【问题标题】:How to link two paths in Python 3? [closed]如何在 Python 3 中链接两条路径? [关闭]
【发布时间】:2018-08-10 05:09:59
【问题描述】:

好的,所以我的 python 代码中有两个单独的路径,我需要将它们链接在一起以避免两次输入我的游戏的其余部分并浪费空间和代码。

如您所见,最后四行左右相同,但有两个不同的缩进。我怎样才能让它们都一样?所以不必写出来:

print('''You carefully wrap the material around your head, wincing in pain everytime your hand bumps the wound.''')
print('''You wonder what the wound was from. It is unimportant however as the bleeding seems to be slowing.''')

两次,我只需要写一次。

【问题讨论】:

  • 请粘贴您的代码,而不是您的代码图像!
  • 我有一个问题,为什么你在接受输入之后打破循环然后处理相同的输入?
  • 编程中有一个重要的原则,称为 DRY 代码。 en.wikipedia.org/wiki/Don%27t_repeat_yourself 您的代码重复次数过多。你应该阅读更多关于函数的内容。

标签: python python-3.x


【解决方案1】:

使用函数:

def rip_and_bandage():
    print('''You carefully wrap the material around your head, wincing in pain everytime your hand bumps the wound.''')
    print('''You wonder what the wound was from. It is unimportant however as the bleeding seems to be slowing.''')

【讨论】:

    【解决方案2】:

    在这种特殊情况下,您可以为yeet_bleed 指定默认值。例如

    yeet_bleed = 0
    # Some input to yeet_bleed here
    if bleeding_heal == '1' or yeet_bleed == '1':
        print('something')
    

    while True 循环的另一个建议:

    while bleeding_heal not in ['1','2','3']:
        bleeding_heal = input("some text:")
    

    【讨论】:

      【解决方案3】:

      在每个路径之后对公共函数进行函数调用,或者在函数中编写路径代码,一旦函数返回,您的公共代码块就会被执行。

      尽量不要使用多个和嵌套的if,会使代码混乱-使用句柄功能-解决方案如下:

      What's an alternative to if/elif statements in Python?

      【讨论】:

        猜你喜欢
        • 2012-02-25
        • 2016-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-05
        • 1970-01-01
        • 2010-10-31
        相关资源
        最近更新 更多