Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to end a while loop when one variable is greater than the other?

I want my while loop to end when the num value is less than the random number.
I have no idea what I’m doing wrong.

num = int(input("Please choose a number (1-10): "))
import random
random = random.randint(1,5)
while (num > random):
    print(num, random)

I want it to print (num, random) until the num is less than the random.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

the body of the while loop is defined indented below the while keyword.
So you most likely want to change one of the two numbers in the while body.

so either

while num > random:
    number=int(input("Please choose a number (1-10): "))

or

while num > random_num:
    random_num=random.randint(1,5)

Note that you are overwriting the random package by naming a variable random, which is something you almost never want.

You also should try to import only at the top of a file:
Should import statements always be at the top of a module?

edit: full code:

import random
random_num=random.randint(1,5)
number=int(input("Please choose a number (1-10): "))
while number > random_num
    print(number ,random_num)
    number=int(input("Please choose a number (1-10): "))
# now the number is <= random_num
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading