我試圖測試每個輸入,然後返回數字被清除,然後做數學。例如,用戶輸入的是N而不是我希望輸出的數字,而不是數字,而如果用戶輸入1,那麼我希望它移動到下一個功能請求功率,然後做同樣的事情,如果通過然後進入輸出問題答案的最後部分。Python Recrusive Statement錯誤未定義
程序通過了非數字區域的錯誤,當它到達非常最後的功能時,它告訴我基礎也沒有功率被定義。
代碼是用Python2和Python3編寫的。所有的作品都很好。我主要使用python3。
# Below we are creating the recursive statement to do the math for us. We are calling Base and Power
# from the main function where the user Inputs the numbers.
def pow(base, power):
if power == 0:
return 1
if power == 1:
return base
else :
return base * pow(base, power - 1)
def determineBase():
while True:
try:
base = int(input ('Please Enter A Base: '))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return base
def determinePower():
while True:
try:
power = int(input ('Please Enter A Power: '))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return power
def main():
determineBase()
determinePower()
pow(base,power)
print("The answer to",base,"to the power of", power,"is", pow(base,power),".")
main()
嘗試把遞歸返回和下一個def之間的差距也可以,請你從截圖中刪除這些行,以便我可以看到整個堆棧跟蹤? –
@James_Hughes不會改變任何東西。我爲你添加了一張不同的照片。第48行和第46行是出現錯誤的地方 – Yrroth
問題不在於遞歸函數本身,請參見下文。 –