python中if else语句,if函数的使用方法
学习if语句,并输入以下代码以确保其正常工作: 人员=20
cats=30
dogs=15
if people cats:
打印' too many cats! The world is doomed!'
if people cats:
打印' not many cats! The world is saved!'
if people dogs:
print 'The world is drooled on!'
if people dogs:
print 'The world is dry!'
dogs =5
if people=dogs:
print ' peoplearegreaterthanorequaltodogs.'
if people=dogs:
print ' peoplearelessthanorequaltodogs.'
if people==dogs:
print 'People are dogs.'
执行结果root @ he-desktop :~~/my stuff # python ex 29.pytoomanycats! The world is doomed!
The world is dry!
peoplearegreaterthanorequaltodogs。
People are less than or equal to dogs。
人员阵列文档。
加分练习
通过以上的练习,我们自己推测if语句的作用,用自己的话回答以下问题。
1 .你认为if对其下的代码做了什么?
如果判断为True,则执行下面的代码,否则不执行。
2 .为什么if下的代码要缩进四个空格?
为了表示这些代码是if判断下包含的代码。
3 .不缩进会发生什么?
显示缩进错误。
4 .第27部分可以用聪明的大雁表达来判断if吗?
改变people、dogs、cats变量的值,看看会发生什么。
答案:
1. if语句下的代码是if的分支。 就像书的章节一样,选择这一章就跳到这里读。 这个if语句就像是说:“聪明的枪判断为True后执行下面的代码,否则跳过这些代码。”
2 .用冒号结束语句是告诉python要开始新的代码段。 缩进四个空格意味着这些代码包含在这个代码段中,与使用函数相同。
3 .如果不缩进,就会出现错误。 python要求冒号后面的语句有缩进。
4 .可以。 另外,复杂的句子也可以。
5 .更改变量值后,判断语句相应地为True或False,输出不同的语句。
比较我的答案和你自己的答案,确保你能理解代码块这个概念。 因为这对下一次练习非常重要。
输入并执行以下代码: 人员=30
cars=40
buses=15
if cars people:
print 'We should take the cars.'
elif cars people:
print 'We should not take the cars.'
else:
print 'We can't dicide.'
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.'
else:
print 'Fine,let's stay home then.'
执行结果root @ he-desktop :~~/my stuff # python ex 30.pyweshouldtakethecars。
Maybe we could take the buses。
Alright,let's just take the buses。