Python中if语句

基本语法

if 语句的判断条件可以用>(大于)、<(小于)、==(等于)、>=(大于等于)、<=(小于等于)来表示其关系。
当判断条件为多个值时,可以使用以下形式:

if 判断条件1:
    执行语句1……
elif 判断条件2:
    执行语句2……
elif 判断条件3:
    执行语句3……
else:
    执行语句4……

由于 python 并不支持 switch 语句,所以多个条件判断,只能用 elif 来实现,如果判断需要多个条件需同时判断时,可以使用 or (或),表示两个条件有一个成立时判断条件成功;使用 and (与)时,表示只有两个条件同时成立的情况下,判断条件才成功。

if示例

光看不做假把式,所以语法很简单,我们直接上手做两道例题试试。

  • 判断闰年?用户输入年份year, 判断是否为闰年?
  • 提示:能被4整除但不能被100整除的 或者 能被400整除 那么就是闰年
while True:
    print('Please input year:')
    year = int(input())
    
    if year % 4 == 0 and not year % 100 == 0 or year % 400 == 0:
        print('闰年')
    else:
        print('平年')

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

  • 输入年、月,输出本月有多少天。合理选择分支语句完成设计任务。
    输入样例1:2004 2
    输出结果1:本月29天
    输入样例2:2010 4
    输出结果2:本月30天
# 定义一个判断是否是闰年的函数
def is_LeapYear(year):
    return year % 4 == 0 and not year % 100 == 0 or year % 400 == 0


while True:
    print("请输入某年某月,如:2019-06:")
    date = input()
    date.replace('-', '')
    year = int(date[0:4])
    month = int(date[-2:])
    if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
        print("%d-%d 有 31 天" % (year, month))
    elif month == 4 or month == 6 or month == 9 or month == 11:
        print("%d-%d 有 30 天" % (year, month))
    else:
        if is_LeapYear(year):
            print("%d-%d 有 29 天" % (year, month))
        else:
            print("%d-%d 有 28 天" % (year, month))

测试:
在这里插入图片描述

  • 1.从控制台输入要出的拳 —石头(1)/剪刀(2)/布(3)
    2.电脑随即出拳–先假定电脑只会出石头,完成整体代码功能
    3.比较胜负
    石头 胜 剪刀
    剪刀 胜 布
    布 胜 石头
import random
while True:
    computerInt = random.randint(1, 3)
    print("石头:1   剪刀:2   布:3")
    print("请输入以上数字中任意一个代表你的猜拳:")
    playerInt = int(input())
    if (playerInt == 1 and computerInt == 2) or (playerInt == 2 and computerInt == 3) or (
            playerInt == 3 and computerInt == 1):
        print("你赢了!")
    elif playerInt == computerInt:
        print('平局!')
    else:
        print('你输了!')

测试:在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值