代码缩进方面:具有相同缩进的多行代码属于同一个代码块,不可随意缩进。
注意:代码的缩进为一个 tab
键,或者 4 个空格 —— 建议使用空格
(在 Python 开发中,Tab 和空格不要混用)
(一)if语句
代码:
# 定义布尔型变量 表示是否有车票 a = bool(input("您是否有票乘车?\n")) #定义整型变量,表示刀的长度(刀的长度超过20厘米禁止携带) b = int(input('请您输入您所带刀具长度\n')) if a : print('有票乘车,请您上车安检') #安检时检查刀具,如果超过20厘米不允许上车 if b >= 20: print('您的刀具长度超过20厘米,请您处理') else: print('请您上车') else: print("您没有购票,不能上车")
结果:
您是否有票乘车? True 请您输入您所带刀具长度 55 有票乘车,请您上车安检 您的刀具长度超过20厘米,请您处理
代码:
a = int(input("请输入您的数学成绩:\n")) if a < 60: print('很抱歉您没有及格!') else: if a < 90: print('恭喜您,您及格了!') else: if a <= 100: print('您太过优秀') else: print('这个成绩区间不存在,请您严肃对待这个问题')
结果:
请输入您的年龄:999 Traceback (most recent call last): File "D:/untitled/demo.py", line 806, in <module> assert 20 < a < 100 AssertionError
请输入您的数学成绩: 88 恭喜您,您及格了!
代码:
a = str(input('请输入老年痴呆的基本要素:\n')) if a == '1:记忆力不好': print('您是老年痴呆') else: if a == '2:记不清数字': print('您是老年痴呆') else: if a == '4:记忆力不好': print('您是老年痴呆')
结果:
请输入老年痴呆的基本要素: 2:记不清数字 您是老年痴呆
(二)pass语句
pass 语句是空语句,用于占位。
a = str(input('请输入老年痴呆的基本要素:\n')) if a == '1:记忆力不好': print('您是老年痴呆') else: if a == '2:记不清数字': pass #空语句,占位置,不做任何处理 else: if a == '4:记忆力不好': pass#空语句,占位置,不做任何处理
结果:
请输入老年痴呆的基本要素: 2:记不清数字
(三)assert 语句
assert 用于对一个 bool 表达式进行断言,如果该 bool 表达式为 True,该程序可以继续向下执行;否则程序会引发 AssertionError 错误,目的是让程序在不符合条件时早点奔溃。
代码:
assert 1 == 1 #只有所执行的语句正确才会继续向下执行 assert len(['你好',0,1,2,3,4,5,6,7])<10 a = int(input('请输入您的年龄:')) assert 20 < a < 100 print('您输入的年龄在20到100之间') assert 1 == 1 assert len(['你好',12])<10
结果:
请输入您的年龄:99 您输入的年龄在20到100之间
请输入您的年龄:999 Traceback (most recent call last): File "D:/untitled/demo.py", line 806, in <module> assert 20 < a < 100 AssertionError
(四)逻辑运算
在程序开发中,通常在判断条件时,会需要同时判断多个条件,只有多个条件都满足才会执行后续代码,这时候要用到逻辑运算符(与and、或or、非not)
代码:
age = int(input('请输入你的年龄:')) if age >=0 and age <=120: print('年龄正确') else : print('年龄错误')
结果:
请输入你的年龄:77 年龄正确
代码:
python_score = 50 c_score = 50 # 要求只要有一门成绩 > 60 分就算合格 if python_score > 60 or c_score > 60: print("考试通过") else: print("再接再厉!")
结果:
再接再厉!
代码:
a = True if not a: print('gggg')
(五)elif
代码:
a = str(input('请输入节日名称:\n')) if a == '情人节': print('鲜花') elif a == '生日': print('吃蛋糕吧') elif a == '平安夜': print('吃苹果') else: print('没过节日!你想吃啥?')
结果:
请输入节日名称: 情人节 鲜花