笨办法学Python 习题 31: 作出决定

笨办法学Python 习题 31: 作出决定,第1张

概述笨办法学Python 习题 31: 作出决定

这本书的上半部分你打印了一些东西,而且调用了函数,不过一切都是直线式进行的。你的脚本从最上面一行开始,一路运行到结束,但其中并没有决定程序流向的分支点。现在你已经学了if,else,和elif,你就可以开始创建包含条件判断的脚本了。


上一个脚本中你写了一系列的简单提问测试。这节的脚本中,你将需要向用户提问,依据用户的答案来做出决定。把脚本写下来,多多鼓捣一阵子,看看它的工作原理是什么。

# -*- Coding:utf-8 -*-print "You enter a dark room with two doors. Do you go through door #1 or door #2?"door = raw_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 = raw_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 %s is probably better. Bear runs away." % bearelif 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 = range("> ")    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! 数字:%s" % insanityelse:    print "You stumble around and fall on a knife and dIE. Good job! 数字:%s" % door

这里的重点是你可以在“if语句”内部再放一个“if语句”。这是一个很强大的功能,可以用来创建嵌套(nested),其中的一个分支将引向另一个分支的子分支。


你需要理解if语句包含if语句的概念。做一下附加题,确保自己真正理解了它们。

结果:

You enter a dark room with two doors. Do you go through door #1 or door #2?> 1There's a giant bear here eating a cheese cake. What do you do?1. Take the cake.2. Scream at the bear.> 2The bear eats your legs off. Good job!

加分习题

1、为游戏添加新的部分,改变玩家做决定的位置。尽自己的能力扩展这个游戏,不过别把游戏弄得太怪异了。

2、写一个全新的游戏,你可能不喜欢我提供的这个,那么自己写一个玩玩。这是你的电脑,你可以用它做任何自己想做的事情。

常见问题回答

可以用多个 if/else 来取代 elif 吗?

某些情况下可以,但是这个也依赖于每一个if/else是怎么写的 。这也意味着, Python会检查每个if-else的组合,而不是只检查if-elif-else组合中的第一个为假的分支,尝试用两种方式多编写一些代码,以找出他们的不同点。

怎样判断一个数字处于某个值域中?

有两种方法: 一种经典的方式是使用0 < x < 10 或者 1 <= x < 10,另一中方式是使用x in range(1,10)。

怎样用 if/elif/else 区块实现四个以上的条件判断?

为每一个可能的选择增加一个elif 代码块。


总结

以上是内存溢出为你收集整理的笨办法学Python 习题 31: 作出决定全部内容,希望文章能够帮你解决笨办法学Python 习题 31: 作出决定所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1198530.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存