'How to stop a while loop from executing continuously?

Sorry if I phrased the question poorly, I am creating a basic game which generates a random number and asks the user to try guessing the number correctly and helps the user in the process.


import random

#print("*************  THE PERFECT GUESS  *****************")

a = random.randint(1,5)

num = int(input("enter a number : "))

while (num<a):
    print("try guessing higher \U0001F615")
    num = int(input("enter a number : "))
    

while (num>a):
    print("try guessing lower  \U0001F615")
    num = int(input("enter a number : "))
    
if (num == a):
    print("yay! You guessed it right,congrats \U0001F60E!")

Here , once I execute the program, it gets stuck in the while loop and the compiler asks me to keep guessing forever. Why is the code stuck in the while loop? Its an entry controlled loop so i thought it would break out of the loop as soon as the condition was false.



Solution 1:[1]

Why is the code stuck in the while loop?

Because computers do what tell them to do, not what you want them to do.

Num = new_guess()
While num!=a:
  If a<num:
    Too_high()
  Else:
    Too_low()
  Num = new_guess()

Sorry for the capitals

Solution 2:[2]

For you if you wanted to break put of a loop: Easiest way:

break

The harder, force stop way:

import sys
sys.exit()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gnight
Solution 2 Dharman