习题 30: Else 和If
目标与感悟:
•Python的规则里,只要一行以“冒号(colon)”:结尾,它接下来的内容就应该有缩进。
•Python只会运行它碰到的是True的第一个区块
ex30.py
#-*-coding:utf-8-*-
#下面出现了elif和else语句,它们都属于子句,无法独立运行,都是出现在if语句内部的
#if 如果的意思
#elif,else if 的缩写,否则如果的意思
#else,否则的意思
people = 30
cars = 40
buses = 15
#这里其实只有3种情况,大于、小于、否则(等于)
if cars > people:
print "We should take the cats."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
if buses > cars:
print "That's too many buses."
elif buses < cars:
print "Maybe we could take the buses."
else:
print "We still can't decide."
if people > buses:
print "Alright, let's just take the buses."

本文是个人学习《笨办法学Python》的笔记,主要探讨了Python中的if条件语句,包括elif和else的使用。强调Python中冒号后的代码块需要缩进,且程序会执行遇到的第一个为True的条件区块。
最低0.47元/天 解锁文章
1134





