cdchenli 发表于 2018-8-14 06:15:19

python入门——条件语句、for、while循环4

一、if语句

[*]条件测试
  每条if语句的核心都是一条值为false或True的表达式,这种表达式称为条件测试python根据条件测试的结果决是否执行后面的代码;
  检查是否相等
  >>> name = 'Woon'
  >>> name == 'Woon'
  True
  >>> name == 'xi'
  False
  检查是否相等时需要考虑大小写,如果大小写不重要可以用lower()进行转换;
  >>> name == 'woon'
  False
  检查是否不等
  >>> name != 'woon'
  True
  >>> name != 'Woon'
  False
  >>>
  比较数字
  >>> num = '30'
  >>> num == '30'
  True
  >>> num == '3.0'
  False
  >>> num != '30'
  False
  检查多个条件
  >>> num1 = 18
  >>> num2 = 60
  >>> num1 > 30 and num2 < 70
  False
  >>> num1 <25 and num2 >43
  True
  >>> num > 30 or num2 <70
  >>> num1 >30 or num2 <70
  True
  检查值是包含在列表中
  num_list =
  num1 =6
  if num1 in num_list:
  print("sad" + num1)
[*]if语句
  if语句是一个简单的判断;
  age = 19
  if age > 18:
  print("你可以看yellow movies")
3、if-else语句
  if语句根据判断结果返回值决定执行那些代码;
  age = 17
  if age > 18:
  print("你可以看yellow movies")
  else:
  print("你可以在等" + str(18-age) + "年去看")

[*]if-elif-else语句
  #int()来获取输入的数字为整型而不是字符串;
  age = int(input("请输入你的年龄:"))
  if age < 18:
  print("你可以看yellow movies")
  elif age > 60:
  print("专心带孙子吧")
  else:
  print("你可以在等" + str(18-age) + "年去看")
  该语句中可以使用多个elif语句进行判断分支当满足分支条件时,便执行该分支代码;并且可以省略最后的else语句(其实最后的else是用elif代替了);
二、while循环
1、简单循环
  while语句循环需要设置循环结束条件,如果不设置会一直执行下去;
  age = 1
  while age <= 3:
  print("吃奶去!" + str(age) + "岁小孩!")
  age += 1
2、使用标识
  while循环使用标识来退出循环或者结束程序
  while True:
  age = input("请输入你的年龄:")
  if age == '3':
  print("吃奶去!" + str(age) + "岁小孩!")
  elif age == '22':
  print("原来是个二货")
  elif age == '38':
  print("原来是个三八")
  elif age == '40':
  continue
  elif age == '44':
  break
  else:
  print("那啥?咋说!")
3、while循环处理字典
  dict_name = {}
  active = True
  while active:
  name = input("请输入你的名字:")
  sex= input("请输入你的性别")
  if sex == 'male' or sex == 'feimale':
  dict_name = sex
  else:
  print("不男不女的,请去泰国")
  if name == "no":
  active = False
  for name,sex in dict_name.items():
  print(name + sex)
  print(dict_name)
页: [1]
查看完整版本: python入门——条件语句、for、while循环4