1.6 KiB
1.6 KiB
条件语句
- 正常写法
a = 20
b = 10
if a==b:
print("a == b")
elif a < b:
print("a < b")
else:
pring("a > b")
- 简写一行if
a = 20
b = 10
if a > b: print("a > b")
- 简写一行if else
a = 20
b = 10
print("A") if a > b else print("B")
- pass 语句,空if处理
a = 66
b = 200
if b > a:
pass
and or
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 开始下一次循环
i = 1
while i < 7:
print(i)
if i == 3:
break
i += 1
i = 0
while i < 7:
i += 1
if i == 3:
continue
print(i)
- else语句,条件不成立,执行else语句
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
for 循环
- break
- continue
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(默认地),并以指定的数字结束
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语句
for x in range(10):
print(x)
else:
print("Finally finished!")
- pass语句
for x in [0, 1, 2]:
pass