条件判断
1 #条件判断 2 #输入年龄 根据年龄打印不同的内容。 3 age = 20 4 if age >= 18: 5 print('your age is',age) 6 print('adult') 7 print('-----------------------------------') 8 #根据 python的缩进规则 如果if语句的判断是True就把缩进的两行代码执行。否则什么也不做 9 #也可以添加else语句。如果if语句执行的结果是False执行else里的结果 10 age = 3 11 if age >= 18: 12 print('your age is',age) 13 print('adult') 14 else: 15 print('your age is',age) 16 print('teen') 17 print('-----------------------------------') 18 #也可以做更加详细的判断使用 elif 19 #elif是 else if 的缩写,可以有多个elif 20 age = 3 21 if age >= 18: 22 print('your age is',age) 23 print('adult') 24 elif age >= 6: 25 print('your age is',age) 26 print('teen') 27 else: 28 print('is a kid') 29 print('-----------------------------------') 30 31 #if执行语句有一个特点 从上往下判断。如果某个判断结果是True,那么该判断对应的语句执行后,就忽略剩下的elifhe else 32 age = 20 33 if age >= 6: 34 print('teen') 35 elif age >= 18: 36 print('adult') 37 else: 38 print('kid') 39 print('-----------------------------------') 40 #if判断条件还可以简写 x 可以是非零数值 非空字符串 非空list 就判断为True 否则为False 41 if 3: 42 print('kidd') 43 print('-----------------------------------') 44 if 0: 45 print('000') 46 print('-----------------------------------') 47 48 #条件判断之使用input()读取用户的输入 49 #birth = input('birth:') 50 #if birth < 2000: 51 # print('00前') 52 #else: 53 # print('00后') 54 #报错 55 #birth:2001 56 #Traceback (most recent call last): 57 #File "if.py", line 50, in <module> 58 # if birth < 2000: 59 #TypeError: '<' not supported between instances of 'str' and 'int' 60 #input()返回的数据类型是str,str不能直接和整数比较,必须先把str转换成整数。Python提供了int()函数来完成这件事情: 61 62 #修改后: 63 s = input('birth:') 64 birth = int(s) 65 if birth < 2000: 66 print('00前') 67 else: 68 print('00后') 69 70 #如果不输入数字 会报错 退出程序 71 72 #练习:根据BMI指数判断体重 73 height = 1.75 74 weight = 80.5 75 bmi = 80.5 / (1.75 * 1.75) 76 if bmi < 18.5: 77 print('体重过轻') 78 elif 18.5 <= bmi < 25: 79 print('体重正常') 80 elif 25 <= bmi < 28: 81 print('体重过重') 82 elif 28 <= bmi < 32: 83 print('体重肥胖!该减肥了') 84 else : 85 print('严重肥胖')
运行结果: