目录
if快速体验
if语法:注意冒号,缩进换行。
if 条件:
条件成立执行的代码1
条件成立执行的代码2
...
# 快速体验if,一定要注意if语句后条件成立执行的代码要带有缩进!
if True:
print('code 1')
print('code 2')
print('code 3') # 没有带缩进的代码不属于if的语句块
if False:
print('code 1')
print('code 2')
print('code 3')
if实例:上网
实例:上网
1、简单版需求:
如果用户年龄大于等于18岁,输出:"已成年,可以上网"
age = 20
if age >= 18:
print('You can enjoy the Internet now')
2、进阶版需求:
用户可以输入自己的年龄,如果用户年龄大于等于18岁,输出:"已成年,可以上网"
# input()输入后默认为字符串类型,本需求需要将数据转换为整型
age = int(input('Please enter your age here: '))
if age >= 18:
print('You can enjoy the Internet now')
if else
if else语法
if 条件:
条件成立执行的代码1
......
else:
条件不成立执行的代码1
......
age = int(input('Please enter your age: '))
if age >= 18:
print(f'Your age is {age}, you can enjoy the Internet now.')
else:
print(f'Your age is {age}, you are not allowed to enter the Internet cafe.')
print('System closed.')
if多重判断-elif
多重判断语法:
if 条件1:
条件1成立执行的代码1
......
elif 条件2:
条件2成立执行的代码1
......
elif ......
......
else:
以上条件都不成立执行的代码
......
实例需求:
如果年龄小于18,为童工,不合法
如果年龄在18和60之间,为合法工作年龄
如果年龄大于60为退休年龄
age = int(input('Please enter your age here: '))
if (1 < age) and (age < 18): # 化简为1 < age < 18
print(f'Your age is {age}, illegal working age.')
elif (18 <= age) and (age <= 60): # 化简为18 <= age <= 60
print(f'Your age is {age}, legal working age.')
elif (60 < age) and (age < 150): # 化简为60 <= age <= 150
print(f'Your age is {age}, retirement age.')
else:
print('Error input!System closed!')
if嵌套
if 条件1:
条件1成立执行的代码
......
if 条件2:
条件2成立执行的代码(此时也满足条件1)
......
实例需求:
如果有钱,就可以上公交车,没有钱不能上公交车
如果上公交车,判断是否有空座位
money, seat = 1, 0 # 1表示有钱和有位置
if money == 1:
print('You can enter the BUS now.')
if seat == 1:
print('You can take a vacant seat on the BUS now.')
else:
print('There have not vacant seat to use now.')
else:
print('You do not have enough money to enter the BUS.')
print('System closed.')
三目运算符
三目运算符:简单的条件运算,
语法:条件成立执行的表达式 if if的条件 else 条件不成立执行的表达式
# 三目运算符实例:当a大于b时输出a,否则输出b
a, b = 1, 2
c = a if a > b else b
print(c)
# 需求:有两个变量aa bb,如果aa大于bb,执行aa - bb;否则,执行bb - aa
aa, bb = 9, 20
cc = (aa - bb) if (aa > bb) else (bb - aa)
print(cc)
if应用-猜拳游戏
需求:
角色:
玩家:手动出拳
电脑:随机出拳,使用import导入随机模块
判断输赢:
玩家获胜
平局
电脑获胜
# 导入随机模块random
import random
print('******FINGER-GUESSING GAME******\n0--scissors\t1--stone\t2--cloth')
user = int(input('Please enter your choice: '))
if (user < 0) or (user > 2):
print('Enter error!System Closed.')
# 调用随机数模块,从0-2取整数包括0和2:random.randint(a, b)从a到b中取整数,包括a和b
computer = random.randint(0, 2)
if computer == 0:
computer_select = 'scissors'
elif computer == 1:
computer_select = 'stone'
else:
computer_select = 'cloth'
# 判断输赢
if ((user == 0) and (computer == 2)) or ((user == 1) and (computer == 0)) or ((user == 2) and (computer == 1)):
print(f'\tComputer: {computer_select}\n\tYou Win!')
elif (user == computer):
print(f'\tComputer: {computer_select}\n\tDraw!')
else:
print(f'\tComputer: {computer_select}\n\tYou Lose!')
print('\tGame Closed.')