typora/note/Python/控制语句.md

147 lines
1.6 KiB
Markdown
Raw Normal View History

2024-12-11 21:48:55 -05:00
### 条件语句
- 正常写法
```python
a = 20
b = 10
if a==b:
print("a == b")
elif a < b:
print("a < b")
else:
pring("a > b")
```
- 简写一行if
```python
a = 20
b = 10
if a > b: print("a > b")
```
- 简写一行if else
```python
a = 20
b = 10
print("A") if a > b else print("B")
```
- pass 语句空if处理
```python
a = 66
b = 200
if b > a:
pass
```
### and or
```python
a = 200
b = 66
c = 500
if a > b and c > a:
print("Both conditions are True")
a = 200
b = 66
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
```
### while 循环
- break 终止循环
- continue 开始下一次循环
```python
i = 1
while i < 7:
print(i)
if i == 3:
break
i += 1
```
```python
i = 0
while i < 7:
i += 1
if i == 3:
continue
print(i)
```
- else语句条件不成立执行else语句
```python
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
```
### for 循环
- break
- continue
```python
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
```
- range() 函数:返回一个数字序列,默认情况下从 0 开始,并递增 1默认地并以指定的数字结束
```python
for x in range(10):
print(x)
for x in range(3, 10):
print(x)
for x in range(3, 50, 6):
print(x)
```
- else for循环不满足条件时执行else语句
```python
for x in range(10):
print(x)
else:
print("Finally finished!")
```
- pass语句
```python
for x in [0, 1, 2]:
pass
```