【问题标题】:Python Function That Receives String, Returns String + "!"Python函数接收字符串,返回字符串+“!”
【发布时间】:2017-05-05 03:00:48
【问题描述】:

正如标题所暗示的,我只是想创建一个 Python 函数,它接收一个字符串,然后返回该字符串并在末尾添加一个感叹号。

“Hello”的输入应该返回

Hello!

“再见”的输入应该返回

Goodbye!

等等。

这是我尝试过的:

def addExclamation(s):
    s = input("please enter a string")
    new_string = s + "!"
    return new_string

print(s(addExclamation))

这给了我错误信息:

NameError: name 's' is not defined on line 6

为什么没有定义“s”?我以为我确定 s 是 addExclamation 函数中的输入。谢谢您的帮助。

【问题讨论】:

  • 你把一切都搞混了。
  • @TigerhawkT3 我在搞混什么?

标签: python string function return


【解决方案1】:

您使用参数s 定义了一个函数。该函数立即丢弃该值并要求输入。您正在调用与该参数同名的函数,并向其发送函数名称的参数。这没有任何意义。

def addExclamation(s):
    new_string = s + "!"
    return new_string

print(addExclamation('Hello'))

或者:

def addExclamation():
    s = input("please enter a string")
    new_string = s + "!"
    return new_string

print(addExclamation())

【讨论】:

    【解决方案2】:

    您在此处混淆了函数和参数

    print(s(addExclamation))
    

    而且,您可能打算在函数之外读取输入并将字符串传递到:

    def addExclamation(s):
        new_string = s + "!"
        return new_string
    
    s = input("please enter a string")
    print(addExclamation(s))
    

    【讨论】:

      【解决方案3】:

      在声明中:

      s(addExclamation)
      

      您尝试调用未定义的s 函数。

      你给addExclamation的参数就是你要调用的函数。你应该写:

      addExclamation("Hello")
      

      在本例中,您使用字符串参数调用函数addExclamation():“hello”。

      但是你需要改变它的实现:

      def addExclamation(s):
          result = s + "!"
          return result
      

      这个实现是不言自明的:它创建了一个新的字符串result,将原始字符串s和“!”连接起来。

      如果你想使用input,你可以这样做:

      text = input("Enter a text: ")
      print(addExclamation(text))
      

      【讨论】:

        猜你喜欢
        • 2014-12-07
        • 1970-01-01
        • 1970-01-01
        • 2023-03-06
        • 2021-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-15
        相关资源
        最近更新 更多