如何从嵌套的'if'重新启动函数,而不重复Python中的函数步骤
我正在从《艰苦学习python》一书中学习python,目前我正在修改其中一个练习 当嵌套的如何从嵌套的'if'重新启动函数,而不重复Python中的函数步骤,python,function,if-statement,duplicates,restart,Python,Function,If Statement,Duplicates,Restart,我正在从《艰苦学习python》一书中学习python,目前我正在修改其中一个练习 当嵌套的if语句为True时,我希望重新启动以下函数,但不重复以下步骤(当它要求“增量”时)。目前它只是这样做: def ask(): bottom = int(input("Add the lowest element in the list: ")) top = int(input("Add the highest element in the list: ")) if top <
if
语句为True
时,我希望重新启动以下函数,但不重复以下步骤(当它要求“增量”时)。目前它只是这样做:
def ask():
bottom = int(input("Add the lowest element in the list: "))
top = int(input("Add the highest element in the list: "))
if top < bottom:
print("\nThe highest element needs to be greater than the lowest!\n")
ask() # This supposed to restart the function
step = int(input("Add the step by which the list increments: ")) # In case the `if` statement is `True` this step is called twice (or more)
return(bottom, top, step)
def ask():
bottom=int(输入(“添加列表中最低的元素:”)
top=int(输入(“添加列表中最高的元素:”)
如果顶部<底部:
打印(“\n最高元素需要大于最低元素!\n”)
ask()#这应该是为了重新启动函数
step=int(输入(“添加列表递增的步骤:)#如果'if`语句为'True',则调用该步骤两次(或多次)
返回(底部、顶部、台阶)
我知道ask()
命令在if
语句中重复函数,因此,当它结束时,函数从“停止”的位置继续。换句话说,它首先从if
语句调用“increment”步骤,然后从if
语句后面的函数本身调用“increment”步骤。不幸的是,我没有找到逃避的方法
你可以找到完整的代码
非常感谢您的帮助。您必须使用while循环(或某种循环)。除非有基本情况,否则不能使用递归函数 这里有一种方法
def ask():
while True:
bottom = int(input("Add the lowest element in the list: "))
top = int(input("Add the highest element in the list: "))
if top > bottom: break
print("\nThe highest element needs to be greater than the lowest!\n")
step = int(input("Add the step by which the list increments: ")) # In case the `if` statement is `True` this step is called twice (or more)
return(bottom, top, step)
您需要在函数中缩进代码,就像在pastebin文件中一样。空白在Python中非常重要。是的,对不起,我在发布后才意识到,复制/粘贴会将其删除。现在我纠正了它。我在链接的源代码中看到了
而循环。你知道在你目前的Python学习水平上,你的break
?因为这就是在循环中重复提问的全部内容,一旦得到可接受的答案,就离开循环。是的,实际上我遇到了break
,但我没有考虑在函数中包含循环。我要试试那个。尽管如此,我仍感兴趣的是,出于教育目的,是否可以使用if
语句实现这一点。如果您将内部ask
调用行更改为:return ask()#这应该重新启动函数
?