age = 20 if age >= 18: print(‘your age is ‘,age) print(‘if 判断语句是true‘) 结果: your age is 20 if 判断语句是true
age = 20 if age >= 18 and age < 19: print(‘your age is ‘,age) print(‘if 判断语句是true‘) else: print(‘your age is ‘,age) print(‘if 判断语句是False‘) 输出结果: your age is 20 if 判断语句是False
age = 20 if age >= 18: print(‘your age is ‘,age) print(‘if 判断语句是true‘) else: print(‘your age is ‘,age) print(‘if 判断语句是False‘) 输出结果: your age is 20 if 判断语句是true
elif
是else if
的缩写,完全可以有多个elif
,所以if
语句的完整形式就是:
if <条件判断1>: <执行1> elif <条件判断2>: <执行2> elif <条件判断3>: <执行3> else: <执行4>
eg:
age = 20 if age >= 18 and age < 19: print(‘your age is ‘,age) print(‘if 判断语句是true‘) elif age < 20: print(‘your age is ‘,age) print(‘if 判断语句是False,elif判断语句是True‘) else: print(‘your age is ‘,age) print(‘if 判断语句是False,elif判断语句是False‘) 输出结果: your age is 20 if 判断语句是False,elif判断语句是False
if
语句执行有个特点,它是从上往下判断,如果在某个判断上是True
,把该判断对应的语句执行后,就忽略掉剩下的elif
和else
,所以,请测试并解释为什么下面的程序打印的是teen
:age = 20 if age >= 6: print(‘teen‘) elif age >= 18: print(‘adult‘) else: print(‘kid‘)
结果:
teen
一下几种的布尔值都为False:
None、False(布尔型)、所有的值为0的数、0(整型)、0.0+0.0j(复数)、""(空字符串)、[](空列表)、{}(空元组)、()(空字典)
补充:for循环里面也可以用break,continue
验证用户三次登录,
原文:http://www.cnblogs.com/ylqh/p/6376264.html