The loop technique in Python
In this Python lesson, you'll learn how to control the execution of a loop using loop control statements like break and continue.
Python programming language provides 2 types of loops, for loops and while loops. Use these loops together with loop control statements like break
and continue
you can create different types of loops. We'll learn about these Python loops below.
Infinite loop in Python
It is possible to create infinite loops in Python using while. When the while
loop condition always True
, you get an infinite loop.
To get rid of an infinite loop in Python, use Ctrl + C.
Example of while using infinite loop:
The Python program below requires the user to enter a number and print 3 times the number of that number. The loop is infinite because there are no stopping conditions.
while True:
num = int(input("Nhập một số: "))
print("Gấp ba của",num,"là",3 * num)
The result when running the above code is:
Nhập một số: 3
Gấp ba của 3 là 9
Nhập một số: 5
Gấp ba của 5 là 15
Nhập một số: 7
Gấp ba của 7 là 21
Nhập một số: 9
Gấp ba của 9 là 27
Nhập một số: 10
Gấp ba của 10 là 30
Nhập một số:
Traceback (most recent call last):
You just enter Enter will continue to enter the new number and the program will run until you press Ctrl + C.
Python loop with the condition at the beginning
This is a regular repeat, without a break
statement. The while
loop condition will appear at the beginning and end of the loop when this condition is False
.
Python loop diagram provided at the beginning:
Example of a loop with the condition at the beginning:
# Try different numbers by assigning numbers to n
n = 15
# Use the following command if you want users to enter numbers
#n = int (input ("Enter number n:"))
# Initializing and counting variables i
tong = 0
i = 1
while i <= n:
tong = tong + i
i = i + 1 # update count
# Code by TipsMake.com
# in total
print ("Sum of numbers from 1 to", n, "is", tong)
The above program repeats the numbers until the given number n
, sums those numbers and prints them to the screen. After running the program, we get the result:
Tổng các số từ 1 đến 15 là 120
Python loop with conditions in between
This type of loop can be done using an infinite loop associated with the break
statement in the loop block.
Python loop diagram with conditions in between:
Example of a loop with the middle condition:
# Nhận đầu vào từ người dùng cho đến khi họ nhập một nguyên âm nguyenAm = "aeiouAEIOU" # vòng lặp vô hạn while True : m = input ( "Nhập một nguyên âm: " ) # Điều kiện ở giữa khối lệnh if m in nguyenAm : break print ( "Đây không phải là nguyên âm. Hãy thử lại!" ) # Code by TipsMake.com print ( "Chuẩn rồi, cảm ơn bạn!" )
The above program requires the user to enter a vowel, accompanied by a test command to force the user to enter until correct. As long as the user data entered is not vowel until then the loop continues.
After running the program, we get the following results:
Python loop with the condition at the end
This type of loop ensures that the block is executed at least once. It can be done using an infinite loop along with the break
command at the end. This is quite similar to the do.while
loop in C.
Python loop diagram provided at the end:
Example of Python loop with the end condition:
Below we will create a dice program, giving random results to users using a while
loop. The loop will continue until the user chooses to stop.
# Tung xúc xắc cho đến khi người dùng chọn thoát
import random while True : input ( "Nhấn Enter để tung xúc xắc" ) # nhận số mặt xúc xắc bất kỳ từ 1 đến 6 num = random . randint ( 1 , 6 ) print ( "Bạn tung được mặt" , num ) option = input ( "Bạn có muốn tung lại không?(y/n) " ) # điều kiện if option == 'n' : break
When running the program, we get the following result:
Nhấn Enter để tung xúc xắc
Bạn tung được mặt 1
Bạn có muốn tung lại không?(y/n) y
Nhấn Enter để tung xúc xắc
Bạn tung được mặt 4
Bạn có muốn tung lại không?(y/n) n
>>>
So you already know the basic iteration techniques in Python, don't forget to do Python exercises to practice your repetition techniques.
In the next lesson, you will learn about Python functions, syntax and how they work. Do not miss it!
Next lesson: Python functions
Previous post: Pass command in python
You should read it
May be interested
- Loop in programming Csimilar to other programming languages, c also provides us with many control structures and allows you to perform complex parts.
- How to Fix Boot Loop Problems in Windowsafter starting your windows device, you may sometimes experience an infinite boot loop issue (also known as an 'infinite boot loop' error).
- More than 100 Python exercises have solutions (sample code)more than 100 python code examples are shared by guy zhiwehu on github, however, the solution of this series is written on the old python version. following tipsmake.com will be vietnameseized and edited to suit python 3.x to help you learn and practice python.
- What is Loop mail?what is loop mail? to help you with this question, the following article will help you find out what loop mail is.
- Bookmark 5 best Python programming learning websitesif you are a developer or you are studying and want to stick with this industry, learn python to add a highlight in your journey.
- Manage files and folders in Pythonpython also provides a variety of methods to handle various directory-related operations. in this article, we will learn about managing files and directories in python, namely creating folders, renaming folders, listing folders and working with them.
- For ... loop in JavaScriptthe for ... in loop is used to iterate over the properties of an object. when we haven't discussed the object yet, you may not feel comfortable with this loop. but once you understand how objects work in javascript, you will find this loop very useful.
- Loop control in JavaScriptjavascript provides high control to handle loop commands and switch commands. there may be a situation when you need to exit the loop without having to go to its endpoint. there may also be situations when you want to jump over a part of the code block and start the next loop.
- Why Microsoft Loop Can't Compare to Notionmany people have been using notion for brainstorming for years, so it's interesting to see if loop can replace it as they move deeper into the microsoft ecosystem.
- Multiple choice quiz about Python - Part 3today's topic quantrimang wants to challenge you is about file and exception handling in python. let's try the following 15 questions!