【问题标题】:Character creator in Python issuePython问题中的角色创建者
【发布时间】:2016-02-14 20:07:02
【问题描述】:

我在解决帽子似乎是一个非常基本的问题时遇到了严重的麻烦,我不知道为什么它不起作用。

基本上,我正在为基于文本的游戏制作角色创建器,其中有一部分您需要从三种角色类型中选择一种。但是,如果我输入正确或不正确的字符类型,它仍然只是让我选择再次输入。

我正在使用 python 3.2

def choose_mech_type():
    mecha_type = input("""
Choose mecha type:
Marine
Flight
Ground
""")

    if mecha_type == ("marine"):
        head = ("m.head.basic")
        body = ("m.body.basic")
        back = ("m.back.basic")
        arms = ("m.arms.basic")
        hands = ("m.hands.basic")
        legs = ("m.head.basic")
        feet = ("m.feet.basic")

    if mecha_type == ("flight"):
        head = ("f.head.basic")
        body = ("f.body.basic")
        back = ("f.back.basic")
        arms = ("f.arms.basic")
        hands = ("f.hands.basic")
        legs = ("f.head.basic")
        feet = ("f.feet.basic")

    if mecha_type == ("ground"):
        head = ("g.head.basic")
        body = ("g.body.basic")
        back = ("g.back.basic")
        arms = ("g.arms.basic")
        hands = ("g.hands.basic")
        legs = ("g.head.basic")
        feet = ("g.feet.basic")

    if mecha_type != ("ground") or ("marine") or ("flight"):
        choose_mech_type()

【问题讨论】:

    标签: python python-3.2


    【解决方案1】:

    代码的主要问题是以下行总是正确的:

    if mecha_type != ("ground") or ("marine") or ("flight"):
    

    检查这个逻辑的正确方法是:

    if mecha_type not in ["ground", "marine", "flight"]:
    

    另一个主要问题是,一旦进入 if 语句,就会递归调用该函数。而不是这样做,您应该使用一个在有有效输入时退出的循环。

    def choose_mech_type():
        while True:     
            mecha_type = input("""
    Choose mecha type:
    Marine
    Flight
    Ground
    """)
            if mecha_type in ["ground", "marine", "flight"]:
                return mecha_type
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      • 2018-03-01
      相关资源
      最近更新 更多