I am learning python from the 'Learn Python the Hard Way' book and at the moment I am tinkering with one of the exercises.
I would like to restart the following function when the nested if
statement is True
but without repeating the following step (when it asks for the "increment") again. Currently it just does that:
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)
I understand that the ask()
command repeats the function inside the if
statement and, therefore, when it ends, the function continues from where it was 'stopped'. In other words, it calls first the "increment" step from the if
statement and, second, from the function itself following the if
statement. Unfortunately I did not find a way to escape this.
You can find the whole code here.
Any help is appreciated.
You are going to have to use a while loop (or some sort of loop). You can't use a recursive function unless there is a base case.
Here is one way to do it.
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)