Python中的if语句
1. if语句
条件成立,只执行条件下缩进的代码,没有缩进的不执行。
小例子
age = int(input('请输⼊入您的年龄: '))
if age >= 18:
print(f'您的年龄是{age},已经成年,可以上网')
print('系统关闭')
需要注意:input()函数的返回值是str类型。与int做比较时要先进行类型转换。
2. if···else···语句
3.多重判断(if···elif···else)
4. if嵌套
if嵌套的执行流程
应用:猜拳游戏
需求分析:
- 参与游戏的角色
- 玩家
- 手动出拳
- 电脑
- 随机出拳
- 玩家
- 判断输赢
- 玩家获胜
- 电脑获胜
- 平局
随机的实现:
- 导入random模块
import random
- 使用random模块中随机整数功能
random.randint(a,b);
例如:
random.randint(0,2);表示随机生成一个整数数字,它的范围是{0,1,2}。
代码实现:
import random
# 生成代表电脑出拳的随机数字
computerOperation = random.randint(0,2)
print("规则:0--石头,1--剪刀,2--布")
playerOperation = int (input("请出拳:"))
# 玩家获胜 p0:c1 或 p1:c2 或 p2:c0
if((playerOperation == 0) and (computerOperation == 1) or (playerOperation == 1)
and (computerOperation == 2) or (playerOperation == 2) and (computerOperation == 0)):
print("玩家获胜")
# 平局 玩家 == 电脑
elif playerOperation == computerOperation:
print("平局")
else:
print("电脑获胜")
print(f"电脑出的是:{computerOperation},玩家出的是:{playerOperation}")
*三目运算符
语法:
条件成立的执行表达式 if 条件 else 条件不成立执行的表达式
上手体验:
a = 1
b = 2
c = a if a >b else b
# 以上条件不成立,把 b 赋值给 c
print(c) # 2