educative.io

Why the output is "Hello" and not "!Hello!"?

my_string = “Hello”

def exclamation(my_string):
my_string = “!!” + my_string + “!!”
return my_string

exclamation(my_string)
print(my_string)

Nevermind, i found the problem.

can you explain why


Course: Learn Python 3 from Scratch - Free Interactive Course
Lesson: Quiz - Learn Python 3 from Scratch

Hey @s_h, In Python, variables that store mutable data types, like lists, are passed by reference, whereas variables that store immutable data types, like strings, are passed by value.

Instead of passing a reference to the original string when you provide a string to a function, you construct a duplicate and pass it to the function. The original string is, therefore, unaffected by any modifications made to it inside the method.

Since the my_string variable is a string in the example code, the exclamation function’s modifications to the my_string parameter are actually changes to a copy of the original string. That’s why the “my_string” initial value has not changed.

2 Likes