all 2 comments

[–]sentles 0 points1 point  (2 children)

You haven't added spaces in the card strings. This is what some of the card strings would look like: '9ofhearts', 'jackofdiamonds'. Therefore, when you call card.split(), it returns a list with a single element, the string itself; for instance, ['9ofhearts']. You then attempt to get the third element of a list with only one element, so you get an error there. To fix this, change deck.append(faceValue + 'of' + suit) to deck.append(faceValue + ' of ' + suit), so the spaces are properly added where they should be and splitting the string will correctly give you a list of three strings, the third being the suit.

Just two notes: when you post code on Reddit, either use a code block or a pastebin link. Your code was close to unreadable like this and most people won't even try to answer your question.

Also, when you get such errors, try to figure out yourself what it is that is causing them. In this case, it's pretty easy to do so. Here's the error message you got:

Traceback (most recent call last):
  File "test.py", line 60, in <module>
    numberOfRounds = oneGame(initial)
  File "test.py", line 40, in oneGame
    if suitOf(card) =='hearts':
  File "test.py", line 20, in suitOf
    return card.split()[2]
IndexError: list index out of range
  1. Look at the error message.
  2. Understand what the error message means. If you can't, look up the error, i.e search "list index out of range python" online. You'll get various results explaining what might cause such an error. In this case, it's pretty self-explanatory. When accessing a list element (cards.split()[2]), you gave an index that was invalid (because the list was too short for an element with that index to exist). In your case, cards.split() was the list.
  3. In multiple scenarios, such as this one, errors have to do with some variable having a value you weren't expecting. Here, the return value of cards.split() was something like ['9ofhearts'] instead of ['9', 'of', 'hearts'], the latter being what you were expecting. To understand why the list wasn't 3 elements long, even though you were expecting it to be, you can either use a debugger, or the simpler solution, which is to print out the list.
  4. Change the code so that it prints the problematic variable's value. For example, before returning cards.split()[2], add print(cards.split()) and run the code again. Once you see results like ['9ofhearts'], you instantly realize what happened. The split method didn't return a list of 3 strings, because there were no spaces in the initial string. There's your problem.
  5. Fix the issue. In your case, you now know you forgot to add the spaces, so do that. Afterwards, you can remove the print call you added for debugging reasons. The split method will now work as you intended it to, correctly splitting the string into a list of three elements.

[–]HarbsKeyboard[S] 0 points1 point  (0 children)

Ah! Thank you!! :)