如何从嵌套的 `if` 重新启动函数而不复制 Python 中的函数步骤

How to restart function from nested `if` without duplicating function steps in Python

我正在从 'Learn Python the Hard Way' 书中学习 python,目前我正在修改其中一个练习。

我想在嵌套的 if 语句为 True 时重新启动以下函数,但不再重复以下步骤(当它要求 "increment" 时)。目前它只是这样做:

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)

我知道 ask() 命令在 if 语句 中重复 函数,因此,当它结束时,函数从它所在的地方继续是 'stopped'。换句话说,它首先从 if 语句调用 "increment" 步骤,然后从 if 语句之后的函数本身调用。不幸的是我没有找到逃避这个的方法。

您可以找到完整的代码 here

感谢任何帮助。

您将不得不使用 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)