'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?
Solution 1:[1]
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
Solution 2:[2]
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...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anentropic |
| Solution 2 |
