我的Python代码有问题吗

2024-03-29 11:45:09 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我在空闲时间所做的,但是由于某种原因,每当我尝试这段代码时,我得到了所有的东西。它的目标是从1到6中选择一个随机数。 相反,这是我得到的

number = 1,2,3,4,5,6

import random

for i in range(20):
    question= raw_input("Do you want a number from 1 to 6")
    if question == "yes":
        print number
    elif question == "no":
        print "Ok"

enter image description here


Tags: 代码inimportnumber目标forinputraw
3条回答

是的,这是错误的,在你的代码你只是打印列表的整数。要获得随机数,需要使用random.randint函数,如:

import random
for i in range(20):
    question= raw_input("Do you want a number from 1 to 6")
    if question == "yes":
        print random.randint(1, 6)
    elif question == "no":
        print "Ok"`

你要找的是^{}。你知道吗

示例代码:

>>> import random
>>> number = [1,2,3,4,5]

>>> for i in range(3): 
        print(random.choice(number)) 
=>  5
    4
    2

从python文档:

random.choice(seq)

Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.


至于代码中的问题,您不会得到任何随机生成的数字或从tuple中进行选择,而只是打印整个tuple。你知道吗

number的值是元组(1, 2, 3, 4, 5, 6),因此这是按预期工作的。 如果要从该集合中选择一个随机数,可以尝试使用random.sample函数

示例:

import random
result = random.sample(numbers, 1)    
print result  # will produce one number from the set

或者,如果您知道您总是要使用一个连续范围中的选择,那么您可以使用randint

相关问题 更多 >