Why does my python function return the wrong result? -
i'm attempting create simple python game, 'higher or lower'. i'm extremely new programming please give me improvements.
this have 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 part, works correctly. majority of game works , returns "correct!" or "incorrect!" based on user's input. however, time time report incorrect when user has chosen correct choice.
for example, previous card 1. when user entered higher, next card 13 reported higher being incorrect.
your cards being stored strings:
def generate_card(): return str(random.randint(1,13))
and string comparison isn't want want here:
>>> '13' > '2' false
this lexicographic comparison, want when, example, you're putting things in alphabetical order. higher/lower game, want numeric comparison. that, want keep card number, , change get_user_choice
converts user input number:
def get_user_choice(): choice = input("please enter 'higher' or 'lower': ") return int(choice)
Comments
Post a Comment