Hi there! I’m very new to Python and have been asked to modify the following code in a way that it would print 11 instead of 10:
def inc(x):
x = x +1
a = 10
inc(a)
print(a)
The way I understand the code, is that there is no assigned link between variables x and a, so the function defined above doesn’t really affect the result when I try to print(a).
I’ve tried assigning one variable to the other, but the value for x (the x+1) gets overwritten into a and then 10, hence printing out 10 again.
I hope someone can help me with this small task and explain to me what way works and why!
Thank you!!
def inc(x):
x = x + 1
return x
a = 10
a = inc(a)
print(a) # 11
b = 20
b = inc(b)
print(b) # 21
print(inc(5)) # 6
inc(x) # NameError -- variable x is not defined. It doesn't exist outside of the function
x = 1
x = inc(x)
print(x) # 2. Now it works because a variable 'x' in the global scope has been defined.
# There is a global variable x, and within the function, a variable x scoped & accessible only within the function
You’re getting it! The variable x in this instance is scoped to the function inc(). Outside of that function, x is undefined and might as well not exist. Until you reassign a explicitly outside the function in this scenario, it will stay unchanged.
The incorrect way (for this situation), but a good learning example:
a = 10
def inc(): # This doesn't need any arguments
a = a + 1 # because this is referencing the global variable 'a' defined outside the function
print(a) # 10
inc()
print(a) # 11
The above function won’t increment from any argument like the first one, but only increments the global variable a