Python3 Loop
# Python3.x Python3 Loop Statements
This chapter will introduce the use of Python loop statements.
Python has two loop statements: `for` and `while`.
The control structure diagram of Python loop statements is shown below:
!(#)
### Loop Control Keywords and Methods
| Keyword / Function | Description | Example |
| --- | --- | --- |
| `for` | Iterative loop, used to traverse a sequence or iterable object | `for i in list:` |
| `while` | Conditional loop, executes while the condition is True | `while x > 0:` |
| `break` | Immediately terminates the current loop | `break` |
| `continue` | Skips the remaining code in the current iteration and proceeds to the next iteration | `continue` |
| `else (loop)` | Executes when the loop terminates normally (not via `break`) | `for i in range(3): ... else: ...` |
| `pass` | Placeholder statement in a loop (no operation) | `for i in range(5): pass` |
| `range()` | Generates a sequence of integers, often used with `for` loops | `range(0, 5)` |
| `enumerate()` | Gets both index and value during iteration | `for i, v in enumerate(list):` |
* * *
## while Loop
The general form of the `while` statement in Python is:
while condition:
statementsβ¦β¦
The execution flowchart is as follows:
!(#)
Execution GIF demonstration:
!(#)
Note the colon and indentation. Also, Python does not have a `do..while` loop.
The following example uses `while` to calculate the sum from 1 to 100:
## Example
#!/usr/bin/env python3
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 to %d the sum is: %d" % (n,sum))
The execution result is as follows:
1 The sum up to 100 is: 5050
### Infinite Loop
We can achieve an infinite loop by setting a condition that never becomes false. Example:
## Example
#!/usr/bin/python3
var = 1
while var == 1 : # The expression is always true
num = int(input("input a number :"))
print("The number you entered is: ", num)
print("Good bye!")
Executing the above script, the output is as follows:
input a number :5
The number you entered is: 5
input a number :
You can use **CTRL+C** to exit the current infinite loop.
Infinite loops are very useful for servers handling real-time client requests.
### while Loop with else Statement
If the condition statement after `while` is false, the `else` block is executed.
The syntax is as follows:
while :
else:
If the `expr` condition is true, the `statement(s)` block is executed. If it is false, the `additional_statement(s)` are executed.
Loop through numbers and check their size:
## Example
#!/usr/bin/python3
count = 0
while count < 5:
print(count, " less than 5")
count = count + 1
else:
print(count, " greater than or equal to 5")
Executing the above script, the output is as follows:
0 less than 5
1 less than 5
2 less than 5
3 less than 5
4 less than 5
5 greater than or equal to 5
### Simple Statement Group
Similar to the syntax of the `if` statement, if your `while` loop body contains only one statement, you can write that statement on the same line as the `while`, as shown below:
## Example
#!/usr/bin/python
flag = 1
while(flag):
print('Welcome to visit!')
print("Good bye!")
**Note:** You can use CTRL+C to interrupt the infinite loop above.
Executing the above script, the output is as follows:
Welcome to visit!
Welcome to visit!
......
YouTip