Python- Variable Scope
def Interface(): Number = input('Enter number: ') Interface() print(Number) This is a small simplified snippet of my code which produces: Traceback (most recent call last):
Solution 1:
It depends on what you want to do.
Probably making the Interface function return Number would be the easiest solution
def interface():
number = input("Enter number: ")
returnnumber
print(interface())
Please see this SO QA on the topic of scope rules in python
Note: as you can see, I have converted the names of the function and the variable to lowercase, following the PEP-8 guideline
Solution 2:
Because variable Number only belongs function Interface(). You can use return like this:
defInterface():
number = int(input("Enter number: "))
# remember use int() function if you wish user enter a numberreturn(number)
print(Interface())
or use global just like this:
defInterface():
global number
number = input("Enter number: ")
# remember use int() function if you wish user enter a number
Interface()
print(number)
And only use global when you need the variable can use at everywhere or you need the function return other things. Because modifying globals will breaks modularity.
Here is the document about what is global variable.
Post a Comment for "Python- Variable Scope"