我寫了以下函數,它需要一個變量input_name
。然後用戶輸入一些分配給input_name
的值。我想知道在功能之外訪問input_name
的最佳方式。我知道在一個函數內定義一個變量爲全局變量,意味着它可以在函數之外使用。然而,在這種情況下,變量實際上是函數的一個參數,所以我不確定如何將其定義爲全局變量。我明白任何幫助,請查找下面的問題代碼:作爲全局變量的Python函數參數
def input(input_name, prompt):
while True:
data = raw_input(prompt)
if data:
try:
input_name = int(data)
except ValueError:
print 'Invalid input...'
else:
if input_name >= 0 and input_name < 100:
print 'Congratulations'
break
input_name = 'Please try again: '
else:
print 'Goodbye!'
break
month = 0
day = 0
year = 0
century = 0
input(month, "Please enter the month (from 1-12, where March is 1 and February is 12): ")
input(day, "Please enter the day (from 1-31): ")
input(year, "Please enter the year (from 0 - 99, eg. 88 in 1988): ")
input(century, "Please enter the century (from 0 - 99, eg. 19 in 1988): ")
A = month
B = day
C = year
D = century
附註:'input_name ='請再試一次:'' - 您可能想要在那裏設置'prompt',而不是'input_name'。 – poke 2012-02-11 18:45:55