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.
Reblochon Masque
37k10 gold badges60 silver badges85 bronze badges
3 Answers 3
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"))
answered Jul 2, 2013 at 17:58
Rohit Jain
214k45 gold badges420 silver badges535 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
user2533561
so the tries and userNumber are still in the loop itself? Also i have to ask for the userNumber twice in order for this too work? I actually wrote a similar program in java but i dont remember how i did it.
Rohit Jain
Yes, they both should be inside the loop only. And if you just want the give user two chance, then add the
tries in the while loop condition.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")
answered Jul 2, 2013 at 17:59
2rs2ts
11.2k12 gold badges56 silver badges100 bronze badges
Comments
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.")
Comments
lang-py
IndentationError. :)tries, but you apparently forgot to do anything with it - like preventing more than 5 tries or at least printing back how many guesses it took the user.