python while
时间: 2023-10-14 16:17:43 浏览: 62
The `while` loop in Python is used to repeatedly execute a block of code as long as a certain condition is true. The basic syntax of a `while` loop in Python is as follows:
```
while condition:
# code to be executed while condition is true
```
Here, the `condition` is a Boolean expression that is evaluated at the beginning of each iteration of the loop. If the condition is true, the code inside the loop is executed. This process continues until the condition evaluates to false.
For example, the following code uses a `while` loop to print the numbers from 1 to 10:
```
num = 1
while num <= 10:
print(num)
num += 1
```
In this example, the `condition` is `num <= 10`. As long as `num` is less than or equal to 10, the loop will continue to execute. Inside the loop, the current value of `num` is printed, and then `num` is incremented by 1 using the `+=` operator.
The output of this code will be:
```
1
2
3
4
5
6
7
8
9
10
```
阅读全文