【问题标题】:Name Error in python from function来自函数的python中的名称错误
【发布时间】:2017-06-27 21:39:44
【问题描述】:

我这里有一个代码,它使用函数来绘制输出。我不断收到“提示”未定义,但它不是已经在函数过滤器中说明了吗? [在此处输入图片说明][1]

def menu():
    print ("[1] Compute Area of a Circle")
    print ("[2] Compute Perimeter of a Rectangle")
    print ("[3] Compute Volume of a Cone")
    print ("[4] Compute Slope of a Straight Line")
    print ("[5] Exit")

    #Determining the input of the user    
    choice = filterer("Choose from the menu:")

#function for the filter
def filterer(prompt):
    while True:
       choice = float(input(prompt))
       if choice > 5 or choice < 1:
          print ("Must input integer between 1 and 5. Input again")
        elif choice.is_integer == False:
          print ("Must put an integer. Input again.")
        else:
          return prompt

filterer(choice)

【问题讨论】:

  • prompt 在函数定义内定义,但不在函数定义外;即,它没有为 filterer(prompt) 行定义
  • 在最后一行调用filterer(prompt)时,prompt的值是多少?你还没有在任何地方定义它。
  • 但不是使用“过滤器(提示)”的方式来调用函数值吗?我需要这个值,因为它将用于其他功能。
  • 我不是在“else: return prompt”这行定义了吗?
  • 我应该使用其他词而不是提示符吗?

标签: python python-3.x function iteration nameerror


【解决方案1】:

@Hamms 和 @stybl 都在 cmets 中回答了这个问题,但是,为了清楚起见,您需要更改

filterer(prompt)

进入

filterer("do some amazing thing or something")

除了您想用作提示而不是“做一些令人惊奇的事情或某事”的引用。

关键是要考虑代码的范围。 filterer(prompt) 假设提示是由它被调用的时间定义的。但是你在没有定义提示的情况下调用它。如果您愿意,您可以定义提示,例如,

prompt = "do something super groovy"
filterer(prompt)

【讨论】:

    【解决方案2】:

    其他人指出了主要问题,即您试图引用该范围内不存在的变量 (prompt)。

    也就是说,我不认为你想调用filterer 两次,我认为你不希望它返回提示,而是返回所做的选择。另外,您的整数测试不正确。

    这是完整的工作代码:

    def filterer(prompt):
        while True:
            try:
                choice = int(input(prompt))
            except ValueError:
                # Value couldn't be parsed as an integer
                print("You must enter an integer. Try again.")
            else:
                # Value was successfully parsed
                if choice > 5 or choice < 1:
                    print("Must input integer between 1 and 5. Input again")
                else:
                    return choice  # <-- changed from prompt
    
    def menu():
        print("[1] Compute Area of a Circle")
        print("[2] Compute Perimeter of a Rectangle")
        print("[3] Compute Volume of a Cone")
        print("[4] Compute Slope of a Straight Line")
        print("[5] Exit")
    
        # Determining the input of the user    
        choice = filterer("Choose from the menu: ")
    
        print("You chose: {}".format(choice))
    
    menu()
    

    【讨论】:

    • 而不是return choice,也许他正在寻找递归调用:return filterer(prompt)
    • @BrettBeatty 你为什么这么认为?这只会导致一遍又一遍地看到菜单。
    【解决方案3】:

    prompt 是在函数过滤器的范围内定义的,所以不能在函数外访问。行:

    filterer(prompt)
    

    应该改为:

    foo=filterer(bar)
    

    在执行此操作之前必须定义变量 bar。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      相关资源
      最近更新 更多