2012-06-19 35 views
3

我想要做的是隨機生成兩個等於給定數字的數字。然而,爲了獲得所需的答案,我希望它是隨機的。那就是問題所在。如何創建一個在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追加到列表但不工作。因爲我知道運行程序'的範圍(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) 
+0

for/while + break? –

回答

3
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 

對於十進制數betweeen 0和10:

from random import uniform 

b = uniform(0, 10) 
c = 10 - b 
+0

那麼你如何做分數?因爲那是我最迷惑的另一個。 – fanjojo

+0

@fanjojo查看更新回答 –

1

也許我錯過了點,但有不需要循環來選擇總結到另一個的兩個隨機數。一個randint和簡單的減法做的工作:

from random import randint 

def random_sum(given_number): 
    a = randint(1, given_number) 
    return a, given_number - a 
+0

這並沒有解決OP要保留的數字加起來爲10的事實。 – Ben

0

這做什麼描述,但其他兩個答案可能做你,因爲對於任何給定的數字,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「繼續」會跳出一個條件塊或一個迭代循環的,而「破發」將徹底退出循環。 sys.exit()會退出python,所以它不是你想要的。

+0

那是我的問題 – fanjojo

+0

有什麼問題?退出循環?如果是這樣,請注意這樣一個事實,即每個提出循環回答的人都使用一個while循環,因爲它是一個循環,在特定條件下退出。 – Ben

相關問題