how to check if the printed value of a random.choice matches with a "guess" variable

Question:

Basically, I’m writing a basic “hello world” code to refresh my memory and I’m stuck. I want to print a random choice from the list numbers and I want to check to see if my initial x matches with the output that was randomly chosen. However, when I run the code all I’m getting is print("nice") even when the numbers don’t match. Here is the code:

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)
Asked By: fodakall

||

Answers:

The numbers.count(x) will return the number of occurrences of x in numbers, since in that point of the code you already know that there is at least one copy of x in it (because this line is inside of the if that checks for x in numbers), it will always return a positive number which is implicit cast to True

A possible approach is to store the random value and compare to 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)
Answered By: Hemerson Tacon
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.