Search code examples
pythonstringfunctionreturn

Python Function That Receives String, Returns String + "!"


As the title suggests, I'm just trying to create a Python function that receives a string, then returns that string with an exclamation point added to the end.

An input of "Hello" should return

Hello!

An input of "Goodbye" should return

Goodbye!

Etc.

Here's what I tried:

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

print(s(addExclamation))

This gave me the error message:

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

Why is "s" not defined? I thought I determined that s is the input within the addExclamation function. Thank you for your help.


Solution

  • You define a function with a parameter s. That function immediately throws that value away and asks for input. You are calling a function with the same name as that parameter, and sending it an argument of the function name. That doesn't make any sense.

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

    Or:

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