Python 函数接收字符串,返回字符串+ "!"

2024-10-06 12:41:04 发布

您现在位置:Python中文网/ 问答频道 /正文

正如标题所示,我只是试图创建一个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函数中的输入。谢谢你的帮助。


Tags: 函数字符串标题hellonewinputstringreturn
3条回答

你把函数和参数混为一谈了:

print(s(addExclamation))

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

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

s = input("please enter a string")
print(addExclamation(s))

用参数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())

在声明中:

s(addExclamation)

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

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

addExclamation("Hello")

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

但你需要改变它的实现方式:

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

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

如果要使用input,可以执行以下操作:

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

相关问题 更多 >