Python之if语句(综合练习)

if 语句综合练习

练习1:猜拳游戏

需求:

1.从控制台输入你要出的拳 ---石头(1)/剪刀(2)/布(3)
2.电脑机出拳
3.比较胜负

代码:

# 导入生成随机数的模块
import random

# 1.从控制台输入要出的拳

# 接收用户输入,int表示强制转换为整型
person = int(input('请输入你要出的拳(石头1/剪刀2/布3):'))

# 2.电脑机出拳

# 生成1-3的随机数
computer = random.randint(1,3)
print('电脑出的拳为:%s'  %computer )

# 3.比较胜负

if (person == 1 and computer == 2 ) \
    or (person == 2 and computer == 3 ) \
    or (person == 3 and computer == 1):
    print('玩家胜利~')
elif person == computer:
    print('平局')
else:
    print('玩家失败~')

运行结果:
在这里插入图片描述
练习2:判断闰年

需求:

用户输入年份,判断是否为闰年?
提示:能被400整除的是闰年,能被4整除但是不能被100整除的是闰年

代码:

year = int(input('Year:'))

if (year % 400 == 0) or (year % 4 == 0 and year % 100 !=0):
    print('%s是闰年' %year)
else:
    print('%s不是闰年' %year)

运行结果:
在这里插入图片描述
练习3:判断某月有多少天

需求:

输入年,月,输出本月有多少天

例如:
  2004 2
  29天
  2010 4
  30天

分析:
 2 月: 闰年的2月:29天,平年的2月:28天
 1,3,5,7,8,10,12 月: 31天
 4,6,9,11 月: 30天

注:能被400整除的是闰年,能被4整除但是不能被100整除的是闰年

代码:

# 接收从控制台输入的年份和月份
year = int(input('year:'))
month = int(input('month:'))

# 判断年份是否为闰年
if (year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)):
    # 判断月份
    if(month == 2):
        print('%s年-%s月 有29天' %(year,month))
    elif(month == 4 or month == 6 or month == 9 or month == 11 ):
        print('%s年-%s月 有30天' %(year,month))
    else:
        print('%s年-%s月 有31天' %(year,month))
else:
    if (month == 2):
        print('%s年-%s月 有28天' % (year, month))
    elif (month == 4 or month == 9 or month == 11):
        print('%s年-%s月 有30天' % (year, month))
    else:
        print('%s年-%月 有31天' % (year, month))

运行结果:
在这里插入图片描述
练习4:判断某个月份属于哪个季节

需求:

用户输入月份,打印该月份所属的季节
提示: 3,4,5春季  6,7,8夏季  9,10,11秋季 12,1,2冬季

代码:

month = int(input('month:'))
if month == 3 or month == 4 or month == 5:
    print('%s月属于春季' %month)
elif month == 6 or month == 7 or month == 8:
    print('%s月属于夏季' %month)
elif month == 9 or month == 10 or month == 11:
    print('%s月属于秋季' % month)
else:
    print('%s月属于冬季' %month)

运行结果:
在这里插入图片描述

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值