python第三天
if语法
-
如果条件成立,则执行代码。
if True: print('条件成立时需执行的代码1') print('条件成立时需执行的代码2') print('条件成立时需执行的代码3') # 下方的print因为和if并列,所以不管条件是否成立都执行 print('此处不管条件是否成立都执行')
-
如果条件成立,则执行代码,否则就执行其它代码
if True: print('条件成立时需执行的代码1') print('条件成立时需执行的代码2') print('条件成立时需执行的代码3') else: print('条件不成立时执行的代码1') print('条件不成立时执行的代码2') print('条件不成立时执行的代码3')
# 让用户输入年龄,系统自动判断是否能运行 age = int(input('请输入你的年龄:')) print(f'你的年龄是{age}') if age >= 18: print('你己成年,可以上网!') else: print('你还未成年,回家读书吧')
-
多重判断语法
if 条件1成立: print('条件成立时需执行的代码1') print('条件成立时需执行的代码2') print('条件成立时需执行的代码3') elif 条件2成立: print('条件不成立时执行的代码1') print('条件不成立时执行的代码2') print('条件不成立时执行的代码3') else: print('以上条件都不成立时执行的代码')
IF嵌套
if 条件1成立:
print('条件1成立时执行的代码1')
print('条件1成立时执行的代码2')
print('条件1成立时执行的代码3')
if 条件2成立:
print('条件2成立时执行的代码1')
print('条件2成立时执行的代码2')
print('条件2成立时执行的代码3')
else:
print('执行条件2不成立时执行的代码')
else:
print('执行条件1不成立时执行的代码')
"""
坐公交车场景:如果出门有带钱的话,则可以上公交车。如果没带钱的话只能走路了。
上车后,如果有空座位的话则可以坐下,如果没有位子的话,就只能站着了。
"""
money = 1
seat = 1
if money == 1:
print('帅哥,请上车。')
if seat == 1:
print('小帅哥,这边有座位,过来坐。')
else:
print('没有空座位,你只能站着了。')
else:
print('不好意思,兄弟,你只能走路跟着哥了')
猜拳游戏--电脑固定出拳
"""
与电脑玩猜拳游戏:
1、自己手动与电脑互相出拳:(电脑先固定出某值) 0--石头,1--剪刀,2--布
2、比较两者的胜负关系:(玩家胜、电脑胜、平局)
"""
# 玩家先出拳
people = int(input('请你选择自己的出拳(0--石头,1--剪刀,2--布):'))
computer = 2
if ((people == 0) and (computer == 1)) or ((people == 1) and (computer == 2)) or ((people == 2) and (computer == 0)):
print('玩家获胜')
elif people == computer:
print('打成平局')
else:
print('电脑获胜')
随机数
import 模块名 #导入random模块
random.randint(开始,结束) # 使用randdom模块中的随机数功能
import random
random.randint(0,2)
猜拳游戏--电脑随机出拳
"""
与电脑玩猜拳游戏:
1、自己手动与电脑互相出拳:(电脑随机) 0--石头,1--剪刀,2--布
2、比较两者的胜负关系:(玩家胜、电脑胜、平局)
"""
import random
# 玩家先出拳
people = int(input('请你选择自己的出拳(0--石头,1--剪刀,2--布):'))
# computer = 2
computer = random.randint(0, 2)
if ((people == 0) and (computer == 1)) or ((people == 1) and (computer == 2)) or ((people == 2) and (computer == 0)):
print('玩家获胜')
elif people == computer:
print('打成平局')
else:
print('电脑获胜')
三目运算符
又叫三元运算符或三元表达式(目的:化简代码量)
语 法:
条件成立执行代码 if 条件 else 条件不成立执行的代码
a = 1
b = 2
c = a - b if a > b else b - a
print(c)
# 有两个数,当变量1大于变量2时,变量1减变量2,如果变量1小于变量2,变量2砬变量1
x = 66
y = 88
z = x - y if x > y else y - x
print(z)