Can variables outside a function be referenced within a function? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can variables outside a function be referenced within a function?

Thia chapter says variables within a function cant be referenced outside it. But how about the other way around. For example For example def ss(): print(x) x=5 ss()

23rd Feb 2017, 12:30 PM
Mufaddal Abbas
Mufaddal Abbas - avatar
1 Answer
+ 2
Yes, variables outside can be referenced within functions, as long as the variable is within the scope of the function, and the variable's name is not being redeclared/reused within the function. Your example will work just fine. That "x" variable is in the scope of the function, so it will be available when you call the function (as long as you call the function after declaring the variable, which is what you have done). To find out more, you can read up on "scope".
23rd Feb 2017, 12:53 PM
Jehad Al-Ansari
Jehad Al-Ansari - avatar