您的位置:首页 > 编程语言 > Python开发

Python学习:if语句

2015-01-20 18:33 316 查看
先举例:
age = 20if age >= 18 :    print 'Adult'elif age < 18 :    print 'Nonage' 
计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。比如,输入用户年龄,根据年龄打印不同的内容,在Python程序中,用
if
语句实现:
[code]age = 20if age >= 18:    print 'your age is', age    print 'adult'
根据Python的缩进规则,如果
if
语句判断是
True
,就把缩进的两行print语句执行了,否则,什么也不做。也可以给
if
添加一个
else
语句,意思是,如果
if
判断是
False
,不要执行
if
的内容,去把
else
执行了:
[code]age = 3if age >= 18:    print 'your age is', age    print 'adult'else:    print 'your age is', age    print 'teenager'
注意不要少写了冒号
:
。当然上面的判断是很粗略的,完全可以用
elif
做更细致的判断:
[code]age = 3if age >= 18:    print 'adult'elif age >= 6:    print 'teenager'else:    print 'kid'
elif
else if
的缩写,完全可以有多个
elif
,所以
if
语句的完整形式就是:
[code]if <条件判断1>:    <执行1>elif <条件判断2>:    <执行2>elif <条件判断3>:    <执行3>else:    <执行4>
if
语句执行有个特点,它是从上往下判断,如果在某个判断上是
True
,把该判断对应的语句执行后,就忽略掉剩下的
elif
else
,所以,请测试并解释为什么下面的程序打印的是
teenager
[code]age = 20if age >= 6:    print 'teenager'elif age >= 18:    print 'adult'else:    print 'kid'
if
判断条件还可以简写,比如写:
[code]if x:    print 'True'
只要
x
是非零数值、非空字符串、非空list等,就判断为
True
,否则为
False
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: