发布时间:2017-11-15 15:51:30编辑:Run阅读(5087)
多实践,多练习
练习代码如下:
# coding: utf-8
__author__ = 'www.py3study.com'
print("You enter a dark room with two doors.Do you go through door #1 or door #2 ?")
door = input(">>")
if door == '1':
print("There's a giant bear here eating a cheese cake. What do you do ?")
print("1. Take the cake.")
print("2. Scream at the bear.")
bear = input(">>")
if bear == '1':
print("The bear eats your face off. Good job!")
elif bear == '2':
print("The bear eats your legs off. Good job!")
else:
print("Well, doing {} is probably better. Bear runs away.".format(bear))
elif door == '2':
print("You stare into the endless abyss at Cthulhu's retina.")
print("1. Blueberries.")
print("2. Yellow jacket clotherpins.")
print("3. Understanding revolvers yelling melodies.")
insanity = input(">>")
if insanity == '1' or insanity == '2':
print("Your body survives powered by a mind of jello. Good job !")
else:
print("The insanity rots your eyes into a pool of muck. Good job !")
else:
print("You stumble around and fall on a knife and die. Good job !")
这里的重点是你可以在"if语句"内部再放一个“if语句”,这是一个很强大的功能,可以用来创建嵌套(nested)的决定,其中的一个分支将引向另一个分支的子分支
应该看到的结果
上面的列子有更多的选择,这里就不演示了
常见问题
可以用多个if/else来取代elif吗?
有时候可以,不过这也取决于if/else是怎么样写的。而且这样一来python就需要去检测每一处if/else,而不是像if/elif/else一样,只需要检查到第一个True就可以停下来了
怎么判断一个数字处于某个值域中?
两个办法:经典语法是使用1<x<10,或者用x in range(1,10)也可以
怎样用if/elif/else区块实现四个以上的条件判断?
简单,多写几个elif区块就可以了
上一篇: 习题27:if和else
下一篇: 习题29:循环和列表
47604
45984
36909
34467
29079
25713
24565
19714
19245
17756
5564°
6155°
5690°
5737°
6704°
5483°
5484°
5988°
5965°
7295°