Home > database >  If statement with list is producing inaccurate output
If statement with list is producing inaccurate output

Time:08-07

Code is:

import random

Cards = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]

user = int(input("Number\n"))
print(Cards[user])

computer = int(input("Number\n"))
print(Cards[computer])

if Cards[user] > Cards[computer]:
    print(f"You win {user} {computer}")
else:
    print(f"You Lose {computer} {user}")

Output is:

Number
11
K
Number
12
A
You win 11 12

Its meant to say "You Lose" Since K as in king of cards is lower than an A which stands for Ace. What am I doing wrong here?

CodePudding user response:

This behavior occurs because you are comparing strings, rather than ints.

>>> "K" > "A"
True

As the "cards" are arranged in ascending order, you only need to check if user is greater than computer. This will compare ints and work the way you expect.

As an aside, you should be verifying that the index you get from the user is a valid one for the length of the list. There are many ways to do this.

CodePudding user response:

As @Samwise already commented:

How would Python know (without you telling it somehow) that "K" is a king and "A" is an ace and that ace > king? What would you expect it to say if you asked it to compare, say, "X" and "Y"?

Use the index of the elements instead:

import random

cards = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]

user = input("Number\n")      # int() doesn't work in all cases
computer = input("Number\n")

if cards.index(user) > cards.index(computer):
    print(f"You win {user} {computer}")
else:
    print(f"You Lose {computer} {user}")

CodePudding user response:

Maybe you should compare the index which orders the cards by value

import random

Cards = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]

user = int(input("Number\n"))
print(Cards[user])

computer = int(input("Number\n"))
print(Cards[computer])

if user > computer:  # Changed here
    print(f"You win {user} {computer}")
else:
    print(f"You Lose {computer} {user}")

CodePudding user response:

As stated by @maggle, the way to do it is to just compare the integers user and computer.

Comparing the indexes (as stated by @puncher) does not work, as Cards.index("11") will return ValueError (as the integer 11 is not in the list cards).

  • Related