Python Connect Four game win function - python
I have most of my Python version of Connect Four coded, except for the win function and the gravity. Below is the code for determining if the game has been won yet.. It doesn't function, currently the only way the game ends is if all the spots are taken up. Any ideas?
winners = [ [1,2,3,4],[2,3,4,5],[3,4,5,6],[4,5,6,7],[8,9,10,11],[9,10,11,12],[10,11,12,13],[11,12,13,14],
[15,16,17,18],[16,17,18,19],[17,18,19,20],[18,19,20,21],[22,23,24,25],[23,24,25,26],[24,25,26,27],
[25,26,27,28],[29,30,31,32],[30,31,32,33],[31,32,33,34],[32,33,34,35],[36,37,38,39],[37,38,39,40],
[38,39,40,41],[39,40,41,42],[1,8,15,22],[8,15,22,29],[15,22,29,36],[2,9,16,23],[9,16,23,30],[16,23,30,37],
[3,10,17,24],[10,17,24,31],[17,23,31,38],[4,11,18,25],[11,18,25,32],[18,24,32,39],[5,12,19,26],[12,19,26,33],
[19,25,33,40],[6,13,20,27],[13,20,27,34],[20,28,34,41],[7,14,21,28],[14,21,28,35],[21,28,35,42],[1,9,17,25],
[9,17,25,33],[17,25,33,41],[8,16,24,32],[16,24,32,40],[15,23,31,39],[2,10,18,26],[10,18,26,34],[18,26,34,42],
[3,11,19,27],[11,19,27,35],[4,12,20,28] ]
def makeMove(self):
self.Player = self.game.Player
if self.game.Player == 'Black':
self.b.config(image=self.Black, command=self.invalidMove)
num = self.num
self.game.moves['Black'].append(num)
self.game.free.remove(num)
w = self.won(self.game.Player)
if self.game.moves['Black'] in winners:
self.game.turninfo.config(text=self.game.Player+' WON!')
elif self.game.free == [ ]:
self.game.turninfo.config(text='Game is a draw!')
else:
self.game.Player = 'Red'
self.game.turninfo.config(text=self.game.Player+"'s Turn")
elif self.game.Player == 'Red':
self.b.config(image=self.Red, command=self.invalidMove)
num = self.num
self.game.moves['Red'].append(num)
self.game.free.remove(num)
w = self.won(self.game.Player)
if contains(self.game.moves['Red'],winners):
self.game.turninfo.config(text=Player+' WON!')
for c in self.game.cells:
c.freeze()
elif self.game.free == [ ]:
self.game.turninfo.config(text='Game is a draw!')
for c in self.game.cells:
c.freeze()
else:
self.game.Player = 'Black'
self.game.turninfo.config(text=self.game.Player+"'s Turn")
I think your issue is that you are checking to see if a players moves match one of the win conditions exactly. This is possible but probably won't happen that often, for example a player might make the moves [2, 3, 1, 4] which should count as a win, but [2, 3, 1, 4] is not in winners so you will not get a match. Also, if it ever took a player more than four moves you would never get a winner for the same reason (since [6, 1, 2, 3, 4] wouldn't be found in winners either).
What you actually want to find out is if for any of the win conditions, all of the moves of the win condition were made by a player. This can be expressed like this:
for winner in winners:
won = True
for move in winner:
if move not in self.game.moves['Black']:
won = False
if won:
# game ending logic
break
This can be shortened considerably to the following (but it might be harder to follow):
if any(all(m in self.game.moves['Black'] for m in w) for w in winners)):
# game ending logic
Related
How to write a game on Python with lists and loop? [duplicate]
This question already has answers here: Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list? (6 answers) Closed 6 days ago. I wrote the code for this game, but it has problems. A game with one cube. Before the game, 3 players write numbers from 1 to 6 on a piece of paper. A dice is thrown. Now the task is to get numbers from 1 to 6. The person who gets 1 can cross out 1 on his sheet of paper. Then next person. The winner is the first to cross out all the numbers one by one. The idea is to create 3 lists and remove random number from each list in while loop The Pycharm show this problem: "if len(numbers_Berni) == 0: TypeError: object of type 'NoneType' has no len()" This is my code: numbers_Berni = [1, 2, 3, 4, 5, 6] numbers_Rolf = [1, 2, 3, 4, 5, 6] numbers_Rosa = [1, 2, 3, 4, 5, 6] import random print("Let's start, press ENTER to continue") while len(numbers_Rolf) > 0 or len(numbers_Rosa) > 0 or len(numbers_Berni) > 0: print("Press ENTER to make Berni throw the dice") rand = random.choice(numbers_Berni) print("Berni's current numbers:") numbers_Berni = numbers_Berni.remove(rand) print(numbers_Berni) if len(numbers_Berni) == 0: print("Berni win") print("Game over") quit() print("Press ENTER to make Rolf throw the dice") rand = random.choice(numbers_Rolf) print("Rolf's current numbers:") numbers_Rolf = numbers_Rolf.remove(rand) print(numbers_Rolf) if len(numbers_Rolf) == 0: print("Rolf win") print("Game over") quit() print("Press SPACE to make Rolf throw the dice") rand = random.choise(numbers_Rosa) print("Rosa's current numbers:") numbers_Rosa = numbers_Rosa.remove(rand) print(numbers_Rosa) if len(numbers_Rosa) == 0: print("Rosa win") print("Game over") quit() The idea is to create 3 lists and remove random number from each list in while loop
When you remove an element from the list you don't reassign the result of the remove function back to the original list. remove() does NOT return anything. Change numbers_Berni = numbers_Berni.remove(rand) to just numbers_Berni.remove(rand). Obviously you have to change the statements for numbers_Rolf and numbers_Rosa as well.
How to break a loop depending on answer from input, then move on with the rest of the program [duplicate]
This question already has answers here: How to make a while true statement in a program that already has a while true statement (4 answers) Closed last year. Hi so I'm very new to coding and I'm making a blackjack game for my high school project, I'm on the part where it asks the user to hit or stand and when they hit it asks them again until they bust or stand, I want it so once they stand the loop for asking them to hit or stand breaks but moves on with the rest of the code which is the logic for the dealer / computer to hit or stand. But when they do stand it just stops the entire program. How do I fix this? The code is not fully completed and I apologize for what probably is a big mess. # Import the required modules import random # Print welcome message print('Welcome To Blackjack!') # State the rules for the game print('This is blackjack. Rules are simple whoever has the biggest sum of the cards at the end wins. Unless someone gets 21 / blackjack or goes over 21 (bust). Bust is when a player goes over 21 and the lose. Once it is your turn you can choose to hit or stand, if you hit you get another card, if you stand it becomes the other persons turn. Your goal is to get the closest number to 21 without going over it. The game uses no suit cards. The values of the face cards are a Jack = 10, Queen = 10, King = 10, Ace = 11 or 1 whatever works the best. ') # Global Variables deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'] dealer_cards = [] player_cards = [] print('Dealing...') # Create the dealcard function to deal a card when needed def dealcard(turn): card = random.choice(deck) turn.append(card) deck.remove(card) # Removes the card out of the deck so it cant repeat. # Create the function to calculate the total cards that each player has def totalvalue(turn): totalvalue = 0 facecards = ['J', 'Q', 'K'] for card in turn: if card in range(1, 11): totalvalue += card # This adds the cards together elif card in facecards: # Checks if a card is a face card (J, Q, K,) totalvalue += 10 # This gives value to face cards else: # This checks if they get an ace and what works the best in case when they get an ace if totalvalue > 11: # If total is over 11 Ace counts as 1 totalvalue += 1 else: # If total is under 11 Ace counts as 11 totalvalue += 11 return totalvalue for dealing in range(2): dealcard(dealer_cards) dealcard(player_cards) print(f"The dealer's cards are {dealer_cards} and the total amount is {totalvalue(dealer_cards)}") print(f"Your cards are {player_cards} and your total amount is {totalvalue(player_cards)}") while True: # Take input from user playerchoice = (input('Would you like to \n1.Hit \nor \n2.Stay\n')) # Check what choice user chose and execute it if playerchoice == '1': dealcard(player_cards) print(f"You now have a total of {totalvalue(player_cards)} with these cards {player_cards}") continue # If they chose to stand move on to dealers / computers turn if playerchoice == '2': print(f"Your cards stayed the same {player_cards} with a total of {totalvalue(player_cards)}") print("What will the dealer do?...") break # Create dealer logic if totalvalue(dealer_cards) >= 18: print(f"The dealer chose to stand their cards are {dealer_cards} with a total of {totalvalue(dealer_cards)}") if totalvalue(dealer_cards) < 16: dealcard(dealer_cards) print(f"The dealer chose to hit their new cards are {dealer_cards} and their total is {totalvalue(dealer_cards)}") if totalvalue(dealer_cards) == totalvalue(player_cards): print(f"Its a tie you both have {totalvalue(player_cards)}") if totalvalue(dealer_cards) == 21: print(f"The dealer got blackjack! You lose...") break
I think what you are requesting is something like this. I wasn't sure if the program was supposed to keep running so you could play multiple games or that it only had to be able to play one game. if it has to be able to play multiple games you run into an issue with updating the global values. to get around this with the code you have you will have to copy the global values every time you played a new game. As you see this doesn't look too pretty but i tried to keep it as close as to what you wrote as possible. There's still some errors in the game I've posted so you'll still have to copy the deck and return the deck in the same way that the player cards have been returned. but that is for you to do :-) Starting function that copies the variables you already have and return them: def start(): for dealing in range(2): copy_dealer_cards = dealer_cards.copy() copy_player_cards = player_cards.copy() dealcard(copy_dealer_cards) dealcard(copy_player_cards) print(f"The dealer's cards are {copy_dealer_cards} and the total amount is {totalvalue(copy_dealer_cards)}") print(f"Your cards are {copy_player_cards} and your total amount is {totalvalue(copy_player_cards)}") return (copy_dealer_cards, copy_player_cards) Compare the result with. Here you could use the return value to keep score of how many games the player and dealer has each won: def comp(player_res, dealer_res): if dealer_res>player_res: print("Dealer wins\n\n") return 1 if dealer_res<player_res: print("Player wins\n\n") return -1 if dealer_res == player_res: print(f"Its a tie you both have {player_res}") return 0 The main function that plays the game with some updated logic and conditions. As well as a slightly modified while loop. def run() -> None: d_cards , p_cards = start() player_stay = False dealer_stay = False while not(dealer_stay and player_stay): # Take input from user if not player_stay: playerchoice = (input('Would you like to \n1.Hit \nor \n2.Stay\n')) # Check what choice user chose and execute it if playerchoice == '1': dealcard(p_cards) print(f"You now have a total of {totalvalue(p_cards)} with these cards {p_cards}") # If they chose to stand move on to dealers / computers turn if playerchoice == '2': print(f"Your cards stayed the same {p_cards} with a total of {totalvalue(p_cards)}") print("What will the dealer do?...") player_stay = True if not dealer_stay: # Create dealer logic if totalvalue(d_cards) >= 17: print(f"The dealer chose to stand their cards are {d_cards} with a total of {totalvalue(d_cards)}") dealer_stay = True if totalvalue(d_cards) <= 16: dealcard(d_cards) print(f"The dealer chose to hit their new cards are {d_cards} and their total is {totalvalue(d_cards)}") #If bust if totalvalue(p_cards) > 21: print(f"Player bust! You lose...\n\n") break if totalvalue(d_cards) > 21: print(f"Dealer bust! You win...\n\n") break #If blakcjack if totalvalue(p_cards) == 21: print(f"The player got blackjack! You win...\n\n") break if totalvalue(d_cards) == 21: print(f"The dealer got blackjack! You lose...\n\n") break #If hit then evaluate if dealer_stay and player_stay: comp(totalvalue(p_cards), totalvalue(d_cards)) print("New round begins...") break run() run()
I want it so once they stand the loop for asking them to hit or stand breaks but moves on with the rest of the code" Your current while loop while True: just repeats infinitely. Instead, you need a condition to specify when you want to continue. For example, you could do while playerchoice == '1': Note that this change will also require more changes to your code. In particular, you won't need the if statement any more because the body of the while loop will only repeat if the user chose "hit me". The logic for "stand" will go after the while loop. I leave the details for you to figure out.
Determining winner in Rock Paper Scissors [python]
I'm a beginner in python trying to create a RPS game where human is playing against a computer. The game is created such that it would be played over a number of determined rounds (best of 3 rounds). A draw is considered a point for each side. My problem is setting the while condition. Initially I did this: while (player_count + computer_count) != winning_score : where the game ends when all round are played. However there will be instances where not all rounds needs to be played and the winner can already be determined (because of draws, each player will get a point). How do I change the while condition such that when either players get winning_score/2 + 1, the game ends?
hi you can probably do it like this winning_count = winning_score/2+1 while(player_count < winning_count) and (computer_count < winning_count): ... Once either the player win or the computer win is more than the winning count, it goes to False and the loop breaks
Just in case you want to have another perspective on how to implement the game (and how to determine the winner), I exhort you to play with the following version: import random options = {1: 'Rock', 2: 'Scissors', 3: 'Paper'} def play(): score = [0, 0] while not any(wins == 3 for wins in score): print(f'SCORE\tUser: {score[0]} - PC: {score[1]}') user_selection = int(input('Enter your selection:{}> '.format( ''.join([f'\n{n}: {option}\n' for n, option in options.items()])))) pc_selection = random.randint(1, 3) print(f'{options[user_selection]} vs. {options[pc_selection]}') if user_selection in (pc_selection - 1, pc_selection + 2): print('User wins') score[0] += 1 elif user_selection == pc_selection: print('Draw') else: print('PC Wins') score[1] += 1 input('\n_____ ENTER TO PROCEED _____') winner = 'User' if score[0] == 3 else 'PC' print(f'\n{winner} won the match!') play() Hopefully you will find here something useful and new for your learning process.
Rock Paper Scissors (Python) - enumerating a list, pulling values based on logic, and comparing those to the original list
So the question is that there are N number of people in a line, playing rock paper scissors. Each person but me can only use one type of hand, represented as ['P', 'R', 'S', 'P'] for N hands. I can use any type and am at some arbitrary position A. I need to be able to know what position I have to play against once the list reaches me, so N-A-1. This means I have to iterate over the list, figure out a winner for each match up, and compare that result with the next position in the list, until it gets to me. What I've tried doing is creating an empty array of winners and then enumerating through the given list. Once there is a value for winners, it is compared to the value of the next index in the enumeration of the list. I've currently got no solution for what happens when I get to the last iteration, but currently my problem is that I'm getting an empty list as an output for winners. Any help on best practices for this type of logic with lists would be awesome, I haven't been able to find anything that fits. Code: def previous_and_next(n, a, formations): positions = list(formations) print(positions) winners = [] print(winners) for i, pos in enumerate(positions): nex = pos[i + 1] if not winners: if pos == 'R' and nex == 'P': winners.append(nex) elif pos == 'R' and nex == 'S': winners.append(pos) elif pos == 'R' and nex == 'R': continue elif pos == 'P' and nex == 'S': winners.append(nex) elif pos == 'P' and nex == 'R': winners.append(pos) elif pos == 'P' and nex == 'P': continue elif pos == 'S' and nex == 'R': winners.append(nex) elif pos == 'S' and nex == 'P': winners.append(pos) elif pos == 'S' and nex == 'S': continue if nex < len(positions-1): if winners[-1:] == 'P' and nex == 'R' or nex == 'P': continue elif winners[-1:] == 'R' and nex == 'R' or nex == 'S': continue elif winners[-1:] == 'S' and nex == 'P' or nex == 'S': continue elif winners[-1:] == 'P' and nex == 'S': winners.append(pos) elif winners[-1:] == 'R' and nex == 'P': winners.append(pos) elif winners[-1:] == 'S' and nex == 'R': winners.append(pos) def main(): previous_and_next(5,0,'PRSP') main()
You didn't respond to my comment asking for clarification. I'm posting an answer now which I will modify later once you've explained the prompt again. I've tried to interpret your original post into a sequence of steps (as I have understood them). Please let me know if this is the program flow you are going for: ['R', 'S', 'P', 'R', '?'] 0 1 2 3 A 1.) Player 0 and Player 1 play rock paper scissors. Player 0 wins, because (R)ock beats (S)cissors. 2.) The previous winner (Player 0) and Player 2 play rock paper scissors. Player 2 wins, because (P)aper beats (R)ock. 3.) The previous winner (Player 2) and Player 3 play rock paper scissors. Player 2 wins, because (P)aper beats (R)ock. 4.) The previous winner (Player 2) and Player A (you) play rock paper scissors. You must play (S)cissors to beat (P)aper EDIT - Additional question: Let's say we have: ['S', 'R', 'P', 'S', 'S', 'R', 'P'] 0 1 2 3 4 5 6 Rock beats Scissors Paper beats Rock Scissors beats Paper Scissors and Scissors TIE Now that we have arrived at the first tie, what happens exactly? You said that the two scissors are eliminated from the game, but how does the game continue? Do we jump to the Rock at index 5, and have them play against Paper at index 6, OR do we jump to the last valid winner (which in this example was Paper at index 2), and have them play against Rock at index 5? Thanks for your further information. EDIT - Here is a solution I came up with. To figure out how many hand changes you need to make, you need to sum the number of hand changes needed to beat the winning hand before you (which is either 0 or 1), and the number of hand changes you need to make to beat all hands after you. I'm sure there's a cuter way of doing it: from enum import Enum class Hand(Enum): Rock = 0 Paper = 1 Scissors = 2 class Game: def __init__(self, hands): self.hands = hands #staticmethod def get_winner_from_hands(hands): # This function, given a list of hands, will return the winning hand in that list. # In other words, it returns the type of hand that the winning player had in that list of hands. # This is especially useful if we pass in a sublist/slice of the whole list (the slice)... # ...would contain all hands before the player whose number of hand changes we are... # ... interested in computing. # This 'stack' list is meant to simulate the stack data-structure. # It's a stack of hands where, at any given moment, the most recent... # ...winning hand is on top of the stack. stack = [] while hands: # While there are hands left to be matched up if not stack: stack.append(hands.pop(0)) # 'top_hand' represents the hand that's on top of the stack... # ...(the most recent winning hand). top_hand = stack[-1] try: next_hand = hands.pop(0) except IndexError: # There were no more hands left to process. # This happens when we just had a tie (and cleared the stack as a result)... # ...but there was only one more hand left to process (and you need at least two for a match). # This can also happen if the 'hands' list that was passed in only had one hand in it. break winner = Game.get_match_winner(top_hand, next_hand) if winner is None: # It's a tie. stack.clear() elif winner is next_hand: stack.append(next_hand) try: # Return the last winning hand on the stack. return stack.pop() except IndexError: # If the stack was empty, there was no winning hand because of a tie. return None def get_number_of_hand_changes(self, hand_index): # Returns the number of times the player at index 'hand_index'... # ...must change their hand type in order to beat all other hands... # ...before them and after them. hands_before = self.hands[:hand_index] hands_after = self.hands[hand_index+1:] hand = self.hands[hand_index] # Who is the winner before us? previous_winner = Game.get_winner_from_hands(hands_before) if previous_winner is None or hand is Game.get_winning_hand(previous_winner): # All hands before 'hand_index' do not contribute to the total number of... # ...hand changes the player needs to make, either because of... # ...a tie, or we would beat the previous winner without changing hands anyway. hand_changes = 0 else: # We either tied with, or didn't beat the previous winner. hand_changes = 1 # Pick the hand we need to beat the previous winner. hand = Game.get_winning_hand(previous_winner) # This stack of hands represents the hand changes we need to make... # ...to beat the hands that come after us. At any given moment, the... # ...hand on top of this stack is the last hand change we've had to make. stack = [] hands = hands_after while hands: top_hand = hand if not stack else stack[-1] next_hand = hands.pop(0) if top_hand is not Game.get_match_winner(top_hand, next_hand): stack.append(Game.get_winning_hand(next_hand)) # The total number of hand changes we've had to make is... # ...the sum of the number of hand changes we've had to make to... # ...beat the winning hand before us, and the number of hand changes... # we've had to make to beat the hands after us. return hand_changes + len(stack) #staticmethod def get_winning_hand(hand): # Given a hand, return the hand that beats it. return Hand((hand.value + 1) % len(Hand)) #staticmethod def get_match_winner(hand_a, hand_b): # This function simulates a single Rock-Paper-Scissors match between two hands. # It returns the winning hand, or None if it's a tie. if hand_a is hand_b: return None return [hand_a, hand_b][Game.get_winning_hand(hand_a) is hand_b] def main(): hand_index = 4 hands = [ Hand.Rock, Hand.Scissors, Hand.Paper, Hand.Rock, Hand.Paper, # hand_index Hand.Paper, Hand.Paper, Hand.Scissors, Hand.Rock ] game = Game(hands) hand_changes = game.get_number_of_hand_changes(hand_index) print(hand_changes) return 0 if __name__ == "__main__": import sys sys.exit(main())
I'm not 100% sure what the question is asking, but it seems that your problem is that you are trying to compare a string to an int. Try nex = positions[i + 1] instead of nex = i + 1.
Inputting the character onto a map
def board10(): from random import randint coins = 0 board = [] charac = [] for i in range(10): row = [] for j in range(10): row.append('O') charac[x][y] = 'x' board.append(row) def print_board(board): for row in board: print (" ".join(row)) print ("Let's play Treasure Hunt!") print_board(board) print ("Total Coins:", coins) def random_row1(board): return randint(O, len(board) - 1) def random_row2(board): return randint(O, len(board) - 1) def random_col1(board): return randint(O, len(board[0]) - 1) def random_col2(board): return randint(O, len(board[0]) - 1) left_across1 = random_row1(board) right_across1 = random_row2(board) up_vertical1 = random_col1(board) down_vetical1 = random_col2(board) for turn in range(10): left_across2 = int(input("How many moves LEFT of the grid would you like to go?:")) right_across2 = int(input("How many moves RIGHT of the grid would you like to go?:")) up_vertical2 = int(input("How many moves UP of the grid would you like to go?:")) down_vertical2 = int(input("How many moves DOWN of the grid would you like to go?:")) if left_across2 == left_across1 and right_across2 == right_across1 and up_vertical2 == up_vertical1 and down_vertical2 == down_vertical1: print ("Congratulations! You landed on a Treasure Chest!") coins + 10 break else: if (left_across2 < 0 or left_across2 > 8) or (right_across2 < 0 or right_across2 > 8) or (up_vertical2 < 0 or up_vertical2 > 8) or (down_vertical2 < 0 or down_vertical2 > 8): print ("Oops, that's not even in the grid. Try Again") else: print ("Turn", turn + 1 ) print_board(board) print ("Total Coins:", coins) choice = ""; while loop ==1: print ("Menu") print ("a.) Play the Game") print ("b.) Quit the Game") print ("") choice = input("Select an option = ") loop =0 if choice == 'a': print("You have selected to Play the Game") print("Select which size grid you would like to play") print("1.) 8 x 8") print("2.) 10 x 10") print("3.) 12 x 12") choice=input("Select an option = ") if choice =='1': board8() elif choice == '2': board10() elif choice == '3': board12() else: print("You've picked an invalid choice") loop ==1 elif choice == 'b': print("You have selected to Quit the Game") quit() else: print("You've Picked an invalid Choice") loop==1 I am currently trying to make a treasure island game whereby the code prints out a 10x10 (trying to get this one to work first and then implement the rest of the sized maps) with an X in the bottom left of the map. The user then tells the program how many positions it wants to move the character up , left, right, and down and it then moves. It should also have randomly hidden coins in it to allow the character to gain points. Currently I cannot get the board to print with the X on the board. As it is now it returns the error Traceback (most recent call last): File "*file Root*/Controlled Assessment (1).py", line 91, in <module> board10() File "*file Root*/Controlled Assessment (1).py", line 17, in board10 charac[x][y] = 'x' NameError: name 'x' is not defined Any help would be greatly appreciated!
This comes from the line charac[x][y] = 'x' ^ When you index a list, as you're doing here, you should be using something that evaluates to a number. For example, if you have a variable named lst which holds the value [1, 2, 3, 4, 5] (a list of 5 numbers), then lst[0] is 1, lst[3] is 4, and so on. In addition to using a literal number, you can also use a variable which holds a number, like if foo is defined as 2 (which you might do with the code statement foo = 2), then lst[foo] is 3. This is what you're trying to do in your code, using the value stored under x to index the list charac. However, you never actually put a number in x, so Python doesn't know what to do with it. That's why you're getting this error. A very simple program which reproduces this error is lst = [1, 2, 3, 4, 5] print(lst[x]) A simplistic way to fix this program would be by changing it to the following: lst = [1, 2, 3, 4, 5] x = 2 print(lst[x]) In the future, if you try reducing your program to the smallest possible example that gives the error, one like what I just showed, it will become easy for you to find many of the errors you get.