一.逻辑运算符
1.and
条件1 and 条件2
两个条件同时满足,就返回True
只要有一个条件不满足,就返回False
a = int(input('输入你的成绩:'))
if a >= 60 and a <= 100:
print('successfully!!')
else:
print('sorry!!')
2.or
条件1 or 条件2
两个条件只要有一个满足,就返回True
两个条件都不满足的时候,就返回False
a = int(input('输入你的英语四级成绩:'))
b = int(input('输入你的英语六级成绩:'))
if a >= 425 or b >= 425:
print('恭喜你考试通过!!')
else:
print('请继续努力!!')
二.if语句
1.if语句的结构
(1)语法1
if 要判断的条件(True):
条件成立的时候,要做的事情
else:
条件不成立的时候要做的事情
(2)语法2(嵌套)
if 要判断的条件(True):
条件成立的时候,要做的事情
elif 要判断的条件(True):
…
elif 要判断的条件(True):
…
else:
条件不成立的时候要做的事情
a = int(input('请输入你的成绩:'))
if a >= 90:
print('您的成绩等级为A!!')
elif 70 <= a < 90:
print('您的成绩等级为B!!')
else:
print('您的成绩等级为C!!')
2.if语句的应用
(1)需求:
从控制台输入要出的拳 —石头(1)/剪刀(2)/布(3)
电脑随即出拳
比较胜负
石头 胜 剪刀
剪刀 胜 布
布 胜 石头
import random ##Python的第三方模块,可以获取随机数,在使用时上限必须大于下限
Player = int(input('请输入你的拳:--石头(1)/剪刀(2)/布(3)'))
Computer = random.randint(1,3)
print('Player:%d Computer:%d' %(Player,Computer))
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, 判断是否为闰年?
year能被4整除但是不能被100整除 或者 year能被400整除, 那么就是闰年;
YEAR = int(input('请输入你要检测的年份:'))
if ((YEAR%4 == 0 and YEAR%100 != 0) or
(YEAR%400 == 0)):
print('%d年是闰年' %(YEAR))
else:
print('%d年是平年' % (YEAR))
(3)随机选择一个三位以内的数字作为答案。用户输入一个数字,程序会提示大了或是小了
import random
a = int(input('Please input a number:'))
computer = random.randint(0,100)
print('a:%d computer:%d' %(a,computer))
if a > computer:
print('%d is big' %(a))
elif a == computer:
print('%d is equal' %(a))
else:
print('%d is small' %(a))
(4)用 if 判断输入的值是否为空?如果为空,报错Error
value = input('value:')
if not value:
print('Error:Please input a value!!')
else:
print('YES!!')
(5)根据用于指定月份,打印该月份所属的季节。
提示: 3,4,5 春季 6,7,8 夏季 9,10,11 秋季 12, 1, 2 冬季
mouth = int(input('请输入月份:'))
if ((mouth == 3) or (mouth == 4) or (mouth == 5)):
print('%d月是春天' %(mouth))
elif ((mouth == 6) or (mouth == 7) or (mouth == 8)):
print('%d月是夏天' %(mouth))
elif ((mouth == 9) or (mouth == 10) or (mouth == 11)):
print('%d月是秋天' % (mouth))
else:
print('%d月是冬天' % (mouth))
(6) 输入年、月,输出本月有多少天。合理选择分支语句完成设计任务。
输入样例1:2004 2
输出结果1:本月29天
输入样例2:2010 4
输出结果2:本月30天
year = int(input('请输入年份:'))
mouth = int(input('请输入月份:'))
if ((year%4 == 0 and year%100 != 0) or (year%400 == 0)):
if mouth == 2:
print('%d年的%d月是29天' %(year,mouth))
elif ((mouth == 1) or (mouth == 3) or (mouth == 5) or (mouth == 7) or (mouth ==8) or (mouth == 10) or (mouth == 12)):
print('%d年的%d月是31天' %(year,mouth))
else:
print('%d年的%d月是30天' % (year, mouth))
else:
if mouth == 2:
print('%d年的%d月是28天' %(year,mouth))
elif ((mouth == 1) or (mouth == 3) or (mouth == 5) or (mouth == 7) or (mouth ==8) or (mouth == 10) or (mouth == 12)):
print('%d年的%d月是31天' %(year,mouth))
else:
print('%d年的%d月是30天' % (year, mouth))