Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple python loop issue

Tags:

python

loops

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.

like image 747
user2533561 Avatar asked Jun 07 '26 11:06

user2533561


2 Answers

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"))
like image 91
Rohit Jain Avatar answered Jun 10 '26 12:06

Rohit Jain


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")
like image 33
2rs2ts Avatar answered Jun 10 '26 12:06

2rs2ts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!