一、if 语句
在 python 中,if 语句让你能够检查程序的当前状态,并据此采取相应的措施。
1.if 判断语句格式
if 要判断的条件:
条件成立的时候,要做的事情
…
elif 要判断的条件:
条件成立的时候,要做的事情
…
else:
条件不成立的时候,要做的事情
…
简单示例1:
age.py
age = 18
if age >= 19:
print('age大于19')
else:
print('不满足条件')
python3 age.py
不满足条件
简单示例2:
cars.py
car = input('请输入一个品牌:')
if car == '野马':
print('%s的价格是100万,您想继续了解?' % (car))
elif car == '特斯拉':
print('%s的价格是200万,您想继续了解?' %(car))
else:
print('没有%s的详细价格信息,抱歉' %(car))
python3 cars.py
请输入一个品牌:宝马
没有宝马的详细价格信息,抱歉
python3 cars.py
请输入一个品牌:野马
野马的价格是100万,您想继续了解?
python3 cars.py
请输入一个品牌:特斯拉
特斯拉的价格是200万,您想继续了解?
2.逻辑运算符号
and
条件1 and 条件2
两个条件同时满足,就返回True
只要有一个条件不满足,就返回False
示例:
score.py
score = 100
if score >= 80 and score <= 100:
print('成绩合格')
else:
print('成绩不合格,请继续努力')
python3 socore.py
成绩合格
or
条件1 or 条件2
两个条件只要有一个满足,就返回True
两个条件都不满足的时候,就返回False
示例:
score.py
python_score = 30
c_score = 20
if python_score >= 60 or c_score >= 60:
print('考试合格')
else:
print('考试不合格,请继续努力')
python3 socore.py
考试不合格,请继续努力
3.if not
判断用户输入的值是否为空
value = input('Value:')
if value == '':
print('请输入合法的值!!')
if not value:
print('请输入合法的值!!')
练习题:
需求:
1.从控制台输入要出的拳 —石头(1)/剪刀(2)/布(3)
2.电脑随机出拳
3.比较胜负
石头 胜 剪刀
剪刀 胜 布
布 胜 石头
import random
player = int(input('请输入您的动作 >>> 石头(1)/剪刀(2)/布(3):'))
computer = random.randint(1,3)
print('玩家的动作为%d,电脑的动作为%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('玩家失败,电脑胜利')
需求:
1.判断闰年?
用户输入年份year, 判断是否为闰年?
提示:year能被4整除但是不能被100整除 或者 year能被400整除, 那么就是闰年;
year = int(input('请输入您要判断的年份:'))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print('%s是闰年' %(year))
else:
print('%s不是闰年' %(year))
2.随机选择一个三位以内的数字作为答案。用户输入一个数字,程序会提示大了或是小了,直到用户猜中
import random
number = random.randint(1,100)
while True:
gusses = int(input('请输入一个数字(1~100):'))
if gusses == number:
print('胜利')
elif gusses < number:
print('猜小了')
else:
print('猜大了')
需求:
1.输入年、月,输出本月有多少天。合理选择分支语句完成设计任务。
输入样例1:2004 2
输出结果1:本月29天
输入样例2:2010 4
输出结果2:本月30天
year = int(input('请输入年份:'))
month = int(input('请输入月份:'))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
if month in(1,3,5,7,8,10,12):
print('%s年%s月有31天' %(year,month))
elif month == 2:
print('%s年%s月有29天' %(year,month))
else:
print('%s年%s月有30天' %(year,month))
else:
if month in(1,3,5,7,8,10,12):
print('%s年%s月有31天' % (year, month))
elif month == 2:
print('%s年%s月有29天' % (year, month))
else:
print('%s年%s月有30天' % (year, month))
2.用 if 判断输入的值是否为空?如果为空,报错Error。
value = input('请输入一个值:')
if value == '':
print('Error')
else:
print(value)
3.根据指定月份,打印该月份所属的季节。
提示: 3,4,5 春季 6,7,8 夏季 9,10,11 秋季 12, 1, 2 冬季
month = int(input('请输入月份:'))
if month in(3,4,5):
print('%s月为春季' %(month))
elif month in(6,7,8):
print('%s月为夏季' %(month))
elif month in(9,10,11):
print('%s月为秋季' %(month))
else:
print('%s月为冬季' %(month))