Having problems defining variables outside a function (Python)
I'm pretty new to python and I'm trying to make a simple program where you have text menus and I have to us开发者_高级运维e functions to do most of the work (to get used to using functions inside a program). So I'm trying to use a function in this program to get the first, second, and possibly a third number from the user. I need to be able to reuse this function so I can get said numbers from the user, but I'm having problems with only being able to use these variables within the function and nowhere else. Any suggestions will help! Here's the code:
option = 1
while option !=0:
print "\n\n\n************MENU************"
print "1. Counting by one"
print "2. Fibbonacci Sequence"
print "0. GET ME OUTTA HERE!"
print "*" * 28
option = input("Please make a selection: ") #counting submenu
if option == 1:
print "\n\n**Counting Submenu**"
print "1. Count up by one"
print "2. Count down by one"
print "3. Count up by different number"
print "4. Count down by different number"
countingSubmenu = input("Please make a selection: ")
def getNum():
firstNum = input("Please state what number to start at: ")
secondNum = input("Please state what number to end at: ")
if countingSubmenu == 3 or countingSubmenu == 4:
thirdNum = input("Please state what increment you would want to go up by: ")
if option == 1:
getNum()
for x in range(firstNum, secondNum+1):
print x
print "End of test."
Variables are local to the functions in which they are defined. You might try having your function return those values:
def getNum():
firstNum = input("...")
secondNum = input("...")
thirdNum = input("...")
return firstNum, secondNum, thirdNum
if option == 1:
firstNum, secondNum, thirdNum = getNum()
Alternatively, you could use global variables. For example:
global a_var
def a_function():
global a_var
a_var = 3
a_function()
print a_var
However, using a return is probably cleaner.
精彩评论