-2

I am new at Python, and I am building a blackjack game as a capstone project. I think the code is doing pretty well besides a random error that I keep randomly getting different times of running the code. Sometimes the code will run perfectly but, sometimes it randomly just crashes when it hits the below code. sometimes it happens in the beginning and sometimes it may happen when it is going through the while loop again. Sometimes it goes through the same process and never has an issue.

Could someone explain why I keep getting this error? I understand what the error means but, non- of the codes are out of range?? or is it??

Traceback (most recent call last): File "C:\Users\carlo\Documents\training\confusion_list_call.py", line 49, in initial_card() File "C:\Users\carlo\Documents\training\confusion_list_call.py", line 24, in initial_card computer_card.append(cards[random.randint(0,len(cards))]) IndexError: list index out of range

import random

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

computer_card = []
user_card = []
computer_total = 0 
user_total = 0


def computer_deal():
    global computer_card
    computer_card.append(cards[random.randint(0,len(cards))])

def user_deal():
    global user_card
    user_card.append(cards[random.randint(0,len(cards))])

def initial_card(): 
  for _initial in range(1, 3): 
        global user_card 
        global computer_card 
        user_card.append(cards[random.randint(0,len(cards))]) ##randomly happens here or next line
        computer_card.append(cards[random.randint(0,len(cards))]) 

def sum_cards(): 
  global computer_total 
  global user_total
  user_total = 0
  computer_total = 0
  for total_c in computer_card:
    computer_total += total_c 
  for total_u in user_card:
    user_total += total_u

def reset_game():
  global computer_total 
  global user_total 
  global computer_card 
  global user_card 
  computer_total = 0
  user_total = 0
  computer_card.clear()
  user_card.clear()
  

continue_game = True
while continue_game:  
  initial_card() 
  print(f"Your cards: {user_card} \nComputer's Card {computer_card[0]}") 
  choice = input("Would you like another card 'y' or 'n' \n ") 
  
  no_bust = True 
  if choice == 'y':
    
    while no_bust:
      user_deal()
      sum_cards()
      print(f"Users new deck is: {user_card}") 
      print(f"Computer's total: {computer_total} and your total: {user_total}\n ")
      
      if user_total > 21: 
        print("You loss!")
        no_bust = False 
      elif computer_total == user_total:
        print("push: tied! ")
        no_bust = False
      else: 
        choice = input("Would you like another card 'n' or 'y'")
        if choice == 'y': 
          no_bust = True
        if choice == 'n': 
          if computer_total == user_total:
            print("push: tied! ")
          no_bust = False
  
  
  if choice == 'n': 
    if computer_total >= 17 and computer_total < 21: 
      if computer_total > user_total: 
        print(f"You loss!, Computer's total: {computer_total} and your total: {user_total}")
      else:
        print(f"You Win!, Computer's total: {computer_total} and your total: {user_total}")
  
    under_17 = True
    while under_17: 
      if computer_total < 17: 
        computer_deal() 
        sum_cards() 
        print(f"test3: computers new deck ~~~ > {computer_card}\nTest4: computers new total ~~~~ > {computer_total}")
        if computer_total == user_total:
          print("Game is tied: push")
          under_17 = False
        elif computer_total > 21:
          print("Computer has bust, You won!")
          under_17 = False
        elif computer_total >= 17 and computer_total <= 21:
          if computer_total > user_total:
            print(f"test5: Computer's total: {computer_total} and your total: {user_total}")
            print("You lose!")
            under_17 = False
          if computer_total < user_total:
            print("You win!")
            under_17 = False
        else:
          under_17 = True
  
  continue_choice = input("Would you like to play another game, 'y' or 'n'")
  if continue_choice == 'n':
    print("Thank you for playing Black Jack, have a good day!")
    continue_game = False
  if continue_choice == 'y':
    reset_game()
    continue_game is True

I know the functions are messy. I have not learned how to use classes yet and so I don't know how to be tidy yet. but I did remove function parameters in initial_cards() to avoid passing empty list for now... but, I doubt that was the issue. I also change my indents from tabs to space... not sure if that is an issue.

  • Does this answer your question? [How can I randomly select an item from a list?](https://stackoverflow.com/questions/306400/how-can-i-randomly-select-an-item-from-a-list) – Joe Aug 06 '23 at 14:09
  • 1
    "But it is not". No, the chance that python is lying to you, or the fact you've found a bug, is practically zero. It's the wrong way to approach debugging – roganjosh Aug 06 '23 at 14:24
  • @roganjosh Thank you for the life lesson. that was supposed to be a statement with a "?" which I missed. Stating I don't see the issue because in my head it seems correct while deep inside, I know it's truly not. – Carlos Colón Aug 06 '23 at 15:17
  • @JohnGordon wow... I knew this and I completely missed it. I was treating it like a For loop range... correct! Thank you all for the help. Shouldn't have missed it. – Carlos Colón Aug 06 '23 at 15:18
  • The main thing is that you internalise this lesson. You'll go far if you're willing to accept that it's you that is wrong, no matter how much you wanna yell at the console output :P (of course, there are cases when it's wrong but if we're talking base python....) – roganjosh Aug 06 '23 at 15:22
  • @roganjosh I knew I was the issue all this time, if you look inside the body of text, you can see where I question myself. I see your ":P", so I know you meant well (maybe not?). However, next time you could give a lesson with an explanation without jumping into conclusions it would also help. As for the lesson, I agree. the chances of Python being wrong is 0%. but as long as you understand to read the entirety of a question before assuming, then that would make two of us in a good path! – Carlos Colón Aug 06 '23 at 15:39
  • I did mean well, and I'm glad you picked up on my intentions. I don't have time to give a lesson to everyone that posts, nor was I jumping to conclusions beyond what I thought might fast-track us to a solution – roganjosh Aug 06 '23 at 17:06

2 Answers2

0

Lists start indexes at indice 0, you are calling for a number between 0 (which is correct) and len(list), but its supposed to be len(list) - 1, counteracting the offset of the first element starting at 0.

user_card.append(cards[random.randint(0,len(cards)-1)])

Will cause you not to look at an index 1 larger that your largest index in your list.

Odin Mostert
  • 62
  • 1
  • 7
0

The range given to random.randint is inclusive. Therefore, given a list (mylist) then:

mylist[random.randint(0, len(mylist))]

...will cause an IndexError if randint returns a value equal to the length of the list.

Remember that for a non-empty list of length N the inclusive range of valid indexes is:

-N : N-1
DarkKnight
  • 19,739
  • 3
  • 6
  • 22