[英]How to go back to a previous line in python?
我怎样才能做到,如果最后一行是真的,它会回到循环的开头?
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?
如果不满足条件((q == x0 * x1) and (-p == x0 + x1))
循环将自动返回开始
没有必要在else
块内制定逆逻辑if((q != x0 * x1) or (-p != x0 + x1))
因为这是else
的含义。
你的 while 循环是while p != p + 1
但目前你没有在任何地方改变p
的值,所以你没有真正检查任何有用的东西。 如果你只是想继续循环,你可以做while True
(但你必须在你的循环中的某个地方break
!)
你还没有说代码的意图是什么,但我猜你希望它在打印匹配值后停止,在这种情况下你可以这样做:
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
这可能对你有用。
我还添加了一种方法,以便用户无法输入任何负数字符串或数字。)
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
这应该回到循环的顶部。 continue
命令只能在循环中工作,没有其他地方......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.