python判断与循环

2019-06-06  本文已影响0人  嗷老板

一、判断语句

  python中的if判断语句与其他语言中的用法相似,可以实现多个条件的判断,if语句的嵌套等功能,具体的使用格式如下:

  if 条件1:
      事件1
  elif 条件2:
      事件2
  elif 条件3:
      事件3
  ...
  else:
      事件n

执行流程:

  score = 77

  if score >= 90 and score <= 100:
    print("本次考试,等级为A")
  elif score >= 80 and score <= 89:
    print("本次考试,等级为B")
  elif score >= 70 and score <= 79:
    print("本次考试,等级为C")
  elif score >= 60 and score <=69:
    print("本次考试,等级为D")
  else:
    print("本次考试,等级为E")

注意:

二、循环语句

1、while

while循环的格式:

  while 条件:
    事件1
    事件2
    ...

示例:

  i = 1
  while i<=5:
    print("第%d次循环"%i)
    i+=1

运行结果:

  第1次循环
  第2次循环
  第3次循环
  第4次循环
  第5次循环

注:
python的循环语句中也有breakcontinue来控制循环的跳出:
  break直接跳出当前循环语句的执行;
  continue跳出本次循环,继续进行下次循环

2、for

  python中的for循环主要用来遍历保存多个数据的变量,如:字符串、数组、元祖、字典等。

for循环的格式:

  for 临时变量 in 列表或者字符串等:
        循环满足条件时执行的代码
  else:
        循环不满足条件时执行的代码

示例:

  name = "python"
  for temp in name:
    print(temp)
  else:
    print("打印完成")

运行结果:


运行结果
上一篇 下一篇

猜你喜欢

热点阅读