一.if条件判断
1.根据Python的缩进规则,如果if语句判断是True,就把if的内容执行了,否则,什么也不做。
# 判断值是否为空
value=input('value:')
if value == '':
print('值为空')
# if not value:
# print('值为空')
2.给if添加一个else语句,意思是,如果if判断是False,不要执行if的内容,去执行else
#age=19
age=12
if age >= 18:
print('your age is',age)
print('adult')
else:
print('your age is',age)
print('teenager')
3.if语句的完整格式
if <条件判断1>:
<执行1>
elif <条件判断2>:
<执行2>
elif <条件判断3>:
<执行3>
else:
<执行4>
example:
age=2
if age >=18:
print('adult')
elif age>6:
print('teenager')
else:
print('kid')
二.逻辑运算符
1.and
条件1 and 条件2
两个条件同时满足,就返回True
两个条件有一个不满足,就返回False
python_score=int(input('请输入python考试成绩:'))
if python_score < 60:
print('python考试评分为:D')
elif python_score >= 60 and python_score < 70:
print('python考试评分为:C')
elif python_score >= 70 and python_score < 90:
print('python考试评分为:B')
elif python_score >= 90 and python_score <=100:
print('python考试评分为:A')
else:
print('输入成绩错误')
2.or
条件1 or 条件2
两个条件只要有一个满足,就返回True
两个条件都不满足,返回False
python_score=77
c_score=88
if python_score < 60 or c_score < 60:
print('请准备参加补考')
else:
print('恭喜你通过考试!')
三.if嵌套
If嵌套的格式:
if 条件1:
条件1满足执行的动作
if 满足条件1的基础上的条件2:
...
else:
条件2不满足的情况下
else:
条件1不满足时,执行的动作
example:
have_ticket = True
# have_ticket = False
# knife_length = 16
knife_length = 21
if have_ticket:
print('已有车票,请安检...')
if knife_length > 20:
print('长度为 %d:超出限定长度,禁止入内' %knife_length)
else:
print('长度为 %d:没有超过限定长度,允许入内' %knife_length)
else:
print('请先买票')
四.if语句综合练习
1.判断闰年?
用户输入年份year, 判断是否为闰年?
能被4整除但不能被100整除的 或者 能被400整除 那么就是闰年
2.输入年份和月份,输出本月天数
year = int(input('请输入年份:'))
mouth =int(input('请输入月份:'))
if mouth == 2:
if (year % 4 == 0 and year % 100 != 0 ) or (year % 400 == 0) :
print('本月有29天')
else:
print('本月有28天')
elif mouth == 1 or mouth == 3 or mouth == 5 or mouth == 7 or mouth == 8 or mouth == 10 or mouth == 12:
print('本月有31天')
else:
print('本月有30天')