Reputation: 175
Below code continues to print out You Win!
even though the computer_card
is higher.
import random
computer_card = random.choice([2,3,4,5,6,7,8,9,10,11,12,13,14])
player_card = raw_input('Please pick a card \n')
if player_card == 'Jack' or player_card == 'jack':
player_card = 11
if player_card == 'Queen' or player_card == 'queen':
player_card = 12
if player_card == 'King' or player_card == 'king':
player_card = 13
if player_card == 'Ace' or player_card == 'ace':
player_card = 14
if computer_card == player_card:
print 'Computer Choice: ', computer_card
print 'Player Choice: ', player_card
print 'Tie!'
elif computer_card > player_card:
print 'Computer Choice: ', computer_card
print 'Player Choice: ', player_card
print 'Computer Wins!'
elif computer_card < player_card:
print 'Computer Choice: ', computer_card
print 'Player Choice: ', player_card
print 'You Win!'
else:
print 'I am not sure what is really going on if you got to this line.'
Upvotes: 1
Views: 77
Reputation: 4565
The problem:
The input read by raw_string() is converted to string. So the line,
player_card=raw_input()
reads the input, convert it to a string and put it in player_card. And '1' > 9
One Possible Fix:
Change the comparison flow and convert the input to int if the input is not ['jack', 'queen', 'king' or 'ace']
if player_card == 'Jack' or player_card == 'jack':
player_card = 11
elif player_card == 'Queen' or player_card == 'queen':
player_card = 12
elif player_card == 'King' or player_card == 'king':
player_card = 13
elif player_card == 'Ace' or player_card == 'ace':
player_card = 14
else:
player_card = int(player_card)
Further Improvement: Although this solution should fix the immediate problem, the code can be heavily improved. Some improvement suggestions,
Ensure your code can handle invalid input from user [never trust user input]
Use a dict or list to convert user input to a numeric value instead of handling cases one by one.
Upvotes: 3
Reputation: 133
raw_input
puts a string into the variable player_card
. When the player chooses King, Queen, Ace, Jack, the value of player_card
is changed to int by the if
statements. But if the player_card
is something other than these, the value in player_card
remains a string. Like @Fallen said, this can be fixed by converting player_card
to int.
Upvotes: 0