educative.io

Educative

Function Scope python

def multiply_by_10(n):

n *= 10

num = n

plz explain


Course: Learn Python 3 from Scratch - Free Interactive Course
Lesson: Function Scope - Learn Python 3 from Scratch

Hi @Ashish!!
Thanks for contacting the Educative Team. In this function, it is explained that immutable objects are unaffected by the working of a function. However, if we need to update immutable variables through a function, we can assign the returning value from the function to the variable such as

num = 20


def multiply_by_10(n):
    n *= 10
    num = n  # Changing the value inside the function
    print("Value of num inside function:", num)
    return n


num= multiply_by_10(num)
print("Value of num outside function:", num)  # The original value remains unchanged

Here we assigned the returning value i.e. 200, from the function multiply_by_10(n) to variable num to update its value.
The output of this function would be :
image
So the value of the variable has been updated here
But if we do not want to update the value of variable num, we will not assign the returning value from the function to the variable, such as

num = 20


def multiply_by_10(n):
    n *= 10
    num = n  # Changing the value inside the function
    print("Value of num inside function:", num)
    return n

multiply_by_10(num)
print("Value of num outside function:", num)  # The original value remains unchanged

Its output would be :slight_smile:
image
And the value of the variable remains intact in this case.
I hope it helps. Happy Learning :slight_smile: