Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何创建一个在python中给出答案时关闭的循环?_Python_Loops_Control Flow - Fatal编程技术网

如何创建一个在python中给出答案时关闭的循环?

如何创建一个在python中给出答案时关闭的循环?,python,loops,control-flow,Python,Loops,Control Flow,我想做的是随机生成两个等于给定数字的数字。然而,为了让它得到想要的答案,我希望它是随机的。这就是问题所在 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 h

我想做的是随机生成两个等于给定数字的数字。然而,为了让它得到想要的答案,我希望它是随机的。这就是问题所在

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)

我知道创建了一个名为“right”的列表,并且知道尝试将值a和b附加到该列表中,但这不起作用。因为我知道运行程序“在范围内跟踪(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)
但这也实现了同样的目的:

 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',s.t.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,因此这不是您想要的。

这并没有解决OP希望保留加起来等于10的数字这一事实。那么对于分数,您将如何做呢?因为这是我最困惑的另一个问题。有什么问题吗?退出循环?如果是这样的话,请注意这样一个事实,即每个提出答案的人都使用while循环,因为它是一个在特定条件下存在的循环。
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