0

I am trying to create a guessing game for myself. I want to have the computer have a random number which I have to guess. Based on what I guess, it would then respond with "higher or lower" and this should keep happening before i get the right number however what has happened is that now when I put in a guess, it says higher or lower and just repeats this throughout the page. How do I end this loop and make sure that after each "higher" or "lower" i just get another change. Please find code below.

import random the_number = random.randrange(100)+ 1 guess= int(raw_input("Take a guess: ")) tries = 1 while (guess != the_number): if (guess > the_number): print "Lower..." break elif (guess<the_number): print " Higher..." break elif (guess == the_number): print "Awesome achievement" break else: print "Better luck next time." guess = int(raw_input("Take another guess ")) 
3
  • This has been asked and answered on numerous occasion. Commented Oct 29, 2013 at 20:47
  • @GamesBrainiac, include URL. Commented Oct 29, 2013 at 20:48
  • Got it: stackoverflow.com/questions/14011149/… Commented Oct 29, 2013 at 20:49

2 Answers 2

2
import random the_number = random.randrange(100) + 1 tries = 0 while True: tries += 1 guess = int(raw_input("Take a guess: ")) if guess > the_number: print "Lower..." elif guess < the_number: print " Higher..." else: print "Awesome achievement, it took you", tries, "tries" break 
Sign up to request clarification or add additional context in comments.

2 Comments

So what exactly was I doing wrong then? I would like to really understand the theory behind what I was doing wrong? Thank you.
You need to put the guess = int(raw_input(.. inside the loop, and don't break until you're done.
0

something like this

import random def main(): secret = random.randint(1, 10) while (guess != secret): guess = int(raw_input("Guess a number between 1 and 10: ")) if guess > secret: print "too high." elif guess < secret: print "too low." elif guess <1 or guess > 10: print "invalid guess." elif guess == secret: print "You win" break 

1 Comment

Yea I wrote it in sublime and copied it over but it didn't take the formatting over :S. everything after define main should be indented

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.