Ad

How To End A While Loop When One Variable Is Greater Than The Other?

- 1 answer

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.

Ad

Answer

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
Ad
source: stackoverflow.com
Ad