[英]How to ask for user input within a function and return it to def main():?
我需要在以下函數中要求用戶輸入並將n返回給main。 變量n將在主要/其他功能中使用。 但是,無論何時執行此操作,我都會收到一條錯誤消息,指出n未定義。 為什么以下功能無法按需工作?
def main():
intro()
setInput()
print "\nThe prime numbers in range [2,%d] are: "%(n)
for i in range(n):
if testPrime(i):
print i,",",
def setInput():
n = input("Enter the value for what range to find prime numbers: ")
return n
在main()
調用中,您需要像這樣將setInput()
的結果存儲為n
:
def setInput():
n = input("Enter the value for what range to find prime numbers: ")
return n
def main():
intro()
n = setInput()
print "\nThe prime numbers in range [2,%d] are: "%(n)
for i in range(n):
if testPrime(i):
print i,",",
請注意for
循環后的縮進。 我認為這就是您的意圖。
另外,由於您使用的是Python 2.x,因此使用raw_input()
並將字符串轉換為正確的類型會更安全。 例如,您可以這樣做:
s = raw_input("Enter the value for what range to find prime numbers: ")
n = int(s) # or fancier processing if you want to allow a wider range of inputs
您可以使用global
關鍵字...
def setInput():
global n
n = input("Enter the value for what range to find prime numbers: ")
return n
即使在函數外部也可以訪問該變量(在每個函數外部執行n = "something"
具有相同的效果。
n = 42
def foo():
print(n) # getting the value on n is easy
return n+1 # same here
def bar():
global n
n += 10 # setting a value to n need the use of the keyword (one time per function)
if __name__ == "__main__":
print(n) # 42
a = foo() # 42
print(a) # 43
print(n) # 42
bar()
print(n) # 52
或者直接從main
函數調用此函數,然后在參數中傳遞n
(更多的冗余,但是更安全...這取決於變量的作用:使用類似n
的名稱,使用a似乎不是一個好選擇全局變量,但選擇取決於您)
def main():
...
n = setInput()
foo(n)
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.