为什么我的Python代码会跳过while循环?

时间:2016-08-18 14:00:55

标签: python while-loop

我为1到100范围内的用户输入构建猜测程序。

为什么它跳过第二个while循环,我检查用户输入并转发它。它直接与数字1

import random

nums_lasted = []
a = 0
while a < 101:
    nums_lasted.append(a)
    a += 1
secret_num = 1
while secret_num < 0 or secret_num > 100:
    try:
        secret_num = int(input("My number is"))
    except ValueError:
        print("No way that was an integer!")
guess_pc = 50
min = 50
max = 101
while True:
    print("Is it", guess_pc,"?")
    if guess_pc == secret_num:
        print("Easy")
        break
    elif guess_pc > secret_num:
        max = guess_pc
        nums_lasted.append(guess_pc)
        nums_lasted1 = [i for i in nums_lasted if i < guess_pc]
        nums_lasted = nums_lasted1
    elif guess_pc < secret_num:
        min = guess_pc
        nums_lasted.append(guess_pc)
        nums_lasted1 = [i for i in nums_lasted if i < guess_pc]
        nums_lasted = nums_lasted1
    guess_pc = random.choice(nums_lasted)

2 个答案:

答案 0 :(得分:3)

secret_num = 1
while secret_num < 0 or secret_num > 100:

您将secret_num设置为1while仅在secret_num小于0或大于100时运行,因此永远不会执行。{/ p>

答案 1 :(得分:1)

因为secret_num < 0 or secret_num > 100的条件secret_num == 1为false。 1绝对介于0和100之间。您应该将secret_number设置为大于100的值,以使其按预期工作。