【问题标题】:python 3: Name error from input within a functionpython 3:函数内输入的名称错误
【发布时间】:2018-06-11 20:33:50
【问题描述】:

我需要定义一个函数,它将从用户输入中收集的两个整数相乘。说明说要“在函数内”收集用户输入,但这样做会导致错误:

NameError: name 'num_1' is not defined.

这是我的尝试:

def multiply(num_1, num_2):
    num_1 = input("enter a whole number:")
    num_2 = input("enter another whole number:")
    result = int(num_1)*int(num_2)
    return(num_1 + " * " + num_2 + " = " + str(result))

multiply(num_1, num_2)

更改代码以便在调用函数时收集输入使其通过:

def multiply(num_1, num_2):
    result = int(num_1)*int(num_2) 
    return(num_1 + " * " + num_2 + " = " + str(result))

print(multiply(input("enter  a whole number: "), input("enter another whole number: ")))

但我想知道是否可以按照说明在函数中收集输入。

【问题讨论】:

  • 当然,只需删除函数参数。您的函数不接受参数,因为它接受来自input() 调用的值而不是
  • 所以def multiply():,然后拨打multiply()
  • 我希望那些对答案投反对票的人会让 cmets 说出原因。
  • @Chandra 看到我的回答

标签: python python-3.x nameerror


【解决方案1】:

由于输入是由用户定义的,因此该函数没有输入参数。使用:

def multiply():
    num_1 = input("enter a whole number:")
    num_2 = input("enter another whole number:")
    result = int(num_1)*int(num_2) 
    return(str(num_1) + " * " + str(num_2) + " = " + str(result))

multiply()

结果

'1 * 2 = 2'

【讨论】:

    【解决方案2】:

    由于您在函数内部收集值,因此无需将它们作为参数传递。

    def multiply_two_numbers():
        x = input("Enter a number: ")
        y = input("Enter another number: ")
        return x*y
    
    >>> multiply_two_numbers()
    Enter a number: 10
    Enter another number: 12.5
    125.0
    

    【讨论】:

      【解决方案3】:

      是的,可以从函数中获取输入。您正确地从用户那里获得了输入,但是,您似乎遇到了函数范围问题。

      你得到的 NameError 问题是因为你的变量的范围。您已经在函数 multiply 中定义了它们,并且您试图在函数范围之外访问它们。 Python 函数作用域意味着您只能在函数下方的缩进空间中访问这些变量。

      例如:如果你有:

      multiply():
        num_1 = 2
        print(num1)
      

      不会出现名称错误,因为您在函数的范围内。但是,如果你做了这样的事情:

      multiply():
        num_1 = 2
      
      print(num1)
      

      您会收到 NameError: num_1 is not defined

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-12
        • 1970-01-01
        • 2022-01-12
        • 1970-01-01
        相关资源
        最近更新 更多