简体   繁体   English

Python-我的变量没有给我一个随机数来在函数中输出(模块=随机)

[英]Python- my variable doesn't give me a random number to output in a function (Module = Random)

The output is nothing when i enter all 5 numbers into each input, why is that?I tried all the different ways but i couldn't do it.当我在每个输入中输入所有 5 个数字时,输出什么都没有,这是为什么?我尝试了所有不同的方法,但我做不到。

Here is my code--这是我的代码--

    import random
r1 = random.randint(1, 5)
r2 = random.randint(1, 5)

print(r1, r2)

p1 = [int(input('1 - Enter a number from 1 to 5: ')), 'First Person']
p2 = [int(input('2 - Enter a number from 1 to 5: ')), 'Second Person']
p3 = [int(input('3 - Enter a number from 1 to 5: ')), 'Third Person']
p4 = [int(input('4 - Enter a number from 1 to 5: ')), 'Fourth Person']
p5 = [int(input('5 - Enter a number from 1 to 5: ')), 'Fifth Person']

if p1 == r1 or p1 == r2:
    print('ok')

if p2 == r1 or p2 == r2:
    print('ok')

if p3 == r1 or p3 == r2:
    print('ok')

if p4 == r1 or p4 == r2:
    print('ok')

if p5 == r1 or p5 == r2:
    print('ok')

You should add the indice, such as:您应该添加索引,例如:

if p1[0] == r1 or p1[0] == r2:
    print('ok')

First, I think there is an indentation problem at the beginning of your code.首先,我认为您的代码开头存在缩进问题。 To answer your question, the problem is that p1, p2,... are not ints, but a list such as [int, str] .要回答您的问题,问题在于 p1, p2,... 不是整数,而是一个列表,例如[int, str]
So, your tests your should look like:因此,您的测试应该如下所示:

if p1[0] == r1 or p1[0] == r2:
    ...

Also, I advise you to make your code easier to read by doing something like that:另外,我建议您通过执行以下操作使您的代码更易于阅读:

for p in [p1, p2, p3, p4, p5]:
    if p[0] in [r1, r2]:
         print('ok')

I don't understand the need for a list but in order to acheive what you're trying you will have to check the values against the element of the list by indexing and not the list itself.我不明白需要一个列表,但为了实现你正在尝试的东西,你必须通过索引而不是列表本身来检查列表元素的值。

It'd look something like this:它看起来像这样:

import random
r1 = random.randint(1, 5)
r2 = random.randint(1, 5)

print(r1, r2)

p1 = [int(input('1 - Enter a number from 1 to 5: ')), 'First Person']
p2 = [int(input('2 - Enter a number from 1 to 5: ')), 'Second Person']
p3 = [int(input('3 - Enter a number from 1 to 5: ')), 'Third Person']
p4 = [int(input('4 - Enter a number from 1 to 5: ')), 'Fourth Person']
p5 = [int(input('5 - Enter a number from 1 to 5: ')), 'Fifth Person']

if p1[0] == r1 or p1[0] == r2:
    print('ok')

if p2[0] == r1 or p2[0] == r2:
    print('ok')

if p3[0] == r1 or p3[0] == r2:
    print('ok')

if p4[0] == r1 or p4[0] == r2:
    print('ok')

if p5[0] == r1 or p5[0] == r2:
    print('ok')
import random

r1 = random.randint(1, 5)
r2 = random.randint(1, 5)

print(r1, r2)

numbers = [int(i) for i in input('Enter 5 numbers from 1 to 5: ').split()]

for i in numbers:
    if i == r1 or i == r2:
        print('ok')

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

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