Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.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_Random_While Loop_Numbers - Fatal编程技术网

Python 如何生成特定数量的随机数?

Python 如何生成特定数量的随机数?,python,loops,random,while-loop,numbers,Python,Loops,Random,While Loop,Numbers,我必须要求用户输入一个数字,然后使用while循环生成用户指定的随机数 import random x = int(input("Write a number: ")) y = random.randint(0, 10) while x != 0: print(y) y = random.randint(0, 10) 对代码进行少量修改。 您没有减少x import random x = int(input("Write a number: ")) while x !=

我必须要求用户输入一个数字,然后使用while循环生成用户指定的随机数

import random

x = int(input("Write a number: "))
y = random.randint(0, 10)

while x != 0:
    print(y)
    y = random.randint(0, 10)

对代码进行少量修改。 您没有减少
x

import random

x = int(input("Write a number: "))

while x != 0:
    y = random.randint(0, 10)
    print(y)
    x-=1


你的
while
循环将永远旋转,因为你从不减少
x
。您可以通过将以下内容添加到循环体来解决此问题:

x -= 1
如果您不希望在用户输入负数时它永远旋转(从那时起,它将永远减少而不会达到0),您可以将
while
更改为:

while x > 0:
执行这种类型循环的更简单/标准/惯用的方法是使用
for。。。范围内

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

您可以使用
random.choices
从一个范围中选择10个值

x = int(input("Write a number: "))
values = list(random.choices(range(11), k=x))
对于更大的范围,您可能更愿意重复调用
random.randint

values = [random.randint(0,10) for _ in range(x)]

我想指出的是,
for
循环比
while
循环更可取,但Sam Stafford在这方面胜过了我!列表理解解决方案也很好

我知道你的代码只是一个例子,但是那些变量名真的很糟糕,小心点。无论如何,这里有一个
numpy
解决方案,也许有一天会派上用场

将numpy导入为np
num_to_gen=int(输入(“选择要生成的随机数:”)
rand\u nums=np.random.randint(低=0,高=11,大小=num\u to\u gen).tolist()
打印(兰特)

最后一个建议很容易就是最好的方法。但是要注意,使用
\uuu
作为虚拟变量可能会破坏它在交互式shell中的使用。最好检查输入是否是一个数字,而不是盲目地使用
int(输入(…)
,如果输入不代表一个数字(例如,如果用户键入“胡说八道”一词),则可能会出现运行时错误或字符串“xyz”。)请参见。