dimanche 12 juillet 2020

How to create a conditional that works if an int is contained twice in a list

This quite simple game asks the user to guess a random number. The program ends when he guesses. I wanted to add a simple feature, i wanted notitfy the user when he used twice the same number. The problem is that the conditional that i wrote is always true, it prints "You already tried that number" every time.

I know how to make the program work, i just don't know what to write. It would be smart to say if guess is contained twice in previous_guess.

    # myNumber.py
# This game uses a home made function


def num():
    import random

    # Think a number
    computer_number = random.randint(1, 100)

    def is_same(target, number):
        if target == number:
            result = "Win"
        elif target > number:
            result = "Low"
        else:
            result = "High"
        return result

    # Start the game
    print("Hello.\nI have thought of a number between 1 and 100:")

    # Collect the user's guess as an integer
    guess = int(input("Can you guess it?"))
    # Use our function
    higher_or_lower = is_same(computer_number, guess)
    # run the game until the user is correct
    while higher_or_lower != "Win":
        if higher_or_lower == "Low":
            guess = int(input("Sorry you are too low. Try again"))
        else:
            guess = int(input("Sorry you are too high. Try again"))

        higher_or_lower = is_same(computer_number, guess)

This is the part i wanted to add

previous_guess = [guess]
if guess in previous_guess:
            print("You already tried with that number")

#previous_guess = []
#previous_guess.append(guess)
#I could also write it like this, same thing

Aucun commentaire:

Enregistrer un commentaire