【问题标题】:Need to understand why my function is working in this way需要了解为什么我的功能以这种方式工作
【发布时间】:2020-06-15 21:38:01
【问题描述】:

我刚开始学习python,在一些关于我为了练习而做的函数的练习中,我提出了以下简单的想法,我想稍后以更大的方式进行测试,这是我的代码:

def test_function(firstn):
    firstn = input("introduce your name: ") ## assigns the value of the introduced value
    print(firstn + " Perez") ##prints the function + the surname

 test_function(0) ## calls the function and executes

一切都按预期工作,问题是,当我第一次完成最后一行的代码时,我调用了函数“test_function”,如果我未指定括号之间的值,代码失败并出现以下错误留言:

def test_function(firstn):
    firstn = input("introduce your name: ")
    print(firstn + " Perez")

test_function() ## without any value

"TypeError: test_function() missing 1 required positional argument: 'firstn'" 

我的问题是,为什么当我用括号之间的任何随机数调用函数时它可以工作,而当我只调用没有任何值的函数时它不起作用?

感谢您提供的任何反馈或任何建议,以改进我的使用。

【问题讨论】:

  • def test_function(firstn) 定义了一个采用 1 个必需参数的函数。您实际上并没有使用该名称,实际上您将其重新绑定到不同的值。可能您只是想def test_function() 定义一个没有输入参数的函数。
  • 参见 Python 教程中的Defining Functions

标签: python function input


【解决方案1】:

您已将函数定义为接受单个参数的函数:
def test_function(firstn):.这就是为什么如果您尝试不带参数调用它会引发异常。请注意,您不使用此参数,只需用函数中的第一行覆盖它:
firstn = input("introduce your name: ").

所以你的函数可能应该是:

  • 不带参数def test_function():
  • 以某种方式使用该论点

【讨论】:

    【解决方案2】:

    发生这种情况的原因是因为它对firstn 没有价值,因此无法更改firstn 如果你有这样的功能:

    def test(context):
        context = 5
        print(context)
    

    您将需要 context 变量,因为您是第一次在 def test 中定义它,如果您没有上下文变量,它会在计算机上看起来就像上下文是随机创建的变量一个函数,你不能在函数中定义变量。

    【讨论】:

    • 您可以在函数中创建局部变量。只需分配一个值。在函数foo = "bar" 中会导致python创建一个局部变量“foo”。
    【解决方案3】:

    您在函数定义中指定了参数firstn。它必须在函数调用中提供,否则你会得到那个异常。 由于您在第一行立即覆盖了firstn 变量,因此将其作为参数绝对没有用。

    【讨论】:

    • 所以,如果我只定义我的函数并在其中引入其余代码,以便在我的代码的其他位置调用它,我认为它没问题,对吧?
    • 是的,关键是如果你不打算在函数中使用它,你应该删除它。
    【解决方案4】:

    如果你想编写一个可以接受 0 或 1 个参数的函数,你可以为这样的参数提供一个“默认值”:

    def test_function(firstn="Mr"):
        firstn = input("introduce your name: ") ## assigns the value of the introduced value
        print(firstn + " Perez") ##prints the function + the surname
    
     test_function("Bob") ## calls the function and executes
     test_function() ## calls the function and executes
    

    注意我声明def test_function(firstn="Mr") 的方式,其中firstn 的“默认值”是"Mr"

    【讨论】:

      【解决方案5】:

      Python 函数采用两种类型的参数:必需的位置参数和可选的命名参数。例如,在

      def test_function(firstn, middlen=""):
          print(firstn, middlen, "Perez")
      

      调用者必须提供firstnmiddlen 是可选的。

      在您的情况下,您重新分配了firstn,因此一开始就没有必要拥有它。简单的

      def test_function():
          firstn = input("introduce your name: ") ## assigns the value of the introduced value
          print(firstn + " Perez") ##prints the function + the surname
      

      firstn 的赋值创建了一个局部变量“firstn”,并赋予它从input 返回的值。该变量在函数退出时被销毁。

      【讨论】:

        猜你喜欢
        • 2016-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-18
        • 2016-10-07
        • 2018-01-01
        • 1970-01-01
        相关资源
        最近更新 更多