Python 中的条件判断和循环是编写程序时经常使用的控制结构。条件判断用于根据不同的条件执行不同的代码块,而循环则用于重复执行一段代码。
### 条件判断
在 Python 中,条件判断使用 `if`、`elif`(可选)和 `else`(可选)关键字。语法如下:
```python
if condition1:
# code block to be executed if condition1 is True
elif condition2:
# code block to be executed if condition2 is True
else:
# code block to be executed if none of the above conditions are True
```
下面是一个示例,演示如何使用条件判断:
```python
x = 10
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
```
在上述示例中,变量 `x` 的值为 10。根据条件判断,`x > 0` 为 True,因此会执行 `print("x is positive")` 这一行代码。
### 循环
Python 中有两种常见的循环结构:`for` 循环和 `while` 循环。
#### for 循环
`for` 循环用于遍历一个可迭代对象(如列表、元组、字符串等)中的元素。语法如下:
```python
for item in iterable:
# code block to be executed for each item in the iterable
```
下面是一个示例,演示如何使用 `for` 循环:
```python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
在上述示例中,`fruits` 是一个列表,包含了三种水果。`for` 循环用于遍历列表中的每个元素,并将其打印出来。
#### while 循环
`while` 循环会在条件为 True 的情况下重复执行一段代码,直到条件变为 False。语法如下:
```python
while condition:
# code block to be executed as long as the condition is True
```
下面是一个示例,演示如何使用 `while` 循环:
```python
count = 0
while count < 5:
print(count)
count += 1
```
在上述示例中,`count` 的初始值为 0。`while` 循环会在 `count < 5` 的条件为 True 时重复执行代码块,并在每次循环中递增 `count` 的值。
这些是 Python 中条件判断和循环的基本用法。通过灵活运用这些控制结构,你可以根据不同的条件执行特定的代码块,或者重复执行某段代码,从而实现更复杂的程序逻辑。