Python 控制流程 if条件判断 while循环 continue break pass 三目运算

条件

str = input('请输入成绩:')
try:
    score = int(str)
    if score >= 90:
        print('优秀')
    elif score >= 80:
        print('良好')
    elif score >= 60:
        print('及格')
    else:
        print('不及格')
except:
    print('输入有误')

user = input("请猜拳:请出拳(剪刀/石头/布)")
import random

computer = random.choice(['剪刀', '石头', '布'])
if user == computer:
    print('平局')
elif user == '剪刀' and computer == '布':
    print('你赢了')
elif user == '石头' and computer == '剪刀':
    print('你赢了')
elif user == '布' and computer == '石头':
    print('你赢了')
else:
    print('你输了')

if嵌套

one = ['北京', '上海', '广州', '深圳']
two = ['长沙', '武汉', '郑州', '杭州', '合肥', '福州', '厦门', '南昌', '贵阳', '成都', '西安', '南宁', '海口', '三亚', '重庆', '贵阳', '昆明', '拉萨', '银川', '乌鲁木齐']
where = input("你是哪里人?")
salary_str = input("你的工资是多少?")
salary = int(salary_str)
if where in one:
    if salary >= 10000:
        print('你住在一线城市,你的工资还可以')
    else:
        print('你住在一线城市,你的工资一般')
elif where in two:
    if salary >= 8000:
        print('你住在二线城市,你的工资还可以')
    else:
        print('你住在二线城市,你的工资一般')
else:
    if salary >= 5000:
        print('你住在其他城市,你的工资还可以')
    else:
        print('你住在其他城市,你的工资一般')

三目运算

num = int(input('请输入你猜心中想的的数字是1还是0:'))
num_str = '你猜对了' if num == 1 else print('你猜错了')
print(num_str)

循环

a = 1
while a <= 10:
    print(f'第{a}次')
    a += 1

pass 空语句(占位符)

break 跳出循环

b = 1
while b <= 10:
    if b == 3:
        pass
    elif b == 7:
        break
    else:
        print(f'数字{b}')
    b += 1

continue 跳过本次循环

c = 1
while c <= 10:
    if c == 3:
        c += 1
        continue
    elif c == 7:
        break
    else:
        print(f'数字{c}')
    c += 1

使用循环和条件, 实现100以内的猜数字

import random
num = random.randint(1, 100)
while True:
    guess = int(input('请输入你猜的数字:'))
    if guess == num:
        print('恭喜你猜对了')
        break
    elif guess > num:
        print('猜大了')
    else:
        print('猜小了')

使用循环和条件, 升级石头剪刀布(0-石头, 1-剪刀, 2-布)

caipiao = {0: '石头', 1: '剪刀', 2: '布'}
print(list(caipiao.keys()))
while True:
    user = int(input('请出拳(0-石头, 1-剪刀, 2-布):'))
    computer = random.choice(list(caipiao.keys()))
    if user == computer:
        print(f'平局, 你和电脑都是出的{caipiao[computer]}')
    elif (user == 0 and computer == 1) or (user == 1 and computer == 2) or (user == 2 and computer == 0):
        print(f'你赢了, 电脑出的是{caipiao[computer]}')
    elif (user == 1 and computer == 0) or (user == 2 and computer == 1) or (user == 0 and computer == 2):
        print(f'你输了, 电脑出的是{caipiao[computer]}')
    else:
        print('你输错了')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值