[英]How to create a loop that shuts down when given answer in python?
我想要做的是随机生成两个等于给定数字的数字。 然而,为了得到想要的答案,我希望它是随机的。 那就是问题所在。
a=(1,2,3,4,5,6,7,8,9,)
from random import choice
b=choice(a)
c=choice(b)
d= c+b
if d == 10:
#then run the rest of the program with the value's c and b in it
#probably something like sys.exit goes here but I am not sure to end \/
else:
# i have tryied a few things here but I am not sure what will loop it around*
(感谢您的帮助:D)
我知道创建了一个名为“正确”的列表,并且知道尝试将值 a 和 b 附加到列表中,但它不起作用。 因为我知道运行程序'in for trail in range(100)'所以我得到了答案。 然而,这些值并没有附加到新列表中。 这是问题所在。 然后我要做的是读取列表中的值 0 和 1,然后使用它们。(对不起,它在学校做得不是很好)这是用于不添加到给定变量的分数。 这一点秒不过是。
import sys
right=(0)
y=x+x
from trail in range(y)
a=(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
from random import choice
A=choice(a)
B=choice(a)
d=A/B
if d==1:
right.append(A)
right.append(B)
else:
x.append(1)
from random import choice
a = range(1, 10)
b = c = 0
while b + c != 10:
b = choice(a)
c = choice(a) # You meant choice(a) here, right?
但这完成了同样的事情:
b = choice(a)
c = 10 - b
对于 0 和 10 之间的十进制数:
from random import uniform
b = uniform(0, 10)
c = 10 - b
也许我没有抓住重点,但是不需要循环来选择两个相加的随机数。 一个 randint 和简单的减法可以完成这项工作:
from random import randint
def random_sum(given_number):
a = randint(1, given_number)
return a, given_number - a
这符合您的描述,但其他两个答案可能符合您的要求,因为对于任何给定的数字 d,只有一个其他数字 d', st d+d'=10。 所以我的方式不必要地缓慢。
goal = 10 #the number you're trying to add up to
sum = 0
min = 1
max = 9
b = c = 0 # initialize outside your loop so you can access them afterward
while (sum != goal)
b = random.randint(min, max)
c = random.randint(min, max)
sum = b+c
但是要回答您实际提出的问题,在 python 中,“continue”将跳出条件块或循环的一次迭代,而“break”将完全退出循环。 sys.exit() 将退出 python,所以这不是你想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.