Python入门系列(五)一篇搞懂python语句

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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值