473,803 Members | 3,913 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Solving Python guessing number game

3 New Member
I'm able to create a guessing number game, but I can limit the amount of guesses to less than 3. Can someone tell me what i'm doing wrong?

Expand|Select|Wrap|Line Numbers
  1. # Guess My Number
  2. # The computer picks a random number
  3.  
  4. import random
  5. print "\tWelcome to 'Guess my number'!:"
  6. print "\nI'm thinking of a number between 1 and 100."
  7. print "Try to guess it in as few attempts as possible.\n"
  8.  
  9. #set the initial values
  10. the_number = random.randrange(100) + 1
  11. guess = int(raw_input("Take a guess: "))
  12. tries = 1
  13.  
  14. # guessing loop
  15.  
  16. while (guess != the_number):
  17.     if (guess > the_number):
  18.         print "Lower..."
  19.     else:
  20.         print "Higher..."
  21.  
  22.     guess = int(raw_input("Take a guess: "))
  23. if tries > 3:
  24.     print "You have more than 3 attempts, game over."
  25.     tries += 1
  26.  
  27. else:
  28.     print "You guessed it! The number was", the_number
  29.     print "And it only took you", tries, "tries!\n"
  30.  
  31.  
  32.  
  33. raw_input ("\n\nPress the enter key to exit.")
Nov 17 '08 #1
7 16806
Laharl
849 Recognized Expert Contributor
Please wrap your code in CODE tags so that the indentation doesn't get stripped out.

It looks like you only update tries when it's greater than three. Your idea would work, but you also can't have

Expand|Select|Wrap|Line Numbers
  1. if: 
  2.     code
  3. code
  4. else:
  5.     code
  6.  
because Python won't know to associate the else with the if (can't tell since the parser here rips indentation out). Put the tries update someplace else to fix that.
Nov 17 '08 #2
bvdet
2,851 Recognized Expert Moderator Specialist
I'm able to create a guessing number game, but I can limit the amount of guesses to less than 3. Can someone tell me what i'm doing wrong?
Expand|Select|Wrap|Line Numbers
  1. # Guess My Number
  2. # The computer picks a random number
  3.  
  4.  
  5.  
  6. import random
  7. print "\tWelcome to 'Guess my number'!:"
  8. print "\nI'm thinking of a number between 1 and 100."
  9. print "Try to guess it in as few attempts as possible.\n"
  10.  
  11. #set the initial values
  12. the_number = random.randrange(100) + 1
  13. guess = int(raw_input("Take a guess: "))
  14. tries = 1
  15.  
  16. # guessing loop
  17.  
  18. while (guess != the_number):
  19.     if (guess > the_number):
  20.         print "Lower..."
  21.     else:
  22.         print "Higher..."
  23.  
  24.     guess = int(raw_input("Take a guess: "))
  25. if tries > 3:
  26.     print "You have more than 3 attempts, game over."
  27.     tries += 1
  28.  
  29. else:
  30.     print "You guessed it! The number was", the_number
  31.     print "And it only took you", tries, "tries!\n"
  32.  
  33.  
  34.  
  35. raw_input ("\n\nPress the enter key to exit.")
I made a few changes to your code. The statement to get guess is now inside the loop. Variable tries is incremented after the guess. The if statement that checks for high or low was modified: if >, elif<, else(must be correct guess). If tries == max_guesses, the game is over. Encapsulate the code in a function. Use return to exit the while loop.
Expand|Select|Wrap|Line Numbers
  1. import random
  2. print "\tWelcome to 'Guess my number'!:"
  3. print "\nI'm thinking of a number between 1 and 100."
  4. print "Try to guess it in as few attempts as possible.\n"
  5.  
  6. def guess_num(num, max_guesses):
  7.     # guessing loop
  8.     tries = 0
  9.     while True:
  10.         guess = int(raw_input("Take a guess: "))
  11.         tries += 1
  12.         if guess > num:
  13.             print "Lower..."
  14.         elif guess < num:
  15.             print "Higher..."
  16.         else:
  17.             print "You guessed it! The number was", num
  18.             print "And it only took you %d tr%s!\n" % (tries, ['ies', 'y'][tries==1 or 0])
  19.             return
  20.  
  21.         if tries == max_guesses:
  22.             print "You have had %d guesses. Game over." % max_guesses
  23.             return
  24.  
  25. the_number = random.randrange(1,101)
  26. max_guesses = 3
  27. guess_num(the_number, max_guesses)
  28.  
  29. raw_input ("\n\nPress the enter key to exit.")
Nov 17 '08 #3
dseto200
3 New Member
Thanks bvdet. The book "Python Programming second edition hasn't shown the "def" command yet.
The original exercise - Modify this program so the player has a limited number of guesses. The chp covers import random, randomrange, while loop, while true, if, if-else loop and if elif loop. Is there a way I can do with the def command?
Nov 17 '08 #4
dseto200
3 New Member
The original exercise modify this program to limit the amount of guesses.
Chapter covers if, if-else, if-elif, if-elif-else, while, while True, import random, randrange(), raw_input and comparison operators. How can I do it without using the def command.
Original exercise that I have to modify listed below.

Expand|Select|Wrap|Line Numbers
  1. # Guess My Number
  2.  
  3. # The computer picks a random number
  4. #  The player tries to guess it and the computer lets
  5. #  The player know if the guess is too high, too low
  6. #  or right on the money
  7.  
  8. import random
  9.  
  10. print "\tWelcome to 'Guess my number'!:"
  11. print "\nI'm thinking of a number between 1 and 100."
  12. print "Try to guess it in as few attempts as possible.\n"
  13.  
  14. #set the initial values
  15. # the_number = random.randrange(100) + 1
  16. # guess = int(raw_input("Take a guess: "))
  17. # tries = 1
  18. #  
  19. # # guessing loop
  20.  
  21. while (guess != the_number):
  22.    if (guess > the_number):
  23.    print "Lower..."
  24.    else:
  25.    print "Higher..."
  26.  
  27. guess = int(raw_input("Take a guess: "))
  28.  
  29. tries += 1
  30.  
  31. print "You guessed it! The number was", the_number
  32. print "And it only took you", tries, "tries!\n"
  33.  
  34.  raw_input ("\n\nPress the enter key to exit.")
Nov 17 '08 #5
bvdet
2,851 Recognized Expert Moderator Specialist
Could you clarify what your problem or question is?
Nov 17 '08 #6
boxfish
469 Recognized Expert Contributor
Could you clarify what your problem or question is?
dseto's programming course hasn't covered functions yet.
The original exercise modify this program to limit the amount of guesses.
Just modify the condition in the while-loop so that the loop also stops when the number of tries is too high. You'll need the and operator.
Nov 18 '08 #7
Bodsda
1 New Member
Hi, I've taken a look at your code and your on the right track. Remember loops are an extremely important part of any program especially one like this. Below is a working guess the number game that requires you to input the number of max tries when you call the function.

Expand|Select|Wrap|Line Numbers
  1. #! /usr/bin/env python
  2.  
  3. # Guess the number game
  4.  
  5. import random
  6.  
  7. def main(max):
  8.     print "\tWelcome to 'Guess my number'!"
  9.     print "\nI'm thinking of a number between 1 and 100."
  10.     print "Try to guess in as few attempts as possible.\n"
  11.     num = random.randrange(101)
  12.     tries = 0
  13.     guess = ""
  14.     while guess != num:
  15.         guess = int(raw_input("Take a guess: "))
  16.         if guess > num:
  17.             print "Too high."
  18.         elif guess < num:
  19.             print "Too low."
  20.         tries += 1
  21.         if tries >= max:
  22.             print "Sorry, you took too many guesses. Game Over"
  23.             exit()
  24.     print "Congratulations!"
  25.     again = raw_input("To play again press Enter. Type anything else to quit.")
  26.     if again == "":
  27.         main()
  28.     else:
  29.         exit()
  30.  
  31. main(3)
  32.  
The business part of this code is lines 14-23. thats the important while loop that keeps the game going. As you can see it will keep iterating while the variable 'guess' does not equal variable 'num' (while guess != num:)

This code doesnt have any try-except statements or any error checking for user input or anything like that but it is working. If you need any additional explanation please post again. Thanks

Bodsda
Nov 21 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

0
996
by: Irmen de Jong | last post by:
Hello, some trivia for whom it may concern: I've just downloaded and played the demo of Cyan's new game "URU Ages of Myst". Wonderful-game-but-crappy-controls yadda yadda, but that's not the subject here. I noticed that they're using Python in the game, probably to script the game engine :-) (There is a Python folder in the game install directory
4
2719
by: Moosebumps | last post by:
When I have time, I am planning to evaluate Python for console game development (on Playstation 2, GameCube, and Xbox). Does anyone have any experience with this? Pretty much the only resource I have found, and the only thing that makes me think it might be possible is this: http://asbahr.com/python.html I would be interested to hear anybody's experience with Python on consoles.
8
12030
by: EAS | last post by:
Hey, I'm new to python (and programming in general) so I'll prolly be around here a lot... Anyways, I've found out how to make a "guess my number game" where the player guesses a number between 1 and 100, but I want to switch things around. I want to be able to put in my own number and have the computer guess it. I already know how to make it guess (by using randrange) but I'm having a hard time making it smarter. (Like guessing higher...
2
1690
by: chyf1983929 | last post by:
Is there any modules about mobile game in python? which l can use it to write mobile game . thank you
13
1674
by: Yannick | last post by:
Hi, I would like to program a small game in Python, kind of like robocode (http://robocode.sourceforge.net/). Problem is that I would have to share the CPU between all the robots, and thus allocate a time period to each robot. However I couldn't find any way to start a thread (robot), and interrupt it after a given time period. Any suggestions on how to proceed? Is Python just not adapted to this kind of things?
1
2108
by: blinkrebel | last post by:
Hello I need some help implementing the game of blackjack using the xturtle package. the instructions can be found at http://katie.luther.edu/moodle/file.php/2387/BlackJack.pdf and .gif's for the cards can be found at http://katie.luther.edu/moodle/file.php/2387/cards.zip
3
1788
by: Dew | last post by:
Hello, iam new to programming, and ive been given a task in my Uni to complete certain exercises but i found it very difficulty to solve them. I was wandering if there is someone who can help me solve this problems. I cant tell u how much i will be gratefull if someone can help me. Please if anyone knows how to solve certain task reply to me.Thanks to all in advance. Tasks 1. Your are going to a restaurant where the tip is expected to be...
21
5442
by: cromoglic | last post by:
Hello! I have been making a "guess what number the computer thinks of"-game in python (text-only) for educational reasons. Now, i want to implement a highscore in the code, which writes the best three players with names and number of attempts. First, I'll just show you my game, but nevermind the code in that one: #Importere modulen random: import random #thenumber tilsvarer nå random.randint(0, 100) som er et tilfeldig tall mellom 0 og...
0
10316
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10295
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10069
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9125
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6842
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5500
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5629
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4275
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3798
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.