Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Please help me. I'm trying to learn Python and I'm very beginner. I tried reading and watching videos but I don't understand this logic:

def myFunction(y):
    x = y + y #Local
    print(x)
    return x
x = 5 #Global
myFunction(x)
print(x)

I get the values 10 and 5.

Really, I can't understand why 10. This is breaking my mind. If x equals 5, than the result of the line 2 shouldn't be 2.5? I have 5 = y + y.

My mind is on a loop. Please help, you're my only hope.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

You are passing x as the argument of your function myFunction(). Thus if x=5 you get:

myFunction(5):
   x = 5 + 5 
   return(x) #10

this is why you are getting 10. If you change x=5 to x=10 you will see that the result of the function will be 20 and so on...

You are not replacing the x in the function itself. However, the x you stated will indeed remain a global variable and thus will be printed on the second line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...