当一个变量大于另一个变量时如何结束 while 循环?

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

我希望我的 while 循环在 num 值小于随机数时结束。 我不知道我做错了什么。

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

我希望它打印 (num, random) 直到 num 小于 random。

while 循环的主体在 while 关键字下方缩进定义。 因此,您很可能想更改 while 正文中的两个数字之一。

所以要么

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

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

请注意,您通过命名一个变量 random 来覆盖 random 包,这是您几乎不想要的。

您还应该尝试仅在文件顶部导入: Should import statements always be at the top of a module?

编辑:完整代码:

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