3 Replies - 10560 Views - Last Post: 13 December 2012 - 10:15 AM Rate Topic: -----

#1 Thuy Vi  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 15-October 10

Python Guessing Game

Posted 15 October 2010 - 03:04 PM

Okay, so I have started Python for some weeks now and I have a assignment on creating a guessing game. I finished my guessing game luckily, but now I want to refine it.

For example, if the user enters an interger out of the range of (1, 100) it will print a friendly message and ask the user to re-enter a new number. So far, the code I made for this will ignore the restrictions I placed in and just tell the user if the guess is too high or low.

Also, when a user enters a string, the game will tell the user the answer is invalid and tell the user to re-enter a new number. I got my code to work for this until I enter in another string character:


Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    main()
  File "C:\Users\Mary Anne\Desktop\Cmpt 120\Assignments\a3.py.py", line 51, in main
    guess = int(raw_input("Please re-enter your guess: "))
ValueError: invalid literal for int() with base 10: 'as'



This is my code so far...


import random


def main():
    name = raw_input("Hi! What's your name? ") #Tells the user to enters his/her name.
    if name == name: 
        print 'Nice to meet you ' + name + '!' #Prints a personalized message with instructions.
        print "Let's play a game.\n"
        print "I am thinking of a number from 1 to 100."
        print "You try to guess the number. If you guess right, you win!"
        print "If you guess wrong, I will tell you if your guess is too low or too high.\n"
        print "Got it?"
        print "Good! Let's play!"


    play = 'y' 
    while play == 'y': #When user chooses y, the game is restarted in while loop.
        secret_number = (random.randint(1, 100)) #Secret number is randomly chosen through 1 - 100.
        guess_count = 0 #Guess count starts from 0.

        
        try:        
            guess = int(raw_input("\nWhat is your first guess? ")) #User enters his/her first guess. 
            while guess != secret_number: #A while loop is created if the user does not get the secret number right.
                print "That's not it " + name + "." #Prints out a personalized message.
                if guess < secret_number:
                    guess_count += 1 #Adds one to the guess count.
                    print " Your guess is too LOW." #Prints this message out if the guess is lower than the secret number.
                    guess = int(raw_input("\nWhat is your next guess? ")) #Tells the user to enter in the next guess.
                if guess > secret_number:
                    guess_count += 1 #Adds one to the guess count.
                    print " Your guess is too HIGH." #Prints this message out if the guess is higher than the secret number.
                    guess = int(raw_input("\nWhat is your next guess? ")) #Tells the user to enter in the next guess.
                if guess < 1 or guess > 100:
                    print "\nOops: that's not a valid guess."
                    guess = int(raw_input("Please re-enter your guess: "))
        except ValueError:
               print "\nOops: that's not a valid guess."
               guess = int(raw_input("Please re-enter your guess: "))

            
        if guess == secret_number:
             if guess_count == 0: #If user got the secret number on the first try, this special message is produced.
                guess_count += 1 #Adds one to the guess count.
                print "Amazing: You got in on your first try!"
                print "It took you " + str(guess_count) + " guess(es)" #Tells the user how many guesses he/she made.
             if 1 < guess_count < 10: #If the user guesses the secret number under 10 guesses, this special message is produced.
                guess_count += 1 #Adds one to the guess count.
                print "Nice work!"
                print "It took you " + str(guess_count) + " guess(es)" #Tells the user how many guesses he/she made.
             if guess_count > 10: #If the user guesses the secret number over 10 tries, no special message is produced.
                guess_count += 1 #Adds one to the guess count.
                print "It took you " + str(guess_count) + " guess(es)" #Tells the user how many guesses he/she made

                    
        play = str(raw_input("\n\nWanna play again(y/n)? ")) # When user picks y, the game starts over.
                                                             # When user picks n, the game ends.





Any help would be great, thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: Python Guessing Game

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4309
  • View blog
  • Posts: 12,088
  • Joined: 18-April 07

Re: Python Guessing Game

Posted 15 October 2010 - 03:58 PM

First of all you can remove the name == name if statement, that is doing nothing for you really. Now the actual problem here is that you use a try catch that puts you in an error situation where if you enter another invalid string, you have no way to catch the ValueError again. What you need to do is put the input into a loop where you can go back to the top and re-evaluate the string again. They enter a guess, invalid, jumps to the ValueError catch, prints the message, goes to the top of the loop and reprompts... then continues through the steps again as many times as needed until they enter a valid value.

Hope you get what I am saying. :)
Was This Post Helpful? 0
  • +
  • -

#3 Thuy Vi  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 15-October 10

Re: Python Guessing Game

Posted 18 October 2010 - 09:04 AM

I got the message working when a user enters an interger out of the range (1, 100) now. I guess I don't need that minor code in my function. :) I'll see what I can do to make an input into a loop now. Thanks for the help!
Was This Post Helpful? 0
  • +
  • -

#4 Micleah  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 13-December 12

Re: Python Guessing Game

Posted 13 December 2012 - 10:15 AM

Here's one I made on my iPod using Pythonista. It is heavily modified from Abhinay Omkar's version.

#Author: Abhinay Omkar and Micleah

import random
import console
console.clear()


class GuessNumber:
    def startGame(self):
  	a = random.randint(1,100)
	print '=' * 40
	print 'Guess a number between 1 and 100.'
	print 'You have 7  guesses.'
	t=0
	for t in xrange(7):
		num = raw_input("Guess "+str(t+1)+": ")
		try:
			inp = int(num)
		except ValueError:
			inp=0
		
		if(inp == a):
			print "\nCorrect! You guessed the number in "+str(t+1)+" guesses! Well done!"
			return self.quitGame()
		if(100 > inp > a):
			print "It's less"
		if(100 <= inp):
			print "Guess a number between 1 and 100!"
		if(0 >= inp):
			print "Guess a number between 1 and 100!"
		if(0 < inp < a):
			print "It's greater"
	print '\nYou reached maximum number of guesses.'
	print 'The number was', a
	return self.quitGame()

    def quitGame(self):
	if(str(raw_input("\nTry Again? (y/n): ")).lower() in ('y','')):
		return True
	else:
		print "Thanks for playing!"
		return False

if __name__ == '__main__':
	G = GuessNumber()
	GameIsInteresting = True
	while GameIsInteresting:
		GameIsInteresting = G.startGame()


Damn!! It removed all indentation! Sorry

This post has been edited by baavgai: 13 December 2012 - 11:24 AM
Reason for edit:: tagged

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1