2015-10-18 114 views
0

我非常頻繁地使用這組代碼,所以我創建了一個函數,我想使用它而不是多次編寫代碼。Python變量創建函數

def setVar(): 
try: 
    x = int(input()) 
except: 
    print("The number is not an integer please try again") 
    setVar() 

的功能如下:

def setVarInt(x): 
try: 
    x = int(input()) 
except: 
    print("The number you have entered is not an integer.") 
    print("Please try again.") 
    setVarInt(x) 

所以,當我做setVarInt(T),我希望它創建一個變量T和等待的輸入。

輸入格式:

setVarInt(T) 
print(T) 

輸出格式:

13 #This is where I input T 
13 

我得到這個錯誤:

Traceback (most recent call last): 
    File "E:\Computer Coding\Python\My Code\Function Files\setVars.py", line 19, in <module> 
setVarInt(T) 
NameError: name 'T' is not defined 
+0

它看起來像你只需要返回值,如果它是一個int。 –

+0

你能舉個例子嗎? –

+0

'return x'返回 –

回答

0

不使用遞歸來解決這個問題,你應該使用一個while循環。另外,您的x參數不是必需的。

def setVarInt(): 
    while True: 
     try: 
      return int(input()) 
     except ValueError: 
      print('Please enter an integer') 

然後當你調用這個函數時,你必須捕獲返回值才能打印它。

x = setVarInt() 
print(x) 
+1

也可能值得指出的是,你應該趕上'ValueError'與所有的例外。 [你可以'返回int(input())'而不用else塊] – AChampion

+0

我也將函數從'setVarInt'重命名爲'getInt',因爲它實際上並沒有設置變量。 'setVar'是OPs混淆的剩餘部分。 –

+0

謝謝,這正是我需要它完美的作品。 –

0

你已經做得差不多了。你剛剛忘記了return關鍵詞。

試試這個:

def setVar(): 
    try: 
     x = int(input()) 
     return x 
    except: 
     print("The number is not an integer please try again") 
     return setVar() 



x = setVar() 
print(x) 
+0

除非你在異常中返回setVar(),否則如果它們第一次沒有輸入int,它將不會返回任何東西。可能值得讓這個循環與遞歸。 – AChampion