[Tutor] Having Troubles with For Loops
I am refreshing my memory of Python programming after taking a class this past fall. I am using the book, *Python Programming for the absolute beginner*. I am at chapter 4, challenge 4 which instructs me to create a program that picks a random word and the player has to guess the word. The computer tells the player how mnay letters are in the word. Then the player gets five chances to ask if a letter is in the word. The computer can only respond with "yes" or "no." Then, the player must guess the word. Here is what I have so far. I think I am doing something wrong with the for loops as the program is not reading whether the letter is in the constant and giving the appropriate response. #Word Randomizer #This program picks the word and the user has to figure out what the computer #picked. The computer tells how many letters are in the word. The player #gets five chances to guess the correct word. import random # create a sequence of words to choose from PYTHON = "python" JUMBLES = "jumbles" EASY = "easy" DIFFICULT = "difficult" XYLOPHONES = "xylophones" WORDS = (PYTHON, JUMBLES, EASY, DIFFICULT, XYLOPHONES) # pick one word randomly from the sequence word = random.choice(WORDS) # create a variable to use later to see if the guess is correct correct = word #intial values tries = 1 max_tries = 5 #start the game print( """ Welcome to Word Randomizer! Guess the word the computer picks. (Press the enter key at the prompt to quit.) """ ) #The computer picks the word and gives a hint if correct == PYTHON: print ("This word has six letters.") elif correct == JUMBLES: print ("This word has seven letters.") elif correct == EASY: print ("This word has four letters.") elif correct == DIFFICULT: print ("This word has nine letters.") elif correct == XYLOPHONES: print ("This word has ten letters.") else: raw_input("Press Enter to Exit the Program.") guess_letter = raw_input("Guess a letter: ") #The player gets five chances to see if a letter is in the word. for letter in PYTHON: if letter.lower() not in PYTHON: print ("No") guess_letter = raw_input("Guess a letter: ") else: print ("Yes") guess_letter = raw_input("Guess a letter :") tries +=1 if tries == max_tries: guess_word = raw_input("Guess the word: ") for letter in JUMBLES: if letter.lower() not in JUMBLES: print ("No") guess_letter = raw_input("Guess a letter: ") else: print ("Yes") guess_letter = raw_input("Guess a letter :") tries +=1 if tries == max_tries: guess_word = raw_input("Guess the word: ") for letter in EASY: if letter.lower() not in EASY: print ("No") guess_letter = raw_input("Guess a letter: ") else: print ("Yes") guess_letter = raw_input("Guess a letter :") tries +=1 if tries == max_tries: guess_word = raw_input("Guess the word: ") for letter in DIFFICULT: if letter.lower() not in DIFFICULT: print ("No") guess_letter = raw_input("Guess a letter: ") else: print ("Yes") guess_letter = raw_input("Guess a letter :") tries +=1 if tries == max_tries: guess_word = raw_input("Guess the word: ") for letter in XYLOPHONES: if letter.lower() not in XYLOPHONES: print ("No") guess_letter = raw_input("Guess a letter: ") else: print ("Yes") guess_letter = raw_input("Guess a letter :") tries +=1 if tries == max_tries: guess_word = raw_input("Guess the word: ") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Having Troubles with For Loops
On 02/19/2011 01:06 PM, jyatesster wrote: > I am refreshing my memory of Python programming after taking a class this > past fall. I am using the book, *Python Programming for the absolute > beginner*. I am at chapter 4, challenge 4 which instructs me to create a > program that picks a random word and the player has to guess the word. The > computer tells the player how mnay letters are in the word. Then the player > gets five chances to ask if a letter is in the word. The computer can only > respond with "yes" or "no." Then, the player must guess the word. > > Here is what I have so far. I think I am doing something wrong with the for > loops as the program is not reading whether the letter is in the constant > and giving the appropriate response. > [snip] You're going about it wrong. You should look into the len() function. For example: print("This word has %d letters" % (len(word)) ) for i in range(5): letter = input("Guess a letter: ") if letter.lower() in word.lower(): print("Yes") else: print("No") Your for loops in the end don't do what you think they do. for letter in XYLOPHONES: # Loops through XYLOPHONES if letter.lower() not in XYLOPHONES: # Always will return false, print("No")# because you are looping through the word itself # etc. You are also mixing Python 3's print() with Python 2's raw_input(), so it's hard to tell which you are using. I'm assuming Python 2 because you didn't report the raw_input() failing. If that's the case, you don't need the ()'s around the text you are printing. I also suggest you look into lists and list indexing. You should go through the Python Tutorial [0] if you haven't before. [0] - http://docs.python.org/tutorial/ -- Corey Richardson I've never known any trouble which an hour's reading didn't assuage. -Charles De Secondat ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Having Troubles with For Loops
"jyatesster" wrote Here is what I have so far. I think I am doing something wrong with the for loops as the program is not reading whether the letter is in the constant and giving the appropriate response. Instead of having us guess it would be useful if you told us (or better cut n paste) what actually happened and why you thought it was wrong. Besides helping us understand putting it in words will often help you to understand to the point of seeing the solution... #Word Randomizer import random # create a sequence of words to choose from PYTHON = "python" JUMBLES = "jumbles" EASY = "easy" DIFFICULT = "difficult" XYLOPHONES = "xylophones" WORDS = (PYTHON, JUMBLES, EASY, DIFFICULT, XYLOPHONES) Its easier to ,miss out the constants and just do words = ('python', 'jumbles',) word = random.choice(WORDS) # create a variable to use later to see if the guess is correct correct = word You shouldn't need correct since you aren't changing word, so just use word directly. #intial values tries = 1 max_tries = 5 You don't really need these either, see below... #The computer picks the word and gives a hint The comment is misleading since the computer picked the word further up. Move the random function to here... if correct == PYTHON: print ("This word has six letters.") elif correct == JUMBLES: print ("This word has seven letters.") You can use len(word) to get the letters without all the repetition. print "This word has", len(word), "letters" guess_letter = raw_input("Guess a letter: ") #The player gets five chances to see if a letter is in the word. for letter in PYTHON: if letter.lower() not in PYTHON: You need to use guess_letter not letter. letter will be each of the letters in 'python'... But you don't really want to test the guesses against python (unless python is the word). Better to just use word, and you don't need a loop over the letters you need a loop that repeats up 5 times: for try in range(5): print ("No") guess_letter = raw_input("Guess a letter: ") and then use 'in' to find out if the guess_letter is in the word guess_word = raw_input("Guess the word: ") And you never check to see if the guessed word is the word!. So the user never actually wins or loses... You are heading in the right general direction but you are making it much more complex than it needs to be. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Having Troubles with For Loops
To start with, you don't need to do so much for loop. You have already set the chosen word, word to correct. Every randomly selected word becomes the value of correct so, you need to only check for word in correct. So, after initiating the random selector, you print the number of letters in the word using the syntax like this: The player has 5 tries, depending on the approach you intend to adopt, you may not have to use max_tries. Say you go for the while loop. Set tries to 1 correct=word[random.randrange(len(word)-1)] word = a list of words you want the player to choose from print 'The word has %d letters' % len(correct) while tries <= 5: guess=raw_input('Guess a letter: ') if guess in correct: print 'yes' else: print 'no' tries += 1 What you would achieve with the above is that, immediately the player does 5 guesses, the game exits. How do you expect a player to guess a 7 letter word with just 5 tries. Second, the player should after 5 tries, if you insist on that, have a chance to guess the word itself assuming he has he has made two or three guesses, atleast give him a chance to make a wild guess. You can then tell him if he is right or wrong and go ahead to tell him the word. This is just a game logic from my own perspective. Do the necessary tweak to the cold. If there are other problems, please let's know. I hope this helps. Regards. Sent from my BlackBerry wireless device from MTN -Original Message- From: Corey Richardson Sender: tutor-bounces+delegbede=dudupay@python.org Date: Sat, 19 Feb 2011 13:22:25 To: Subject: Re: [Tutor] Having Troubles with For Loops On 02/19/2011 01:06 PM, jyatesster wrote: > I am refreshing my memory of Python programming after taking a class this > past fall. I am using the book, *Python Programming for the absolute > beginner*. I am at chapter 4, challenge 4 which instructs me to create a > program that picks a random word and the player has to guess the word. The > computer tells the player how mnay letters are in the word. Then the player > gets five chances to ask if a letter is in the word. The computer can only > respond with "yes" or "no." Then, the player must guess the word. > > Here is what I have so far. I think I am doing something wrong with the for > loops as the program is not reading whether the letter is in the constant > and giving the appropriate response. > [snip] You're going about it wrong. You should look into the len() function. For example: print("This word has %d letters" % (len(word)) ) for i in range(5): letter = input("Guess a letter: ") if letter.lower() in word.lower(): print("Yes") else: print("No") Your for loops in the end don't do what you think they do. for letter in XYLOPHONES: # Loops through XYLOPHONES if letter.lower() not in XYLOPHONES: # Always will return false, print("No")# because you are looping through the word itself # etc. You are also mixing Python 3's print() with Python 2's raw_input(), so it's hard to tell which you are using. I'm assuming Python 2 because you didn't report the raw_input() failing. If that's the case, you don't need the ()'s around the text you are printing. I also suggest you look into lists and list indexing. You should go through the Python Tutorial [0] if you haven't before. [0] - http://docs.python.org/tutorial/ -- Corey Richardson I've never known any trouble which an hour's reading didn't assuage. -Charles De Secondat ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Tic-Tac-Toe
Hey, I *think* that everything is working except my function gameWon. I keep getting the following error: " line 67, in gameWon if (cell % 3 == 0) and (self.__mycells[cell] == self.__mycells[cell + 1]) and (self.__mycells[cell + 1]== self.__mycells[cell + 2]): TypeError: unsupported operand type(s) for %: 'instance' and 'int' >>> " My thinking was the following: I wanted to check the verticals, horizontals, and diagonals to see if they were the same. If so, then the game is won. I'm not sure why I'm not actually comparing the value inside the appropriate cells, but clearly the error means that what I'm trying to do is not what is actually happening. My full code is below and I would greatly appreciate any help you can provide. Thanks, Ben _- #Ben Ganzfried #2/18/11 #Tic-Tac-Toe class Player: def __init__(self, name, type): self.__name = name self.__type = type def move(self): cell_index = input("%s's (%s) move: " & (self.__name, self.__type)) cell_index = int(cell_index) while cell_index > 8 and cell_index < 0: print("Please retry...") cell_index = input("%s's (%s) move: " & (self.__name, self.__type)) return cell_index def getName(self): return self.__name def getType(self): return self.__type class Board: def __init__(self): self.__mycells = [] for i in range(0, 9): current_cell = Cell() self.__mycells.append(current_cell) def print1(self): counter = 0 for cell in self.__mycells: cell.print1() counter +=1 if counter % 3 == 0: print("\n") def setCellToX(self, cell_number): cell = self.__mycells[cell_number] if not cell.isOccupied(): cell.setToX() return True else: return False def setCelltoO(self, cell_number): cell = self.__mycells[cell_number] if not cell.isOccupied(): cell.setToO() return True else: return False def isTied(self): for cell in self.__mycells: if not cell.isOccupied(): return False return True def gameWon(self): for cell in self.__mycells: #horizontals if (cell % 3 == 0) and (self.__mycells[cell] == self.__mycells[cell + 1]) and (self.__mycells[cell + 1]== self.__mycells[cell + 2]): return True #verticals elif (cell < 3) and (self._mycells[cell] == self._mycells[cell + 3]) and (self._mycells[cell] == self.__mycells[cell + 6]): return True #diagonals elif (cell == 0) and (self.__mycells[cell] == self.__mycells[cell + 4]) and (self.__mycells[cell] == self.__mycells[cell + 8]): return True elif (cell == 2) and (self.__mycells[cell] == self.__mycells[cell + 2]) and (self.__mycells[cell] == self.mycells[cell + 4]): return True return False class Cell: def __init__(self): self.__value = " " def setToX(self): self.__value = "X" def setToO(self): self.__value = "O" def print1(self): print(self.__value,) #add a predicate (start in terms of question, not action) def isOccupied(self): return not self.__value == " " def main(): #initialize game #draw board #create two players #enter a loop-- prompt each player for a loop...stops when a player wins or a tie board = Board() board.print1() pX = Player("Ben", "X") pO = Player("Sam", "O") while not board.gameWon() and not board.isTied(): c1 = pX.move() success = board.setCellToX(c1) while not success: c1 = pX.move() success = board.setCellToX(c1) board.print1() c1 = pO.move() success = board.setCellToO(c1) while not success: c1 = pO.move() success = board.setCellToO(c1) board.print1() print("Game Over") if __name__ == "__main__": main() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tic-Tac-Toe
On 2/19/2011 3:49 PM, Ben Ganzfried wrote: Hey, I *think* that everything is working except my function gameWon. I keep getting the following error: " line 67, in gameWon if (cell % 3 == 0) and (self.__mycells[cell] == self.__mycells[cell + 1]) and (self.__mycells[cell + 1]== self.__mycells[cell + 2]): TypeError: unsupported operand type(s) for %: 'instance' and 'int' Learn to fish? unsupported operand type(s) for %: 'instance' and 'int' What is that telling you? Take a moment to read each word / symbol and relate it to the statement. PAUSE while you actually do that. If you figure it out hooray. The message is very explicit. If you are stuck then scroll down. Is there a % operator in the statement? Yes. The message tells you that its operand are of type instance and int. instance is the left operand type, int is the right operand type. Which of those types is not valid for %? PAUSE while you actually do that. If you figure it out hooray. The message is very explicit. If you are still stuck then scroll down. the expression being complained about is cell % 0 0 is an int, and that is OK for %. cell is an instance. Do you know why? instances are not valid for %. All of your references to cell in that statement and the ones following expect integers, not instances. You want to, as you say below, examine the cell value. My thinking was the following: I wanted to check the verticals, horizontals, and diagonals to see if they were the same. If so, then the game is won. I'm not sure why I'm not actually comparing the value inside the appropriate cells, but clearly the error means that what I'm trying to do is not what is actually happening. My full code is below and I would greatly appreciate any help you can provide. Thanks, Ben _- #Ben Ganzfried #2/18/11 #Tic-Tac-Toe class Player: def __init__(self, name, type): self.__name = name self.__type = type def move(self): cell_index = input("%s's (%s) move: " & (self.__name, self.__type)) cell_index = int(cell_index) while cell_index > 8 and cell_index < 0: print("Please retry...") cell_index = input("%s's (%s) move: " & (self.__name, self.__type)) return cell_index def getName(self): return self.__name def getType(self): return self.__type class Board: def __init__(self): self.__mycells = [] for i in range(0, 9): current_cell = Cell() self.__mycells.append(current_cell) def print1(self): counter = 0 for cell in self.__mycells: cell.print1() counter +=1 if counter % 3 == 0: print("\n") def setCellToX(self, cell_number): cell = self.__mycells[cell_number] if not cell.isOccupied(): cell.setToX() return True else: return False def setCelltoO(self, cell_number): cell = self.__mycells[cell_number] if not cell.isOccupied(): cell.setToO() return True else: return False def isTied(self): for cell in self.__mycells: if not cell.isOccupied(): return False return True def gameWon(self): for cell in self.__mycells: #horizontals if (cell % 3 == 0) and (self.__mycells[cell] == self.__mycells[cell + 1]) and (self.__mycells[cell + 1]== self.__mycells[cell + 2]): return True #verticals elif (cell < 3) and (self._mycells[cell] == self._mycells[cell + 3]) and (self._mycells[cell] == self.__mycells[cell + 6]): return True #diagonals elif (cell == 0) and (self.__mycells[cell] == self.__mycells[cell + 4]) and (self.__mycells[cell] == self.__mycells[cell + 8]): return True elif (cell == 2) and (self.__mycells[cell] == self.__mycells[cell + 2]) and (self.__mycells[cell] == self.mycells[cell + 4]): return True return False class Cell: def __init__(self): self.__value = " " def setToX(self): self.__value = "X" def setToO(self): self.__value = "O" def print1(self): print(self.__value,) #add a predicate (start in terms of question, not action) def isOccupied(self): return not self.__value == " " def main(): #initialize game #draw board #create two players #enter a loop-- prompt each player for a loop...stops when a player wins or a tie board = Board() board.print1() pX = Player("Ben", "X") pO = Player("Sam", "O") while not board.gameWon() and not board.isTied(): c1 = pX.move() success = board.setCellToX(c1) while not success: c1 = pX.move() success = boa
Re: [Tutor] Tic-Tac-Toe
"Ben Ganzfried" wrote if (cell % 3 == 0) and (self.__mycells[cell] == self.__mycells[cell + 1]) and (self.__mycells[cell + 1]== self.__mycells[cell + 2]): TypeError: unsupported operand type(s) for %: 'instance' and 'int' The error is in the first expression and the message tells you what is wrong. You are trying to use the % operator on an instance. Looking at your code, sure enough... def gameWon(self): for cell in self.__mycells: if (cell % 3 == 0) and (self.__mycells[cell] == cell is one of __mycells which are objects. You need to rethink this test. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tic-Tac-Toe
I got stimulated to create a minimal tic-tac-toe program. No functions, no classes. board = [" "]*9 player = 'X' prompt = "Player %s cell #, Q=quit, B=display board>" while True: cell = raw_input(prompt % player) if cell in 'qQ': break elif cell in 'bB': print ('+---+' + '\n|%s%s%s|'*3 + '\n+---+') % tuple(board) elif not(len(cell) == 1 and cell.isdigit() and '1' <= cell <= '9'): print "Cell must be a number between 1 and 9." elif board[int(cell)-1] != " ": print "Cell is occupied." else: board[int(cell)-1] = player if any(1 for a,b,c in ((0,3,1), (3,6,1), (6,9,1), (0,7,3), (1,8,3), (2,9,3), (0,9,4), (2,7,2)) if board[a:b:c] == [player]*3): print player, "wins" break player = 'O' if player == 'X' else 'X' -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] dict['_find']
Hello all, first post, please be gentle. I'm having serious trouble finding an alternative for the deprecated find module for dictionaries. The code (from Zed Shaw's Hard Way, exercise 40) goes something like this. Hope indentation survives. cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} def find_city(themap, state): if state in themap: return themap[state] else: return "Not found." cities['_find'] = find_city while True: print "State? (ENTER to quit)", state = raw_input("> ") if not state: break city_found = cities['_find'](cities, state) print city_found My question is - how do I rewrite this using an alternate module given find is deprecated? Grateful for all suggestions or pointers. For reference, I'm using 2.6.1 on darwin. Thanks so much for your help. Best, Max -- Dr. Maximilian Niederhofer Founder, Qwerly http://qwerly.com/ | http://qwerly.com/max +44 78 3783 8227 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dict['_find']
Max Niederhofer wrote: Hello all, first post, please be gentle. I'm having serious trouble finding an alternative for the deprecated find module for dictionaries. What find module for dictionaries? The code (from Zed Shaw's Hard Way, exercise 40) goes something like this. Hope indentation survives. cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} def find_city(themap, state): if state in themap: return themap[state] else: return "Not found." cities['_find'] = find_city What is the purpose of this? You have a dictionary called "cities" that contains four items. The first three are pairs of State:City, which makes sense. The fourth is a pair of the word "_find" matched with a function find_city. I don't understand what the purpose of this is. while True: print "State? (ENTER to quit)", state = raw_input("> ") if not state: break city_found = cities['_find'](cities, state) print city_found I think you need to include the actual search inside the while loop. Otherwise, the loop keeps asking for a new state, but doesn't do anything with it until you exit the loop. while True: print "State? (ENTER to quit)", state = raw_input("> ") if not state: break city_found = cities['_find'](cities, state) print city_found But I don't understand the purpose of placing the function inside the dictionary. Much clearer and simpler is: while True: print "State? (ENTER to quit)", state = raw_input("> ") if not state: break print find_city(cities, state) -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor