练习31 源代码
print("""You enter a dark room with two doors.
Do you go through door #1 or door #2?""")
door = input("> ") #输入选择
if door == "1": #如果变量door等于1
print("There's a giant bear here eating a cheese cake.")
print("What do you do?")
print("1.Take the cake.")
print("2.Scream at the bear.")
bear = input("> ") #输入字符串
if bear == "1": #如果door==1且bear==1时,条件成立
print("The bear eats your face off. Good job!")
elif bear == "2": #如果door==1且bear==2时,条件成立
print("The bear eats your legs off. Good job!")
else: #如果door==1且bear不等于1且不等于2时,条件成立
print(f"Well, doing {bear} is probably better.")
print("Bear runs away.")
elif door == "2": #如果变量door等于2成立
print("You stare into the endless abyss at Cthulhu's retina.")
print("1.Blueberries.")
print("2.Yellow jacket clothespins.")
print("3.Understanding revolvers yelling melodies.")
insanity = input("> ") #输入字符串
if insanity == "1" or insanity == "2": #如果door等于2成立,且变量insanity等于1或者等于2成立
print("You body survives powered by a mind of jello.")
print("Good jobs!")
else: #以上条件都不成立时
print("The insanity rots your eyes into a pool of muck.")
print("Good job!")
else: #door不等于1也不等于2时,成立
print("You stumble around and fall on a knife and die. Good job!")
输出结果
You enter a dark room with two doors.
Do you go through door #1 or door #2?
> 1
There's a giant bear here eating a cheese cake.
What do you do?
1.Take the cake.
2.Scream at the bear.
> 2
The bear eats your legs off. Good job!
知识点:
- if 语句写出分支语句
附加练习
1&2.(一二相似,选择做第二题)写一个完全不同的新游戏。可能你不喜欢我的这个,你可以做一个你自己的。
输入代码:
print("""
Welcome to the Game world!
There are two doors in front of you.
So, which door do you want to choose?""" )
door = input("input the door number: ")
if door == "1":
print("You get two dollars.")
print("Good job!")
elif door == "2":
print("There are two boxes you can choose!")
print("box#1: a red box.")
print("box#2: a yellow box.")
box = input("Please, Choose a box > ")
if box == "1":
print("You get one dollars.")
print("Good!")
elif box == "2":
print("You get Ten dollars.")
print("Excellent!")
else:
print("Game over!")
else:
print("You don't get anything.")
输出结果:
Welcome to the Game world!
There are two doors in front of you.
So, which door do you want to choose?
input the door number: 2
There are two boxes you can choose!
box#1: a red box.
box#2: a yellow box.
Please, Choose a box > 2
You get Ten dollars.
Excellent!
常见问题
- 我能用一系列的 if 语句来代替 elif 吗?
在某些情况下可以,但是取决于每个 if/else 是怎么写的。如果这样的话还意味着 Python 将会检查每一个 if-else 组合,而不是像 if-elif-else 组合那样只会检查第一个是 false 的。你可以多试几次,感受一下区别。
具体可查看练习30中if-else和if-elif-else的区别。 - 如何表示一个数字的区间?
有两种方式:一种是 0 < x < 10 或者 1 <= x < 10 这种传统表示方法,另一种是 x 的区间是 (1, 10)。 - 如果想在 if-elif-else 代码块中放更多的选择怎么办?
为每种可能的选择增加更多的 elif 块。