Infinite loop?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • am5243
    New Member
    • Sep 2015
    • 3

    Infinite loop?

    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.

    Code:
    import random
    
    print('Welcome to Guess the Number')
    print('Try to guess the number in as few tries as possible')
    
    the_number= random.randint(1, 100)
    
    guess=int(input("Take a guess!  "))
    tries=1
    
    
    while guess != the_number:
              if guess>the_number:
                  print('Lower... ')
    
    
    else:
              print('Higher... ')
    
    
    guess= int(input('Take a guess!  '))
    tries+=1
    
    print('Well done! The number was', the_number)
    print('and it only took u=you', tries, 'tries!')
    
    input('n/nPress the enter key to exit')
    Attached Files
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    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.
    Code:
    import random
     
    print('Welcome to Guess the Number between 1 and 100')
    print('Try to guess the number in as few tries as possible')
     
    the_number= random.randint(1, 100)
     
    max_tries=10 
    tries=0
    guess = -1
     
    ## start while 
    while guess != the_number and tries < max_tries:
        guess= int(input('Take a guess!  '))
        tries+=1
        if guess == the_number:
            print('Correct')
        elif guess > the_number:
            print('Number Is Lower... ')
        else:
            print('Number Is Higher... ')
    ## end of while loop
     
    print('Well done! The number was', the_number)
    print('and it only took u=you', tries, 'tries!')
     
    input('\n\nPress the enter key to exit')  ## enter to exit is always funny

    Comment

    Working...