Any help with python would be appricated

Hi guys, i am currently learning Python and have come across a problem that i cant figure out...i have googled the problem in my own words to no avail, i dont think i know enough to be able to ask the right question

anyway, im creating a program that randomly selects and card from a deck of 52, i can get this to work, but when a 1 comes up i want it to print "Ace", i have it printing "Ace" when a 1 comes up but it is also printing the 1 which i dont want,
any ideas?

this is where the program picks and number and a suit

and here is my attempt at the problem


if you would like me to explain more then please ask

thank you!

hmm looking at the code here, it shouldn't be able to come up as '1' for number, or number1. If you mean it prints both 'Ace' and '14' when number1 comes up ad 14 is because... That's how you wrote it :D

when number1 comes up as 14, on line 8 that ' if number1 == 14: ' is true, so it will print Ace. Then going down to the if statements that print suit, lets say suit is 1. then line ' if (suit == 1): ' is true as well. here you told it to print number and "Hearts". So just change it to print only the suit.

I think what you'll want to move to is something like this:

...
cardNumber = random.randint(2, 14) # all card values
...

you might try saving the suit value:

suitValue = 'Hearts'
if suit == 2:
suitValue = 'Spades'
if suit == 3:
suitValue = 'Clubs'
if suit == 4:
suitValue = 'Diamonds'

if cardNumber < 11:
print cardNumber, suitValue
if cardNumber == 11:
print 'Jack', suitValue
....

That's just one option.

thank you! worked perfectly :)

Remember to use if elif else, as having just a bunch of if statements means the program will run through them all regardless of which one it is, if elif else will run through them until one is true and skip the rest.

1 Like

ah yes, good point.

I'd recommend going to 3.4 I think the latest version is. That'd help a lot.

1 Like

Current version is 3.5, but most distros are likely not updated to it yet (it was just released)

It's almost always a good idea to keep data away from your logic
in this case the data is just a string that corresponds to a number, so
an enum is perfect (google "enumeration" for more info).

All programming solutions have pros and cons, I think it might be useful to see some other ways of solving this problem.

# using a dictionary (enum):
suits = {1: "Hearts", 2: "Spades", 3: "Clubs", 4: "Diamonds"}
suit = random.randint(1, 4)
print suits[suit]

# using random.choice, top-tip: in Python the standard library
# is really good and very comprehensive, very large toolbox
# for you to play with
suits = ["Hearts", "Spades", "Clubs", "Diamonds"]
suit = random.choice(suits)
print suit

There are even more ways to do it than those two, and those two could be made to be even shorter / cleaner. Happy programming, let me know if you have any questions about the code.

1 Like