这是一个关于if嵌套的小游戏,使用了if,elif,else来进行不同输入的判断,这里的重点是你可以在“if 语句”内部再放一个“if 语句”。这是一个很强大的功能,可以用来创建嵌套(nested)的决定,其中的一个分支将引向另一个分支的子分支
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 is a gaint bear 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.")
elif bear == '2':
print("The bear eats your leg off.")
else:
print("Maybe this way %s can save your life." %bear)
elif door == '2':
print("You stare into the endless abyss at a game.")
print("1.Jump")
print("2.Walk")
print("3.Fly")
way = input('>')
if way == '1' or way == '2': #注意这里使用了or,后面的也要写成等式的判断
print("You may be dead.")
else:
print("You are safe.")
else: #如果一开始输入的不是1或2,,退出游戏
print("Quit the game.")
运行结果
You enter a dark room with two doors.Do you go through door #1 or door #2?
1
There is a gaint bear eating a cheese cake,what do you do?
1.Take the cake.
2.Scream at the bear.
2
The bear eats your leg off.
You enter a dark room with two doors.Do you go through door #1 or door #2?
2
You stare into the endless abyss at a game.
1.Jump
2.Walk
3.Fly
3
You are safe.
You enter a dark room with two doors.Do you go through door #1 or door #2?
don’t want to play
Quit the game.