为什么随机发生器不工作?Python

2024-06-02 06:06:28 发布

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

我对Python还很陌生。当我运行python代码时,它什么都没有显示!有什么意见吗?你知道吗

import random 

q = 1
w = 2
e = 3
r = 4
t = 5
y = 6
u = 7
i = 8
o = 9
p = 10

lista = (q,w,e,r,t,y,u,i,o,p)

numero = random.choice (lista)


if numero == (q,w,e,r,t):
    print ("The colour is: Black")

if numero == (y,u,i,o,p):
    print ("The colour is: Red")

谢谢你, 里卡多·罗查


Tags: the代码importifisrandomred意见
3条回答

您将随机inttuple进行比较: 更改为:

if numero in (q,w,e,r,t):
    print ("The colour is: Black")

if numero in (y,u,i,o,p):
    print ("The colour is: Red")

获取%的一个选项是根据所需的percentlista分为两部分:

import random 

lista = ('q','w','e','r','t','y','u','i','o','p')

letter = random.choice (lista)

percent = 0.20
slice_here = int(len(lista)*percent)

print(lista[:slice_here]) #=> ('q', 'w')
print(lista[slice_here:]) #=> ('e', 'r', 't', 'y', 'u', 'i', 'o', 'p')

if letter in lista[:slice_here]:
    print ("The colour is: Red")

if letter in lista[slice_here:]:
    print ("The colour is: Black")

random.choice(lista)的结果是一个整数。您应该检查元组中是否存在:

if numero in (q,w,e,r,t):
    print ("The colour is: Black")

if numero in (y,u,i,o,p):
    print ("The colour is: Red")

相关问题 更多 >