Find substring in string compared to list - python
I am using python to create a quiz for a school project. I want to have a list of names and question answers that people cannot input. (BC they are inappropriate). Whenever i use the code i have now, it says that any input is one of the blocked ones. I am using an in-browser editor(No pip installations are available to me).
This is my code. I have the list of blocked strings in a variable called "Banned" At first this piece of code worked, but eventually when anyone played it, the code would block all inputs, not just the ones in the Banned list.
import os
import random
print("No Capitals!")
cheatcode = ""
randlist = ["Shiny Cupcake","Good Puppy","Sunshine","Pretty Painting","Happy Trees","Soft Kitten","in love","starstuck"]
randname = random.randrange(0,6)
playscore = 0
question = 0
idkbanned = ["idk","na","n/a","urmom","ur mom","yourmom","your mom","duh"]
banned = ["ur","mom","your mom","yourmom","daddy"]
notallowed = ("Warning, Idk, N/A and duh are not allowed, answering as ""your mom"" is obnoxious")
playname = input("What is your preferred name? ")
playername = (str.lower(playname))
if playername == ("sudo su"):
playername = "{#root}"
pset = input("Set Points? ")
if pset == "y":
points = input("Points ")
point = int(points)
playscore = point
dev = input("question ")
question = int(dev)
#elif [x for x in banned if x in playername]:
# print("Yeah, NO" + " Nice try...deducting 20 points for stupidity")
# playscore -= 20
# playername = randlist[randname]
elif playername == cheatcode:
print("Nice!")
print("Score:")
print("300")
playscore += 300
playername = ("Superuser")
playscore -= 300
else:
question = 0
enc = ["you can do this","never doubt yourself","good effort","almost"]
incorrectnum = random.randrange(0,3)
questions = [
"What does the prime meridian run through",
"what kind of orbit draws a line through a majority of the 7 wonders of the ancient world", "what is the largest metropoitan area in the world that does not body water?","The Kaliningrad oblast borders what body of water", "What country has the lowest people per square mile?","how many time zones does russia span?", "what does AMS stand for","T/F:mount everest is the tallest point on earth","T/F:australia is narrower than the moon","What are citizens of Sudan called","Does Japan's traffic run on the left or right"]
answers = [
["england","observatory","royal observatory"],
["two day","two","2"], "johannesburg","baltic sea", "namibia", "11", "accelerator mass spectrometry", ["false","f"],["false","f"],"sudanese","left"
]
idkount = 0
print("Hello, " + playername)
qai1n = input(questions[question] + "? ")
if qai1n in answers[question]:
print("correct")
playscore += 10
print("score: ")
print(playscore)
question += 1
elif qai1n in idkbanned:
idkount += 1
if idkount > 3:
print("No more IDK, N/A, or your mom, " + playername + " You are stalling")
elif idkount > 3:
print(notallowed + ", " + playername)
playscore -= 10
question += 1
else:
print("Wrong, but " + enc[incorrectnum])
question += 1
qai2n = input(questions[question] + "? ")
if qai2n in answers[question]:
print("correct")
playscore += 10
print("score: ")
print(playscore)
question += 1
elif qai2n in idkbanned:
idkount += 1
if idkount > 3:
print("No more IDK, N/A, or your mom, " + playername + " You are stalling")
elif idkount > 3:
print(notallowed + ", " + playername)
playscore -= 10
question += 1
else:
print("Wrong, but " + enc[incorrectnum])
question += 1
qai3n = input(questions[question] + "? ")
if qai3n in answers[question]:
print("correct")
playscore += 10
print("score: ")
print(playscore)
question += 1
elif qai3n in idkbanned:
idkount += 1
if idkount > 3:
print("No more IDK, N/A, or your mom, " + playername + " You are stalling")
elif idkount > 3:
print(notallowed + ", " + playername)
playscore -= 10
question += 1
else:
print("Wrong, but " + enc[incorrectnum])
question += 1
qai4n = input(questions[question] + "? ")
if qai4n in answers[question]:
print("correct")
playscore += 10
print("score: ")
print(playscore)
question += 1
elif qai4n in idkbanned:
idkount += 1
if idkount > 3:
print("No more IDK, N/A, or your mom, " + playername + " You are stalling")
elif idkount > 3:
print(notallowed + ", " + playername)
playscore -= 10
question += 1
else:
print("Wrong, but " + enc[incorrectnum])
question += 1
qai5n = input(questions[question] + "? ")
if qai5n in answers[question]:
print("correct")
playscore += 10
print("score: ")
print(playscore)
question += 1
elif qai5n in idkbanned:
idkount += 1
if idkount > 3:
print("No more IDK, N/A, or your mom, " + playername + " You are stalling")
elif idkount > 3:
print(notallowed + ", " + playername)
playscore -= 10
question += 1
else:
print("Wrong, but " + enc[incorrectnum])
question += 1
qai6n = input(questions[question] + "? ")
if qai6n in answers[question]:
print("correct")
playscore += 10
print("score: ")
print(playscore)
question += 1
elif qai6n in idkbanned:
idkount += 1
if idkount > 3:
print("No more IDK, N/A, or your mom, " + playername + " You are stalling")
elif idkount > 3:
print(notallowed + ", " + playername)
playscore -= 10
question += 1
else:
print("Wrong, but " + enc[incorrectnum])
question += 1
qai7n = input(questions[question] + "? ")
if qai7n in answers[question]:
print("correct")
playscore += 10
print("score: ")
print(playscore)
question += 1
elif qai7n in idkbanned:
idkount += 1
if idkount > 3:
print("No more IDK, N/A, or your mom, " + playername + " You are stalling")
elif idkount > 3:
print(notallowed + ", " + playername)
playscore -= 10
question += 1
else:
print("Wrong, but " + enc[incorrectnum])
question += 1
qai8n = input(questions[question] + "? ")
if qai8n in answers[question]:
print("correct")
playscore += 10
print("score: ")
print(playscore)
question += 1
elif qai8n in idkbanned:
idkount += 1
if idkount > 3:
print("No more IDK, N/A, or your mom, " + playername + " You are stalling")
elif idkount > 3:
print(notallowed + ", " + playername)
playscore -= 10
question += 1
else:
print("Wrong, but " + enc[incorrectnum])
question += 1
qai9n = input(questions[question] + "? ")
if qai9n in answers[question]:
print("correct")
playscore += 10
print("score: ")
print(playscore)
question += 1
elif qai9n in idkbanned:
idkount += 1
if idkount > 3:
print("No more IDK, N/A, or your mom, " + playername + " You are stalling")
elif idkount > 3:
print(notallowed + ", " + playername)
playscore -= 10
question += 1
else:
print("Wrong, but " + enc[incorrectnum])
question += 1
qai10n = input(questions[question] + "? ")
if qai9n in answers[question]:
print("correct")
playscore += 10
print("score: ")
print(playscore)
question += 1
elif qai10n in idkbanned:
idkount += 1
if idkount > 3:
print("No more IDK, N/A, or your mom, " + playername + " You are stalling")
elif idkount > 3:
print(notallowed + ", " + playername)
playscore -= 10
question += 1
else:
print("Wrong, but " + enc[incorrectnum])
question += 1
qai11n = input(questions[question] + "? ")
if qai11n in answers[question]:
print("correct")
playscore += 10
print("score: ")
print(playscore)
question += 1
elif qai11n in idkbanned:
idkount += 1
if idkount > 3:
print("No more IDK, N/A, or your mom, " + playername + " You are stalling")
elif idkount > 3:
print(notallowed + ", " + playername)
playscore -= 10
question += 1
else:
print("Wrong, but " + enc[incorrectnum])
question += 1
qai12n = input(questions[question] + "? ")
if qai12n in answers[question]:
print("correct")
playscore += 10
print("score: ")
print(playscore)
question += 1
elif qai12n in idkbanned:
idkount += 1
if idkount > 3:
print("No more IDK, N/A, or your mom, " + playername + " You are stalling")
elif idkount > 3:
print(notallowed + ", " + playername)
playscore -= 10
question += 1
else:
print("Wrong, but " + enc[incorrectnum])
question += 1
print("Score")
print(playscore)
This is what I get when using any name(A as an example)
Console: What is your preferred name? A Yeah, NO Nice try...deducting 20 points for stupidity Hello, Shiny Cupcake What does the prime meridian run through?
I have tried
if playername in list(Banned)
I know that my code is not DRY.
Uncomment:
#elif [x for x in banned if x in playername]:
# print("Yeah, NO" + " Nice try...deducting 20 points for stupidity")
# playscore -= 20
# playername = randlist[randname]
And you'll have fixed it.
You're correct the in keywork is what you're looking for but your code is not in the best order
banned = ["ur","mom","your mom","yourmom"]
playername = input("your name")
if playername in banned:
print("good try")
else:
print("welcome "+playername)
you might also want to create a method to avoid repeating the same verification over and over again. A good way to stop the game from continuing is to raise an exception you migth want to check that concept but this will stop the execution
def checkProfanity(word):
if word in banned:
raise Exception("No cursing")
Besides that this is not the best way to check for the presence of a string in the input.
for word in banned:
if playername.__contains__(word):
print("good try")
will also filter things like 'xxx mom xxx'
Related
How do I add a new line before appending(+=) my variable with another variable in python?
I am using Rasa X as my front end. I can't see how that would have anything to do with it, but I figured I will mention it just in case. Anyway, I have a variable that is collecting cell values from my excel sheet. I am using a loop statement add the values to my variable "requested_information". After the loop finishes, I add the string "\n" and my variable "missing_info" to it. When requested_information is printed, the new line is not in there. Here is the text result: And here is my code: for column in load_data.column_names: project_name_cell = str(sheet["B{}".format(row)].value) main_cell = str(sheet["" + column + "{}".format(row)].value) if project_id_provided == False: requested_information += "The " + load_data.column_names[column] + " for project " + project_name_cell + " is " + main_cell + ".\n" else: if main_cell == "n/a" or main_cell == None: missing_info_list.append(load_data.column_names[column]) continue if column == "E" or column == "G" or column == "I" or column == "J": requested_information += "The " + load_data.column_names[column] + " is " + phone_formatter(main_cell) + ".\n" elif column == "M" or column == "N" or column == "O" or column == "P": requested_information += "The " + load_data.column_names[column] + " is " + "${:,.2f}".format(float(main_cell)) + ".\n" elif column == "Q": requested_information += "The " + load_data.column_names[column] + " is " + "{:.2%}".format(float(str(main_cell))) + ".\n" elif column == "D" or column == "F" or column == "H": if main_cell != None or main_cell == "": if rasa_actions_settings.include_email_functions == False: requested_information += ("The " + load_data.column_names[column] + " is " + main_cell + ".\n") #else: ##NOTE - Uncomment procedures to enable personal emails being attached to the employees' contact info #email = email_functions.GetEmailAddress(main_cell) #firstName = main_cell.split(" ") #requested_information += ("The " + load_data.column_names[column] + " is " + main_cell + " and " + firstName[0] + "'s email address is " + email + ".\n") elif column == "R": date = main_cell.split(" ")[0] requested_information += "The " + load_data.column_names[column] + " is " + "{}/{}/{}".format(date[5:7], date[8:], date[0:4]) + ".\n" else: requested_information += "The " + load_data.column_names[column] + " is " + main_cell + ".\n" project_id_provided = True if len(missing_info_list) > 0: missing_info += " There doesn't seem to be any information for the following catagories: \n" first_item_used = False for missing_catagory in missing_info_list: if first_item_used == False: first_item_used = True missing_info += missing_catagory else: missing_info += ", " + missing_catagory if len(missing_info_list) == 1: missing_info = " There doesn't seem to be any information for the " + missing_info_list[0] requested_information += "\n" + missing_info + "." #NOTE - HERE, THE STRINGS ARE COMBINED dispatcher.utter_message(requested_information)
Why isn't the score showing correctly? [closed]
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers. This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers. Closed 2 years ago. Improve this question I'm still a beginner in python, so I decided to make a rock, paper game. For some reason, when the user or computer wins, it doesn't give them a point until the next round. import random games = int(input("")) #how many games usersc = 0 compsc = 0 for x in range(games): score = (str(usersc) + "-" + str(compsc)) user = input("") #ROCK, PAPER, SCISSORS comp = random.randint(0,2) if user == 'ROCK': if comp == 0: print("tie " + score) elif comp == 1: compsc += 1 print("loss " + score) else: usersc += 1 print("win " + score) elif user == 'PAPER': if comp == 0: usersc += 1 print("win " + score) elif comp == 1: print("tie " + score) else: compsc += 1 print("loss " + score) elif user == 'SCISSORS': if comp == 0: compsc += 1 print("loss " + score) elif comp == 1: usersc += 1 print("win " + score) else: print("tie " + score) else: print("try again") if compsc > usersc: print("loss") elif usersc > compsc: print("win") else: print("tie") For example, when the computer wins, it says loss 0-0 when it should say loss 0-1, but then the next round it'll say 0-1. Any help would be appreciated.
Problem is that you store score in a variable before incrementing it so you will always be 1 game behind. The simplest way to ensure the score is always correct would be to create a function to get the score like this... def get_score(): return str(usersc) + "-" + str(compsc) This would ensure the latest user and comp score values are always used. Using this the code becomes... import random games = int(input("")) #how many games usersc = 0 compsc = 0 def get_score(): return str(usersc) + "-" + str(compsc) for x in range(games): user = input("") #ROCK, PAPER, SCISSORS comp = random.randint(0,2) if user == 'ROCK': if comp == 0: print("tie " + get_score()) elif comp == 1: compsc += 1 print("loss " + get_score()) else: usersc += 1 print("win " + get_score()) elif user == 'PAPER': if comp == 0: usersc += 1 print("win " + get_score()) elif comp == 1: print("tie " + get_score()) else: compsc += 1 print("loss " + get_score()) elif user == 'SCISSORS': if comp == 0: compsc += 1 print("loss " + get_score()) elif comp == 1: usersc += 1 print("win " + get_score()) else: print("tie " + get_score()) else: print("try again") if compsc > usersc: print("loss") elif usersc > compsc: print("win") else: print("tie")
When you are printing loss+score or win+score, first update score as score = (str(usersc) + "-" + str(compsc)) and then print it.
I have an indentationerror: Expected an indented block
hello below is where my code is coming with an issue at line 64 near quiz = difficulty_level(user_level) can anyone help? every time i run this it comes in with this error and for the life of me i cannot figure out what is going on or what is wrong def play(): quiz = difficulty_level(user_level): print print quiz print "\nYou have only 5 tries best of luck.\n" answers_list = relate_answer(user_level) blanks_index = 0 answers_index = 0 number_of_guesses = 5 guesses_limit = 0 while blanks_index < len(blanks): user_answer = raw_input("type in your answer for " + blanks[blanks_index] + ": ") if check_answer(user_answer,answers_list,answers_index) == "Correct": print "nice job! that is the right answer!\n" quiz = quiz. replace(blanks[blanks_index],user_answer) blanks_index += 1 answers_index += 1 number_of_guesses = 5 print quiz if blanks_index == len(blanks): print "Congrats" else: number_of_guesses -= 1 if number_of_guesses == guesses_limit: print "Game over!" break elif number_of_guesses < guesses_limit: print "invalid" break else: print "incorrect try one more time" print "You have" + str(number_of_guesses) + "This many guesses left" play()
Change while blanks_index < len(blanks): user_answer = raw_input("type in your answer for " + blanks[blanks_index] + ": ") if check_answer(user_answer,answers_list,answers_index) == "Correct": to while blanks_index < len(blanks): user_answer = raw_input("type in your answer for " + blanks[blanks_index] + ": ") if check_answer(user_answer,answers_list,answers_index) == "Correct":
Can't call list from within class.
When I run the code I get the error message: "AttributeError: type object 'Player' has no attribute 'hkslist'" Why can't I call the list from within the class? The Idea is that the list is supposed to choose one of two of the functions from within the list and then run that once it's called upon. Full code: import random from time import * class Colors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' class Player: coins = 100 health = 100 p = 3 #Potions hoursslept = 0 def __init__(self): random.seed() print("init instance variables here") #self.coins = random.randint(100, 500) Förlegad kod. def hk1(): print("Du sprang iväg") def hk2(): #print("Du försökte springa iväg men trillade och slog i knät: - 20 HP") print("Du sprang iväg") sleep(3) print("men du trillar och slår i knät: -20 HP") self.health = self.health - 20 print("Your health is: " + str(self.health), " HP") #Fortsätt 'storyn' def hkf1(): print("Du besegrade håkan") print("Du tar hans droger och säljer det själv till Eleverna: +150 coins") print("Your health is ", str(self.health), " HP") self.coins = self.coins + 150 print("You have: ", str(self.coins), " coins") def hkf2(): print("Håkan besegrade dig: -50 HP") print("Your health is ", str(self.health), " HP") print("You have: ", str(self.coins), " coins") self.coins = self.coins + 150 self.hkslist = [hk1, hk2] self.hkflist = [hkf1, hkf2] self.indhks = random.randint(0,len(self.hkslist)-1) self.indhkf = random.randint(0,len(self.hkflist)-1) def report_status(self): status_message = "Your health is %s, \nCoins left %s" % (self.health, self.coins) return status_message william = Player() hakan = Player() print("Welcome to a poorly made text-based game:") print("you have ", william.p, " potions") print("Your health is ", str(william.health), " HP") print("You have: ", str(william.coins), " coins") while True: print("Commands: add, drink, coins, sleep, quest") a = input("Enter a command: ") if a == "add" or a == "Add" or a == "buy" or a == "Buy": if william.coins == 0: print("You can't afford a potion") else: william.coins = william.coins - 25 william.p = Player.p + 1 print("You bought a potion for 25 coins") print("You have ", william.coins, " coins left") print("you have ", william.p, " potions") print("Your health is now ", str(william.health), " HP") if a == "drink": if Player.p == 0: print("You can't drink any potions.") print("You have zero potions left!") print("Your health is ", str(william.health), " HP") elif william.health >= 250: print("Your health is already maxed out. You can't drink a potion.") print("you have ", str(william.p), " potions") print("Your health is ", str(william.health), " HP") else: william.health = william.health + 20 william.p = william.p - 1 print("you have ", william.p, " potions") print("Your health is ", str(william.health), " HP") if a == "sleep": if william.health >= 250: print("Your health is already maxed out. You can't drink a potion.") print("Your health is ", str(william.health), " HP") else: william.health = william.health + 5 print("you have ", str(william.p), " potions") print("Your health is ", str(william.health), " HP") if a == "I" or a == "i" or a == "inv" or a == "inventory": if william.p == 0: print("Your backpack is empty") else: print("you have ", str(william.p), " potions") print("Your health is ", str(william.health), " HP") if a == "quest": quest = input("Choose from quest: 1, 2 or 3 ") if quest == "1" or quest == "option 1" or quest == "opt 1": print("Du vandrar runt på Rudbeck när du ser Håkan, din samhällslärare, i ett mörkt hörn") print("Du väljer att gå närmare för att investigera.") print("Håkan står och säljer knark till eleverna.") hk = input("Vad gör du? Spring: Slåss:") if hk == "Spring" or hk == "spring": Player.hkslist[Player.indhks]() if hk == "slåss" or hk == "Slåss" or hk == "s": Player.hkflist[Player.indhkf]() if a == "coins": if william.coins >= 500: print("You're filthy rich!!!") print("You have: ", str(william.coins), " Coins") else: print("You have: ", str(william.coins), " Coins") #Debug tools if a == "add coin" or a == "AC" or a == "ac" or a == "more": extracoins = input("How many coins do you want?: ") Player.coins = int(extracoins) print("You now have: ", str(william.coins), " Coins")
hkslist is an attribute of an instance of Player not of the Player class itself. You can see this in the definition of hkslist (self.hkslist = [hk1, hk2]) where hkslist is defined on self. If you want to access hkslist you'll need to create an instance of Player. For example: player = Player() player.hkslist[player.indhks]()
Edit: Python - Going from 1 Player to Two Player Game Using Functions
I posted something similar earlier, but I did a horrible job of asking the right question. I'm trying to code a two player connect four game, but can only manage a 1 player game, with the user playing against the computer. Can anyone help me with trying to write a 2 player approach to the game? I'm still quite a beginner and am still learning the ropes, so apologies if this is still not a good question and/or is too vague. Here's my current code: import random def winner(board): # Check rows for row in range(6): for col in range(3): if (board[row][col] == board[row][col + 1] == board[row][col + 2] == board[row][col + 3]) and (board[row][col] != " "): return board[row][col] # Check columns for col in range(6): for row in range(3): if (board[row][col] == board[row + 1][col] == board[row + 2][col] == board[row + 3][col]) and (board[row][col] != " "): return board[row][col] # Check diagonal A for row in range(3): for col in range(4): if (board[row][col] == board[row + 1][col + 1] == board[row + 2][col + 2] == board[row + 3][col + 3]) and (board[row][col] != " "): return board[row][col] # Check diagonal B for row in range(5, 2, -1): for col in range(3): if (board[row][col] == board[row - 1][col + 1] == board[row - 2][col + 2] == board[row - 3][col + 3]) and (board[row][col] != " "): return board[row][col] # Tie (just returns an empty string) return "" def printBoard(board): # there are probably better ways to print a board, but I didn"t want to bother with another function, especially since the number of columns and rows are fixed in this game. print (" 1 2 3 4 5 6 7") print ("1: " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " | " + board[0][3] + " | " + board[0][4] + " | " + board[0][5] + " | " + board[0][6] + " | " + board[0][7]) print (" ---+---+---+---+---+---+---") print ("2: " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " | " + board[1][3] + " | " + board[1][4] + " | " + board[1][5] + " | " + board [1][6] + " | " + board [1][7]) print (" ---+---+---+---+---+---+---+") print ("3: " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " | " + board[2][3] + " | " + board [2][4] + " | " + board [2][5] + " | " + board [2][6] + " | " + board [2][7]) print (" ---+---+---+---+---+---+---+") print ("4: " + board[3][0] + " | " + board[3][1] + " | " + board[3][2] + " | " + board[3][3] + " | " + board [3][4] + " | " + board [3][5] + " | " + board [3][6] + " | " + board [3][7]) print (" ---+---+---+---+---+---+---+") print ("5: " + board[4][0] + " | " + board[4][1] + " | " + board[4][2] + " | " + board[4][3] + " | " + board [4][4] + " | " + board [4][5] + " | " + board [4][6] + " | " + board [4][7]) print (" ---+---+---+---+---+---+---+") print ("6: " + board[5][0] + " | " + board[5][1] + " | " + board[5][2] + " | " + board[5][3] + " | " + board [5][4] + " | " + board [5][5] + " | " + board [5][6] + " | " + board [5][7]) print def playerMove(board): validMove = False while not validMove: col = input("What column would you like to play? :") for row in range (6,0,-1): if (1 <= int(row) <= 6) and (1 <= int(col) <= 7) and (board[int(row)-1][int(col)-1] == " "): board[int(row)-1][int(col)-1] = "X" validMove = True break else: print ("Invalid input. Please try again!\n") def computerTurn(board): validMove = False while not validMove: row = random.randint(0,5) col = random.randint(0,6) for row in range (5,0,-1): if board[row][col] == " ": board[row][col] = "O" validMove = True break def game(): openCells = 42 playerTurn = True count = 1 newBoard = [ [ " ", " ", " ", " ", " ", " "," ", " "], [ " ", " ", " ", " ", " "," ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "] ] while not winner(newBoard) and (openCells > 0): printBoard(newBoard) if playerTurn: playerMove(newBoard) playerTurn = not playerTurn else: computerTurn(newBoard) playerTurn = not playerTurn openCells -= 1 printBoard(newBoard) if (winner(newBoard) == "X"): print ("You Won!") print ("\nGAME OVER") elif (winner(newBoard) == "O"): print ("The Computer Won!") print ("\nGAME OVER") else: print ("Tie!") print ("\nGAME OVER \n") EDIT:I modified my code so that I got rid of the computerTurn function and incorporated 2 user inputs in my playerMove function, however my game keeps looping back to player name inputs instead of alternating between turns. Here's the new code (note that only the last couple functions were changed): def playerMove(board): turn = 0 players = [] numPlayers = 2 checkers = ['X','O'] for i in range(numPlayers): players.append(input("Please enter player"+str(i+1)+" name: ")) validMove = False while not validMove: col = input(players[turn]+" what column would you like to play? :") for row in range (6,0,-1): if (1 <= int(row) <= 6) and (1 <= int(col) <= 7) and (board[int(row)-1][int(col)-1] == " "): board[int(row)-1][int(col)-1] = "X" validMove = True break else: print ("Invalid input. Please try again!\n") def game(): openCells = 42 playerTurn = True turn = 0 players = [] numPlayers = 2 count = 1 newBoard = [ [ " ", " ", " ", " ", " ", " "," ", " "], [ " ", " ", " ", " ", " "," ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "] ] while not winner(newBoard) and (openCells > 0): printBoard(newBoard) playerMove(newBoard) playerTurn = not playerTurn openCells -= 1 printBoard(newBoard) if (winner(newBoard) == "X"): print ("You Won!") print ("GAME OVER") elif (winner(newBoard) == "O"): print ("The Computer Won!") print ("GAME OVER") else: print ("Tie!") print ("GAME OVER") game()
I found a simpler way: I made a new function, playerMoveO, and renamed your old one playerMoveX. I made playerMoveO look like this: def playerMoveO(board): validMove = False while not validMove: col = input("You are the O player. What column would you like to play? :") for row in range (6,0,-1): if (1 <= int(row) <= 6) and (1 <= int(col) <= 7) and (board[int(row)-1][int(col)-1] == " "): board[int(row)-1][int(col)-1] = "O" validMove = True break else: print ("Invalid input. Please try again!\n") I also changed playerMoveX to look like this: def playerMoveX(board): validMove = False while not validMove: col = input("You are the X player. What column would you like to play? :") for row in range (6,0,-1): if (1 <= int(row) <= 6) and (1 <= int(col) <= 7) and (board[int(row)-1][int(col)-1] == " "): board[int(row)-1][int(col)-1] = "X" validMove = True break else: print ("Invalid input. Please try again!\n") Then, I changed the main loop, but I replaced the computerTurn function with playerMoveO. It works fine :D EDIT Obviously, there is a cleaner way. In this one, the playerMove function is passed the current symbol. So: def playerMove(board, symbol): validMove = False while not validMove: col = input("You are the {} player. What column would you like to play? :".format(symbol)) for row in range (6,0,-1): if (1 <= int(row) <= 6) and (1 <= int(col) <= 7) and (board[int(row)-1][int(col)-1] == " "): board[int(row)-1][int(col)-1] = symbol validMove = True break else: print ("Invalid input. Please try again!\n") And in the main loop, there is a variable, currentSymbol, which is changed after each turn: def game(): openCells = 42 playerTurn = True count = 1 newBoard = [ [ " ", " ", " ", " ", " ", " "," ", " "], [ " ", " ", " ", " ", " "," ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "] ] currentSymbol = "X" while not winner(newBoard) and (openCells > 0): printBoard(newBoard) playerMove(newBoard, currentSymbol) if currentSymbol == "X": currentSymbol = "O" elif currentSymbol == "O": currentSymbol = "X" openCells -= 1 printBoard(newBoard) if (winner(newBoard) == "X"): print ("X Won!") print ("\nGAME OVER") elif (winner(newBoard) == "O"): print ("O Won!") print ("\nGAME OVER") else: print ("Tie!") print ("\nGAME OVER \n")