python中while循环和for循环的用法
时间: 2023-10-21 08:05:46 浏览: 60
Sure, I'd be happy to help you with that! In Python, while loops are used to repeatedly execute a block of code while a particular condition is true. For example:
```
i = 0
while i < 10:
print(i)
i += 1
```
This code will print the numbers 0 through 9, because the condition `i < 10` is true 10 times. The `i += 1` statement is important, because otherwise the loop would never end.
On the other hand, for loops are used to iterate over a sequence (like a list, tuple, or string) and execute a block of code for each item in the sequence. For example:
```
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
This code will print the strings "apple", "banana", and "cherry", each on its own line. The `fruit` variable takes on the values in `fruits` one at a time, and the `print(fruit)` statement is executed for each one.
I hope that helps! Let me know if you have any other questions.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)