By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,972 Members | 1,092 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,972 IT Pros & Developers. It's quick & easy.

Infinite loop?

P: 3
I am a beginner to Python and am just trying to make a simple 'Guess the number' game. I programmed it to tell you weather the number you guessed is higher or lower than the actual number. However, the 'Higher' and 'Lower' appear on the screen a couple of hundred times instead of just one.

Expand|Select|Wrap|Line Numbers
  1.  
  2. import random
  3.  
  4. print('Welcome to Guess the Number')
  5. print('Try to guess the number in as few tries as possible')
  6.  
  7. the_number= random.randint(1, 100)
  8.  
  9. guess=int(input("Take a guess!  "))
  10. tries=1
  11.  
  12.  
  13. while guess != the_number:
  14.           if guess>the_number:
  15.               print('Lower... ')
  16.  
  17.  
  18. else:
  19.           print('Higher... ')
  20.  
  21.  
  22. guess= int(input('Take a guess!  '))
  23. tries+=1
  24.  
  25. print('Well done! The number was', the_number)
  26. print('and it only took u=you', tries, 'tries!')
  27.  
  28. input('n/nPress the enter key to exit')
  29.  
Attached Images
File Type: jpg pythpn.jpg (10.2 KB, 65 views)
Sep 23 '15 #1
Share this Question
Share on Google+
1 Reply


Expert 100+
P: 614
Your indentation says that the only thing that happens under the while loop is the if statement. Everything from the "else" on happens after the while loop exits, including the input, so "guess" never changes=an infinite loop. And what happens when they don't guess it in the number of tries, or enter anything other than a number.
Expand|Select|Wrap|Line Numbers
  1. import random
  2.  
  3. print('Welcome to Guess the Number between 1 and 100')
  4. print('Try to guess the number in as few tries as possible')
  5.  
  6. the_number= random.randint(1, 100)
  7.  
  8. max_tries=10 
  9. tries=0
  10. guess = -1
  11.  
  12. ## start while 
  13. while guess != the_number and tries < max_tries:
  14.     guess= int(input('Take a guess!  '))
  15.     tries+=1
  16.     if guess == the_number:
  17.         print('Correct')
  18.     elif guess > the_number:
  19.         print('Number Is Lower... ')
  20.     else:
  21.         print('Number Is Higher... ')
  22. ## end of while loop
  23.  
  24. print('Well done! The number was', the_number)
  25. print('and it only took u=you', tries, 'tries!')
  26.  
  27. input('\n\nPress the enter key to exit')  ## enter to exit is always funny 
Sep 23 '15 #2

Post your reply

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