How to return to a previous loop in python

Try nesting the first while loop inside of the second. It'll run your calculation code first, check to see if you'd like to do another, and then return to the top of the while True: loop to do another calculation.

Like this:

while True:
    x, y = raw_input["Enter 2 numbers separated by a space."].split[]
    answer = 0
    #Enter the 2 numbers to be calculated.
    print "You have selected, A = "+ x + " and B = " + y + "."
    while int[y]:
        if [not int[y] % 2 == 0]:
            # this checks if y is even or odd
            answer = int[answer] + int[x]  
            print "A = " + str[x] + " and B = " + str[y] + "."
            print "B is odd so we'll add A to the total."
            print "The running total is " + str[answer] + "."
        else: [int[y] % 2 == 0]
        print "A = " + str[x] + " and B = " + str[y] + "."
        print "B is even, so we'll ignore that number."

        x = int[x] * 2
        y = int[y] / 2

    print "The product is " + str[answer] + "."

    a = raw_input["Would you like to make another calculation? Y or N"]
    if str[a] == "Y" or str[a] == "y":
        continue
    if str[a] == "N" or str[a] == "n":
        print "Thank you have a nice day!"
        break
    else:
        print "Invalid entry. Ending program."
        break

Hope that helps

Depending on what you're trying to do, and where this particular code appears in your program, it's usually advised to wrap your code inside of functions. That way, it doesn't automatically run when you import your module. You have to call a function to make the code run.

If you want to make this an executable script, you'd want to wrap the main loop code in a if __name__ == '__main__: block so that it only executes if it's being executed directly.

e.g.:

def perform_calculation[]:
    while True:
        x, y = raw_input["Enter 2 numbers separated by a space."].split[]
        answer = 0
        #Enter the 2 numbers to be calculated.
        print "You have selected, A = "+ x + " and B = " + y + "."
        while int[y]:
            if [not int[y] % 2 == 0]:
                # this checks if y is even or odd
                answer = int[answer] + int[x]  
                print "A = " + str[x] + " and B = " + str[y] + "."
                print "B is odd so we'll add A to the total."
                print "The running total is " + str[answer] + "."
            else: [int[y] % 2 == 0]
            print "A = " + str[x] + " and B = " + str[y] + "."
            print "B is even, so we'll ignore that number."
            x = int[x] * 2
            y = int[y] / 2
        print "The product is " + str[answer] + "."

def run_loop[]:
    while True:
        perform_calculation[]
        a = raw_input["Would you like to make another calculation? Y or N"]
        if str[a] == "Y" or str[a] == "y":
            continue
        if str[a] == "N" or str[a] == "n":
            print "Thank you have a nice day!"
            break
        else:
            print "Invalid entry. Ending program."
            break

if __name__ == '__main__':
    run_loop[]

break and continue allow you to control the flow of your loops. They’re a concept that beginners to Python tend to misunderstand, so pay careful attention.

Using break

The break statement will completely break out of the current loop, meaning it won’t run any more of the statements contained inside of it.

>>> names = ["Rose", "Max", "Nina", "Phillip"]
>>> for name in names:
...     print[f"Hello, {name}"]
...     if name == "Nina":
...         break
...
Hello, Rose
Hello, Max
Hello, Nina

break completely breaks out of the loop.

Using continue

continue works a little differently. Instead, it goes back to the start of the loop, skipping over any other statements contained within the loop.

>>> for name in names:
...     if name != "Nina":
...         continue
...     print[f"Hello, {name}"]
...
Hello, Nina

continue continues to the start of the loop

break and continue visualized

What happens when we run the code from this Python file?

# Python file names.py
names = ["Jimmy", "Rose", "Max", "Nina", "Phillip"]

for name in names:
    if len[name] != 4:
        continue

    print[f"Hello, {name}"]

    if name == "Nina":
        break

print["Done!"]

Results

See if you can guess the results before expanding this section.

Using break and continue in nested loops.

Remember, break and continue only work for the current loop. Even though I’ve been programming Python for years, this is something that still trips me up!

>>> names = ["Rose", "Max", "Nina"]
>>> target_letter = 'x'
>>> for name in names:
...     print[f"{name} in outer loop"]
...     for char in name:
...             if char == target_letter:
...                 print[f"Found {name} with letter: {target_letter}"]
...                 print["breaking out of inner loop"]
...                 break
...
Rose in outer loop
Max in outer loop
Found Max with letter: x
breaking out of inner loop
Nina in outer loop
>>>

break in the inner loop only breaks out of the inner loop! The outer loop continues to run.

Loop Control in while loops

You can also use break and continue in while loops. One common scenario is running a loop forever, until a certain condition is met.

>>> count = 0 
>>> while True:
...     count += 1
...     if count == 5:
...             print["Count reached"]
...             break
...
Count reached

Be careful that your condition will eventually be met, or else your program will get stuck in an infinite loop. For production use, it’s better to use asynchronous programming.

Loops and the return statement

Just like in functions, consider the return statement the hard kill-switch of the loop.

>>> def name_length[names]:
...     for name in names:
...             print[name]
...             if name == "Nina":
...                     return "Found the special name"
...
>>> names = ["Max", "Nina", "Rose"]
>>> name_length[names]
Max
Nina
'Found the special name'

How do you go back a loop in Python?

The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while and for loops.

How do you call a former loop in Python?

The following is a very common. use add line words = [] between print[ ... ] and option = .... Or you can add it to the top of the outer loop, b/c continue will send execution there before entering the inner loop.

How do you go back to a specific line in Python?

Python does not allow you to go back to a specific line number, and even if it did, you should not take advantage of that capability because it results in unmaintainable programs.

Can you return a for loop?

It is good practice to always have a return statement after the for/while loop in case the return statement inside the for/while loop is never executed. Otherwise, a compile-time error will occur because the method cannot return nothing [unless it has the Java reserved word "void" in the method header].

Chủ Đề