《笨办法学 python3》系列练习计划——31.作出决定

题目

到这里,可以算是一个转折点了。我们之前的练习都是直线型的代码,从头运行到末尾,中间不会有任何分支,那么从今天开始我们的脚本将会有所不同了,利用前面学习的学习的 if , elseelif 语句我们可以创建有判断能力的脚本。

本题,我们将让用户输入一些内容,是我们的脚本根据用户输入的不同做出不同的反应。同时我们需要弄明白它是如何工作的。

新知识

我在上一题不小心已经用了这个知识点——嵌套(nested)。也就是 if 语句中有另一个 if 语句。有了嵌套我们可以让 Python 在一个判断后进入一个分支,而进入的这个分支中还有判断从而可以进入一个子分支。
例如 DIY 一台电脑:

# 首先选 Intel 还是 AMD 的cpu
    # 如果选 Intel 则继续选择是 i9 还是 i7
        # 如果是 i9 我们就围观一下土豪
    # 否则鄙视一下选 i7 的现充
# 否则是 AMD 不知道漏洞是真是假    

加分练习

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




我的答案

31.0 基础练习

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'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 = 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." % bear)

elif 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":
        print("You body survives powered by a mind of jello. Good job!")
        print("The insanity rots your eyes into a pool of muck. Good job!")

    else:
        print("You stumble around and fall on a knife and die. Good job!")

不得不说这游戏就是个坑。哈哈我们运行一下看看
这里写图片描述
果然顺利惨死,Zed 似乎比我玩的开心,他尝试了所有玩法。

回忆一下上一节的一个结论 if 语句如果是假会判定 elif (这货其实是 else + if )如果还是假 则可以继续判定下面的语句,最后都是假的则看看 else 是不是存在。

所以我们去读一下代码会发现,如果只运行一次,我们脚本中的一些部分是不会运行到的,这和我们之前的脚本差异就很明显了,也就是前面说的程序进入了一些分支,而其他的分支如果不满足条件则不会被执行。




返回目录

《笨办法学 python3》系列练习计划——目录

猜你喜欢

转载自blog.csdn.net/aaazz47/article/details/79731185