简体   繁体   English

根据用户输入执行随机数生成器 x 次

[英]Carrying out a random-number generator x number of times based on user input

I am trying to make a random number generator with numbers 1-10 in Python, and I'd like it to generate a certain number of responses based on how many instances the user wants it.我正在尝试用 Python 制作一个数字 1-10 的随机数生成器,我希望它根据用户想要的实例数量生成一定数量的响应。 For example, the output for 5 responses would go something like this: 6, 1, 2, 9, 10, with each of those being randomly generated.例如,5 个响应的输出将是这样的:6、1、2、9、10,每个响应都是随机生成的。 Repeats are ok.重复没问题。

This is all I have so far (I'm not that experienced):到目前为止,这就是我所拥有的(我没有那么有经验):

import random

x = int(input("How many times? "))

y = random.randint(0,10)

...and that's as much as I have. ……和我一样多。 Please help!请帮忙!

After, getting the input from the user, run a loop x number of times and print a random output to the screen:之后,从用户那里获取输入,运行循环 x 次并将随机输出打印到屏幕上:

import random

x = int(input('How many times?'))

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

Also, if you are using python 2.x, use the raw_input function instead of input.此外,如果您使用的是 python 2.x,请使用 raw_input 函数而不是 input。

import random

z = int(input("How many times? "))

for x in range(0, z):
   print "%d\n" % random.randint(1,10)

Hope this helps!希望这可以帮助!

Comprehensions are also good.理解力也不错。 They are much faster than loops, though in this case that is of no importance.它们比循环快得多,尽管在这种情况下并不重要。

[random.randint(1,10) for i in range(x)]

For x =7, this generates a list of seven random numbers between 1 and 10:对于 x = 7,这会生成一个包含 1 到 10 之间的七个随机数的列表:

[5, 6, 4, 7, 7, 10, 5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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