Continuously generate random number in python but stop when it generates a certain number

南笙酒味 提交于 2020-01-05 05:40:29

问题


I want to continuously generate a random number between 1 to 10 but stop if it generates the number 9 or 10.

I'm using this to get the random number

import random
for x in range(1):
  random.randint(1,10)

However, I don't know how to continue from there besides

if range<9 :
    print("Again")
elif:
    for x in range(1):
        random.randint(1,10)
else:
    print("End")      

回答1:


>>> from random import randint
>>> while True:
...     n = randint(1,10)
...     if n in range(1,9):
...         print(n)
...     else:
...         break
...     
6
1
5
7



回答2:


You need to use a while loop. So whilst True (i.e. looping forever), first generate a random number. Then print it whatever it is. Then, if this number (rand) is in the tuple: (9, 10), i.e. it is a 9 or a 10 then break (exit) out of the while loop.

Here is the code for the steps outlined above:

import random
while True:
   rand = random.randint(1, 10)
   print(rand)
   if rand in (9, 10):
       break

which, for me, gave the random output of:

2
3
6
7
9

note how it stopped when it reached 9


The code could actually be written slightly shorter and more efficiently, if we just simply check if rand > 8 as if it passes this, it must be 9 or a 10. This will make the code run faster as at the processor level, this would be quicker to process. However, two things to note are that this wouldn't work if you wanted to stop when you reach other numbers such as say 4 or 8. Also, at this scale, efficiency isn't really something worth worrying about.

Nevertheless, you could still use the following to achieve the same result:

import random
while True:
   rand = random.randint(1, 10)
   print(rand)
   if rand > 8:
       break


来源:https://stackoverflow.com/questions/47476716/continuously-generate-random-number-in-python-but-stop-when-it-generates-a-certa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!