Why does this basic py code work on its own, but not in the function? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why does this basic py code work on its own, but not in the function?

G'day all. OK, this has me stumped! 🤔 I thought how to simplify an original challenge code submission. Can anyone please explain why this code - "a, b = b, a + b" - works on its own here, 😃 https://code.sololearn.com/ce3Ur8xH4Rl0/?ref=app but fails inside the function here, 😭 https://code.sololearn.com/c7CjysYXSX4u/?ref=app Don't really need the code fixed for me, I just need to understand what is making it fail. Thanks in advance 😁

18th Jan 2021, 11:15 AM
Mark McClan
Mark McClan - avatar
4 Answers
+ 1
If I remember correctly, you can use a global variable inside a function but cannot modify it directly. In order to do that, you must make them global inside the function. Add this inside your function: global a,b
18th Jan 2021, 11:49 AM
Avinesh
Avinesh - avatar
+ 1
It doesn't work like that because of the scope of the variables. Especially when trying to assign something that hasent been assigned yet. In the function, there is no a or b. But you tried to assign values to the variables... using the variables with no value. try working with arguments in the function OR just assign a and b INSIDE the function first
18th Jan 2021, 11:51 AM
Slick
Slick - avatar
+ 1
Avinesh , that was spot on. Worked perfectly. Thank you. If we've been taught that already, I've totally forgotten about it (pretty sure we haven't though).
18th Jan 2021, 12:28 PM
Mark McClan
Mark McClan - avatar
+ 1
Mark McClan not sure if that is discussed in the course. We all get similar doubts and I had a similar one in the past 😉 Btw you are welcome.
18th Jan 2021, 1:29 PM
Avinesh
Avinesh - avatar