If 语句
elif 关键字是 pythons 示意“如果后面的条件不为真,那么试试这个条件”。
The else keyword catches anything which isn’t caught by the preceding conditions.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
如果只有一条语句要执行,则能够将其与 If 语句放在同一行。
if a > b: print("a is greater than b")
如果只有一条语句要执行,一条用于 If,另一条用于 else,则能够将所有语句放在同一行中
a = 2
b = 330
print("A") if a > b else print("B")
and 关键字是一个逻辑运算符,用于组合条件语句
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
or 关键字是一个逻辑运算符,用于组合条件语句
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
循环语言
while 语句
应用 while 循环,只有条件为 true,咱们就能够执行一组语句。
i = 1
while i < 6:
print(i)
i += 1
应用 break 语句,即便 while 条件为 true,咱们也能够进行循环
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
应用 continue 语句,咱们能够进行以后迭代,而后持续下一个迭代
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
应用 else 语句,当条件不再为真时,咱们能够运行一段代码
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
for 语句
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
for 循环中的 else 关键字指定循环实现时要执行的代码块
for x in range(6):
print(x)
else:
print("Finally finished!")
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
#If the loop breaks, the else block is not executed.
本文由 mdnice 多平台公布