(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))

猜你喜欢

转载自blog.csdn.net/weixin_44214830/article/details/89017749
今日推荐