简体   繁体   中英

How to create a loop that shuts down when given answer in python?

what I am wanting to do is randomly generate two numbers that equal a given number. Yet to allow for this to get the desired answer I want it to be random. That is the problem.

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*

(thanks for the help :D)

I have know created a list called 'right' and know trying to append values a and b to the list yet that is not working. For I am knowing running the program 'in for trail in range(100)' so I get the answer. Yet the values are not appending into the new list right. Which is the problem. Then what I am going to do it read values 0 and 1 in the list right and then use them.(sorry its not that well done for at school) This is for fractions not adding to a given variable. This bit second but is.

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?

But this accomplishes the same thing:

 b = choice(a)
 c = 10 - b

For decimal numbers betweeen 0 and 10:

from random import uniform

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

Maybe I'm missing the point, but there is no need of a loop to choose two random numbers that sum up to another. A randint and simple subtraction do the job:

from random import randint

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

This does what you describe, but the other two answers probably do what you want , since for any given digit, d, there will be only one other digit, d', st d+d'=10. So my way is unnecessarily slow.

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

but to answer the question you actually posed, in python "continue" will jump out of a conditional block or one iteration of a loop, and "break" will exit the loop completely. sys.exit() will quit python, so it's not what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM