Home > Software engineering >  How to update a string in function without return value?
How to update a string in function without return value?

Time:01-08

def updateString()
    '''you can only edit the code inside the  function'''

    name="cat" 
    print(name)

name="dog"

updateString()

print(name)

The output of this code will be

cat
dog

But my required output is

cat
cat

Can anyone solve this without "return value"

CodePudding user response:

Use global

def updateString():
    '''you can only edit the code inside the  function'''
    global name
    name = "cat"

    print(name)


name = "dog"

updateString()

print(name)

CodePudding user response:

I am also new to python. I may attempt a response to your question, I would say that for this particular question, the return keyword is not strictly required. You can either call the function twice to get the required output (and delete the last print statement) or include an IF statement to allow the second print statement to do what you want. I hope this helps.

  • Related