Using a variable outside of a defined function

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP

Using a variable outside of a defined function



If I had a function that I made:


def a():
n = 2*2



How could I access n out of the function without calling a?





A related question comes to mind, although that's about accessing a variable inside a function when you do call the function, so it's not really a duplicate.
– David Z
4 hours ago





Why would you want to?
– AChampion
4 hours ago





Have you looked at the answers to this question?
– martineau
3 hours ago




2 Answers
2



You cannot. You will need to define the variable outside of the function, or call the function and return it.



You need to return it, so do:


def a():
n = 2*2
return n
print(a())



Output:


4



You can also do print, but return is better, check this: What is the formal difference between "print" and "return"?


print


return






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

Executable numpy error

PySpark count values by condition

Trying to Print Gridster Items to PDF without overlapping contents