【发布时间】:2017-04-06 12:11:06
【问题描述】:
我正在我的 R.Pi 上学习 Python,但遇到了一个小问题。在我看来,以下代码会使“inputchecker”函数在内存中保持打开状态,同时它会路由回“getinput”函数。
这是错误的代码吗?应该做的非常不同吗?
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)
【问题讨论】:
-
它并不完全是 pythonic,因为它可能会导致无法预料的 true if 语句出现问题,而且这不仅限于 python。所有语言都支持这种“hack”。最好使用 while 循环,除非您经常使用 while 循环以将其放入函数中。
标签: python python-3.x raspberry-pi nested-function