Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

function - A simple math in Python that's hard for me

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...