练习31--做决定

一 if语句的嵌套

1 在嵌套的 if 语句结构,可以在一个 if... elif... else 结构里面可有另外一个 if... elif... else 结构。

语法:

 1 if expression1:
 2   statement(s)
 3   if expression2:
 4    statement(s)
 5   elif expression3:
 6    statement(s)
 7   else
 8    statement(s)
 9 elif expression4:
10   statement(s)
11 else:
12   statement(s)

if、elif、else可组成一个整体的条件语句,其中:

  • if是必须有的;
  • elif可以没有,也可以有很多个,每个elif的条件不满足时会进入下一个elif的判断;
  • else可以没有,有的话只能有一个,必须在条件语句的最后,且没有逻辑判断语句。

二 代码及运行结果

1 ex31.py

 1 print("""You enter a dark room with two doors.
 2 Do you go through door #1 or door #2?""")
 3 
 4 door = input(">")
 5 
 6 if door == "1":
 7     print("There's a giant bear here eating a cheese cake.")
 8     print("What do you do?")
 9     print("1. Take the cake.")
10     print("2. Scream at the bear.")
11     
12     bear = input(">")
13     
14     if bear == "1":
15         print("The bear eats your face off.Good job!")
16     elif bear == "2":
17         print("The bear eats your legs off.Good job!")
18     else:
19         print(f"Well,doing {bear} is probably better.")
20         print("Bear runs away.")
21 
22 elif door == "2":
23     print("You stare into the endless abyss at Cthulhu's retina.")
24     print("1.Blueberries.")
25     print("2.Yellow jacket clothespins.")
26     print("3.Understanding revolvers yelling melodies.")
27     
28     insanity = input(">")
29     
30     if insanity == "1" or insanity == "2":
31         print("Your body survives powered by a mind of jello.")
32         print("Good job!")
33     else:
34         print("The insanity rots your eyes into a pool of muck.")
35         print("Good job!")
36 
37 else:
38     print("You stumble around and fall on a knife and die.Good job!")

2 执行结果

PS E:\3_work\4_python\2_code_python\02_LearnPythonTheHardWay> python ex31.py
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 Cthulhu's retina.
1.Blueberries.
2.Yellow jacket clothespins.
3.Underftanding revolvers yelling melodies.
>4
The insanity rots your eyes into a pool of muck.
Good job!
posted @ 2020-07-14 10:56  洛兰123  阅读(169)  评论(0编辑  收藏  举报