笨方法学python3怎么样_练习 31 - 做决定 - 笨办法学Python3

练习 31 做决定

在这本书的前半部分你主要学习了调用函数、打印东西,但是这些基本都是直线运行下来的。你的脚本从上面开始运行,然后到底部结束。如果你用了一个函数,你可以随后再运行它,但是仍然不会有分叉需要你做决定的情况。现在你学习了 if,else,以及 elif,你就可以让脚本来做决定了。

在上个脚本中你写出了一个简单的问问题的测试集。在这个练习中你将问用户一些问题,并基于他们的回答做决定。写下这个脚本,然后多玩几遍,把它弄明白。

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!")

这里很关键的一点是你现在在 if 语句里面又放了一个 if 语句。这在创建“嵌套”(nested)决定的时候非常有用,每一个分支指向另一个选择。

确保你理解了在 if 语句中嵌套 if 语句的理念。你可以通过做附加练习来真正掌握它。

你会看到

这是我玩这个冒险小游戏的结果,我可能玩儿得没那么好。

练习 31 会话

$ python3.6 ex31.py

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 语句来代替 elif 吗?在某些情况下可以,但是取决于每个 if/else 是怎么写的。如果这样的话还意味着 Python 将会检查每一个 if-else 组合,而不是像 if-elif-else 组合那样只会检查第一个是 false 的。你可以多试几次,感受一下区别。

我如何表示一个数字的区间?有两种方式:一种是 0 < x < 10 或者 1 <= x < 10 这种传统表示方法,另一种是 x 的区间是 (1, 10)。

如果我想在 if-elif-else 代码块中放更多的选择怎么办?为每种可能的选择增加更多的 elif 块。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值