(2)Python——逻辑运算符和if语句

1.条件判断

if 要判断的条件:
     条件成立时,要做的事
age = 18
if age >= 18:
    print('你已经成年了')

 

age = 12
if age >= 18:
    print('你已经成年.')
else:
    print('你未满18岁')

2.if语句嵌套

if 要判断的条件:
    条件成立时,要做的事情
elif  条件2:
    要做的事情
else:
    条件不成立时,要做的时请

注意:elif和else都必须和if联合使用,不能单独使用

3.逻辑运算符

1)and
条件1 and 条件2
两个条件同时满足,就返回True
两个条件有一个不满足,就返回False

age=44 
if age >= 0 and age <=120:
     print('年龄正确')
 else:
     print('年龄错误')


2)or:

条件1 or 条件2
两个条件只要有一个满足,就返回True
两个条件都不满足,返回False

 python_score = 61
 c_score = 30

 if python_score > 60 or c_score > 60:
     print('考试通过')
 else:
     print('您未通过考试')

4.综合应用

1)石头剪刀布

import random  #随机数模块导入

#1.输入要出的拳:石头=1 剪刀=2 布=3
player = int(input("请输入您要出的拳: 石头1/剪刀2/布3 :"))

#2.电脑随机出拳
computer = random.randint(1,3)
print(computer)

#3.比较胜负
if ((player == 1 and computer == 2)
    or (player == 2 and computer == 3)
    or (player == 3 and computer == 1)):
    print('玩家胜利~')
elif player == computer:
    print('平局')
else:
    print('玩家失败~')

2)判断闰年

year = int(input("请输入您要判断的年份:"))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print("%s年是闰年" %year)
else:
    print("%s年不是闰年" %year)

3)输入年、月,输出本月有多少天

year = int(input("请输入一个年份:"))
month = int(input("请输入一个月份:"))
if month == 2:
    if 0 == year % 400 or (0 == year % 4 and 0 != year % 100):
        day = 29
        print('%s年%s月有:%s天' % (year, month, day))
    else:
        day = 28
        print('%s年%s月有:%s天' % (year, month, day))
elif month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
    day = 31
    print('%s年%s月有:%s天' % (year, month, day))
elif month == 4 or month == 6 or month == 9 or month == 11:
    day = 30
    print('%s年%s月有:%s天' % (year, month, day))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

马克图布s

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值