如何检查random.choice的打印值是否与“猜测”变量匹配

时间:2019-02-05 22:04:30

标签: python windows random choice

基本上,我正在写一个基本的“ hello world”代码来刷新我的记忆,我陷入了困境。我想从列表numbers中打印一个随机选择,我想检查我的初始x是否与随机选择的输出匹配。但是,当我运行代码时,即使数字不匹配,我得到的只是print("nice")。这是代码:

import random

numbers = [1, 2, 3, 4, 5, 6]
x = int(input("Enter your guess: "))

def random_choice(numbers):
    if x in numbers:
        print(random.choice(numbers))
        if numbers.count(x):
            print("nice")
        else:
            print("not nice")


random_choice(numbers)

1 个答案:

答案 0 :(得分:2)

x将以数字形式返回x的出现次数,因为在该代码点,您已经知道其中至少有一个if的副本(因为此行位于检查x in numbers的{​​{1}}内,所以它将始终返回一个正数,该正数隐式转换为True

一种可能的方法是存储随机值并与x进行比较:

import random

numbers = [1, 2, 3, 4, 5, 6]
x = int(input("Enter your guess: "))

def random_choice(numbers):
    if x in numbers:
        temp = random.choice(numbers)
        print(temp)
        if temp == x:
            print("nice")
        else:
            print("not nice")


random_choice(numbers)