user2533561
user2533561

Reputation: 85

A simple python loop issue

This code:

import random
print("\tWelcome to the guess my number program\n")

print("im thinking of a number between 1 and 100")
print("try to guess it in 5 attempts\n")

randomNum = random.randint(1,101)

tries = 0

userNumber = int(input("please pick a number"))

while userNumber != randomNum:
    if userNumber > randomNum:
        print ("lower") 
    else:
        print("higher") 
    tries += 1

print ("you guessed it! the number was" , randomNum)

For some reason this produces an infinite loop. Any help, im still getting used to python.

Upvotes: 3

Views: 133

Answers (3)

crackalamoo
crackalamoo

Reputation: 13

Try This:

import random
print("Welcome to the guess my number program!")
randomnum = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100.")
print("Try to guess it in 5 attempts.")
tries = 0
usernumber = 0
while not usernumber == randomnum:
   usernumber = int(raw_input("please pick a number.")
   if usernumber > randomnum:
      print("Too High")
   if usernumber < randomnum:
      print("Too Low")
   tries = tries + 1
if usernumber == randomnum:
   print("You got the number!")
print("It took you " + str(tries) + " attempts.")

Upvotes: 0

2rs2ts
2rs2ts

Reputation: 11066

You've forgotten to ask the user to guess again. Try this!

while userNumber != randomNum:
    if userNumber > randomNum:
        print("lower")
    else:
        print("higher")
    tries += 1
    userNumber = int(input("please pick a number")

Upvotes: 3

Rohit Jain
Rohit Jain

Reputation: 213371

You never updated your userNumber or randomNum inside the while loop. So once the loop condition is met, it will execute infinitely.

You need to update your while loop as:

while userNumber != randomNum:
    if userNumber > randomNum:
        print ("lower") 
    else:
        print("higher") 

    tries += 1    
    userNumber = int(input("please pick a number"))

Upvotes: 5

Related Questions