我在我的R.Pi上學習Python,並且遇到了一個小障礙。在我看來,下面的代碼會將「inputchecker」功能保留在內存中,並返回到「getinput」功能。嵌套函數Pythonic?
這是錯的代碼?它應該完全不同嗎?
def getinput(i):
if i == 1:
first = input("Would you like A or B? ")
inputchecker(1, first)
elif i == 2:
second = input("Would you like C or D? ")
inputchecker(2, second)
def inputchecker(n, userinput):
def _tryagain_(n):
usage(n)
getinput(n)
if n == 1:
if userinput in ("A", "B"):
print("You chose wisely.")
getinput(2)
else:
_tryagain_(n)
elif n == 2:
if userinput in ("C", "D"):
print("You chose wisely.")
else:
_tryagain_(n)
def usage(u):
if u == 1:
print("Usage: Just A or B please.")
if u == 2:
print("Usage: Just C or D please.")
getinput(1)
這不完全是Python的,因爲這會導致if語句與不可預見的真正問題,這不是隻蟒蛇限制。所有語言都支持這種「黑客」。最好使用while循環,除非您經常使用while循環將其放入函數中。 – ProgramFast