user4147697
user4147697

Reputation:

Why does my python function return the wrong result?

I'm attempting to create a simple Python game, 'higher or lower'. I'm extremely new to programming so please give me any improvements.

This is what I have so far:

import random
score = 0

def check_choice(lastcard, newcard, userInput):
    if newcard >= lastcard:
        result = "higher"
    else:
        result = "lower"

    if result == userInput:
        print("Correct! \n")
        return True
    else:
        print("Incorrect! \n")
        return False

def generate_card():
    return str(random.randint(1,13))

def get_user_choice():
    choice = input("Please enter 'higher' or 'lower': ")
    return choice

def change_score(result):
    global score
    if result:
        score += 1
    else:
        score -= 1

def play_game():
    play = True
    card = generate_card()
    while play:
        print ("Current card is: " + card)
        choice = get_user_choice()
        if choice == "stop":
            play = False
        newcard = generate_card()
        result = check_choice(card, newcard, choice)
        change_score(result)
        card = newcard


play_game()

For the most part, everything works correctly. The majority of the game works and returns "Correct!" or "Incorrect!" based on the user's input. However, from time to time it will often report back as incorrect even when the user has chosen the correct choice.

For example, the previous card was 1. When the user entered higher, the next card was a 13 but it reported back as higher being incorrect.

Upvotes: 0

Views: 182

Answers (2)

lvc
lvc

Reputation: 35069

Your cards are being stored as strings:

def generate_card():
    return str(random.randint(1,13))

And string comparison isn't want you want here:

>>> '13' > '2'
False

This is a lexicographic comparison, which is what you want when, for example, you're putting things in alphabetical order. But for a higher/lower game, you want a numeric comparison. For that, you want to keep the card as a number, and change get_user_choice so that it converts the user input into a number:

def get_user_choice():
    choice = input("Please enter 'higher' or 'lower': ")
    return int(choice)

Upvotes: 2

Yu Hao
Yu Hao

Reputation: 122383

The result is unexpected because the cards are stored with strings, not integers:

def generate_card():
    return str(random.randint(1,13))

Strings are compared lexicographical:

>>> 7 < 11
True
>>> "7" < "11"
False

Upvotes: 2

Related Questions