简体   繁体   中英

How to go back to a previous line in python?

How can i make it so that if the last line is true it goes back to beginning of the loop?

p = int(input("input value of p: ")  
q = int(input("input value of q: ")  
import random  
list(range(-q, q)):
while p != p + 1:
    x1 = random.choice(l)
    x0 = random.choice(l)
    if((q == x0 * x1) and (-p == x0 + x1)):
        print(x0, x1)
    else:
        if((q != x0 * x1) or (-p != x0 + x1)):
            #What do i put here to return to the beginning of the loop?

if the condition ((q == x0 * x1) and (-p == x0 + x1)) is not met the loop will automatically go back to the start

there's no need to formulate the inverse logic if((q != x0 * x1) or (-p != x0 + x1)) inside the else block since that is the meaning of else .

your while loop is while p != p + 1 but currently you don't change the value of p anywhere, so you're not really checking anything useful. if you just want to keep looping you can do while True (but you will have to have a break in your loop somewhere!)

you haven't said what is the intention of the code but I'm guessing you wanted it to stop after printing the matching values, in which case you could just do:

import random

p = int(input("input value of p: ")  
q = int(input("input value of q: ")  
l = range(-q, q)

while True:
    x1 = random.choice(l)
    x0 = random.choice(l)
    if ((q == x0 * x1) and (-p == x0 + x1)):
        print(x0, x1)
        break

This might work for you.

I have also added a way so the user can not enter any string or numbers that are negative.)

l=[]
while q<=0:
    try:
        q=int(input("Enter a number"))
    except:
        print("That is not a number!")
        continue
while p<=0:
    try:
        p=int(input("Enter a number"))
    except:
        print("That is not a number!")
        continue
    import random  
    list(range(-q, q))
    print(l)
    while p != p + 1:
        x1 = random.choice(l)
        x0 = random.choice(l)
        if((q == x0 * x1) and (-p == x0 + x1)):
            print(x0, x1)
        else:
            if((q != x0 * x1) or (-p != x0 + x1)):
                continue

This should go back to the top of the loop. The continue command will only work in loops, no where else...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM