【问题标题】:Issues with IF repeating loopsIF 重复循环的问题
【发布时间】:2021-10-03 17:44:41
【问题描述】:

首先,我对使用 python 和编码期进行编码非常陌生。 我在 python 中制作了一个骰子滚轮,它允许用户决定边数以及掷骰子的数量。该代码按预期工作,但每当我进行多次重新滚动并退出时,我都会收到一条错误消息。我已经发布了错误消息的屏幕截图并复制了代码。我非常感谢任何反馈,并感谢您阅读本文。 Error Message

## Roller v2

def Roll2():
    print("""
    [ - - - Welcome to Roller v2! - - - ]
    """)
    sides = int(input("How many sides? : "))
    dice = int(input("How many dice? : "))
    modifier = input("Any Modifiers (Include +/-) : ")

    def roller():
        import random as rand
        from random import choices
        d_inf = range(1, sides+1)
        d_choice = choices(d_inf, k=dice)
        print("""Wowee, you rolled :
        """)
        print(d_choice)
        print(""" """)
        print("Unadded Modifiers : (" + modifier + ")")

        repeat = str(input("Would you like to roll the same dice again? (y/n) : "))

        if repeat in ["y", "Y"]:
            roller()
        elif repeat in ["n", "N"]:
            exit = str(input("Would you like to exit? (y/n) : "))
        
        if exit in ["y", "Y"]:
            print("Goodbye!\n")
        elif exit in ["n", "N"]:
            Roll2()
  
    roller()

【问题讨论】:

  • 请输入错误信息并描述您期望发生的情况。也制作一个minimal reproducible example,例如不要要求用户输入,而是硬编码你得到错误的值
  • 这能回答你的问题吗? Local variable referenced before assignment?
  • @Woodford 我认为这不能回答问题;他在本地使用它,而不是在全球范围内使用它。正如它在约翰戈登的回答中所说,这是由于原始函数在递归调用后继续运行造成的。

标签: python loops if-statement random


【解决方案1】:

这样做:

def roll2():

    print("""
    [ - - - Welcome to Roller v2! - - - ]
    """)
    sides = int(input("How many sides? : "))
    dice = int(input("How many dice? : "))
    modifier = input("Any Modifiers (Include +/-) : ")

    def roller():
        import random as rand
        from random import choices
        d_inf = range(1, sides + 1)
        d_choice = choices(d_inf, k=dice)
        print("""Wowee, you rolled :
        """)
        print(d_choice)
        print(""" """)
        print("Unadded Modifiers : (" + modifier + ")")

        repeat = str(input("Would you like to roll the same dice again? (y/n) : "))

        if repeat in ["y", "Y"]:
            roller()
        elif repeat in ["n", "N"]:
            exit = str(input("Would you like to exit? (y/n) : "))

            if exit in ["y", "Y"]:
                print("Goodbye!\n")

            else:
                roll2()
    return roller()

roll2()

【讨论】:

    【解决方案2】:
    if repeat in ["y", "Y"]:
        roller()
    elif repeat in ["n", "N"]:
        exit = str(input("Would you like to exit? (y/n) : "))
        
    if exit in ["y", "Y"]:
        ...
    

    如果repeat 是“y”,则递归调用roller()。并且当递归调用完成时,原始调用继续执行if exit in 语句,并且在该函数的执行中,变量exit 从未被定义。

    【讨论】:

    • 一种解决方案:只需在函数顶部声明exit = "n"
    • @talfreds 谢谢,确实有效。我仍在学习这些东西,所以一切都会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 2015-09-21
    相关资源
    最近更新 更多