0

is this right?

x = 0 def foo(x): for i in range (3): x += i return x print (foo(x))

7th Dec 2016, 6:16 AM
Jacob
2 Answers
+ 4
not really
7th Dec 2016, 7:09 AM
Ahri Fox
Ahri Fox - avatar
0
There are a couple issues here. I think the best way for you to understand what is going on is to translate what you're telling python to do exactly: >python, set x to equal 0 >python, create a new function called "foo", let it accept one input called "x" >python, create a loop that repeats everything under it "3" times. >python, add 1 to "x" >python, return "x", and stop the function. As you are probably wondering: "What? but what about the print command?!' Well, the simple answer is you told your function to stop with the "return" command. This also means because the return function is INSIDE the loop, it will not repeat and only run once. Return, transmits data back in the order it is set up. There can be more than one value returned (return x,y,6). Return will also stop the function as well, and the rest of the program will proceed. Going back to your print command, you are telling python here: >python, print the value of the function you're currently in >>python says: Angry red text Basically, your "foo" function has no value "yet", so when you asked python inside of it "print the result of this" while still inside the function, it basically didn't know what to do. Your function works perfectly fine, however it needs some re-arranging. Try this instead: x = 0 def foo(x): for i in range(3): x += 1 return x print(foo(x)) >>python says: 3
7th Dec 2016, 6:31 PM
Sapphire