Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren0
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 😁
4 Antworten
+ 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
+ 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
+ 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).
+ 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.