4 Replies - 612 Views - Last Post: 20 January 2013 - 11:52 AM Rate Topic: -----

#1 taymo  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 14-January 13

Guessing game getting while loop keeps repeating.

Posted 14 January 2013 - 08:31 AM

import random
number = random.randint(1,20)
guess=raw_input ("Guess the number I'm thinking of between 1 and 20")
while True:
if guess > number:
print "No, the answer is less than ",guess
elif guess < number:
print "No, the answer is greater than ",guess
elif guess == number:
print "Yes, you guessed correctly! The answer is ",number


This is my current code but when i run it the while loop constantly repeats itself and i cant get out of it. Any tips?

Is This A Good Question/Topic? 0
  • +

Replies To: Guessing game getting while loop keeps repeating.

#2 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5316
  • View blog
  • Posts: 11,371
  • Joined: 02-June 10

Re: Guessing game getting while loop keeps repeating.

Posted 14 January 2013 - 10:27 AM

while True:

Hello? True will always be true. When would it ever stop?
Was This Post Helpful? 1
  • +
  • -

#3 darek9576  Icon User is online

  • D.I.C Lover

Reputation: 198
  • View blog
  • Posts: 1,672
  • Joined: 13-March 10

Re: Guessing game getting while loop keeps repeating.

Posted 14 January 2013 - 12:36 PM

Look into break statements. If you type into google High-Low game in Python, you will get many results.
Was This Post Helpful? 0
  • +
  • -

#4 Tayacan  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 145
  • View blog
  • Posts: 275
  • Joined: 18-January 11

Re: Guessing game getting while loop keeps repeating.

Posted 19 January 2013 - 07:20 AM

What darek9576 said - or I'll just tell you, cause it's not a long explanation. break breaks out of loops. There, that's it. So you just put "break" in your code, wherever you want to exit the loop. Like this:

import random

while True:
    print("I'm stuck in a loop!")
    if random.randrange(0,10) == 4:
        break

print("Yay, I got out of the loop")


Was This Post Helpful? 1
  • +
  • -

#5 alexr1090  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 38
  • View blog
  • Posts: 108
  • Joined: 08-May 11

Re: Guessing game getting while loop keeps repeating.

Posted 20 January 2013 - 11:52 AM

or just change the while loop to
 
while guess != number:
  ...
  ...
print "Yes, you guessed correctly! The answer is ",number #this will get entered after guess == number, so I took it out of the while loop

This post has been edited by alexr1090: 20 January 2013 - 11:52 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1