在函数外定义变量时遇到问题(Python)
我刚开始学习Python,想做一个简单的程序,里面有文本菜单。我需要用函数来完成大部分工作,这样我可以习惯在程序中使用函数。所以我想在这个程序里用一个函数来获取用户输入的第一个、第二个,可能还有第三个数字。我希望这个函数可以重复使用,这样就能多次获取这些数字。不过我遇到了一个问题,就是这些变量只能在函数内部使用,其他地方用不了。有什么建议吗?下面是我的代码:
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."
2 个回答
1
另外,你也可以使用全局变量。比如:
global a_var
def a_function():
global a_var
a_var = 3
a_function()
print a_var
不过,使用返回值可能会更简洁一些。
5
变量是局部的,也就是说它们只在定义它们的函数内部有效。如果你想使用这些变量的值,可以让你的函数返回这些值:
def getNum():
firstNum = input("...")
secondNum = input("...")
thirdNum = input("...")
return firstNum, secondNum, thirdNum
if option == 1:
firstNum, secondNum, thirdNum = getNum()