虽然循环打印响应不应该 - Python

时间:2017-06-19 18:36:11

标签: python if-statement while-loop indentation

我的程序包含一个简单的Y / N'输入。我在代码中放置了一个while循环,当输入的输入不是“Y / N”时,它应该响应。或其任何变化。

import time
count_d = 10

load = input('Import modules? Y/N')

if load == 'Y' or load == 'y' or load == ' Y' or load == ' y':
    print('Modules loading...')
    while count_d >0:
        print(count_d)
        count_d = count_d-1
        time.sleep(1)
    print('Modules loaded')
elif load == 'N' or load == 'n' or load == ' N' or load == ' n':
    print('Shutdown initiated.')
    sys.exit()

while load != 'Y' or load != 'y' or load != ' Y' or load != ' y' and load != 'N' or load != 'n' or load != ' N' or load != ' n':
    print('This answer does not correspond with the desired output')
    load = input('Import modules? Y/N')
    if load == 'Y' or load == 'y' or load == ' Y' or load == ' y':
        print('Modules loading...')
        while count_d >0:
           print(count_d)
           count_d = count_d-1
           time.sleep(1)
        print('Modules loaded')
        break
    elif load == 'N' or load == 'n' or load == ' N' or load == ' n':
        print('Shutdown initiated.')
        break

当我输入一个接受的输入时,程序会响应它所需的位置,但也会打印while循环的响应,它只能用一个未接受的输入来识别它。我做了什么错误,所以当我正确地完成它时会释放错误的输出?

3 个答案:

答案 0 :(得分:1)

您可以简化检查,以便不必处理如此繁琐的条件:

if load.strip().lower() == 'y':

elif load.strip().lower() == 'n':

while load.strip().lower() not in ['y', 'n']:

巧合的是,最后一个会修复您的错误,因为您使用or代替and

答案 1 :(得分:0)

执行ifelif块下面的语句,无论它们是否满足条件。
为确保仅在ifelif中的条件不满足时才执行这些语句,必须使用else

while块中包含else循环:

import time
count_d = 10

load = input('Import modules? Y/N')

if load == 'Y' or load == 'y' or load == ' Y' or load == ' y':
    print('Modules loading...')
    while count_d >0:
        print(count_d)
        count_d = count_d-1
        time.sleep(1)
    print('Modules loaded')
elif load == 'N' or load == 'n' or load == ' N' or load == ' n':
    print('Shutdown initiated.')
    sys.exit()
else:
    while load != 'Y' or load != 'y' or load != ' Y' or load != ' y' and load != 'N' or load != 'n' or load != ' N' or load != ' n':
        print('This answer does not correspond with the desired output')
        load = input('Import modules? Y/N')
        if load == 'Y' or load == 'y' or load == ' Y' or load == ' y':
            print('Modules loading...')
            while count_d >0:
               print(count_d)
               count_d = count_d-1
               time.sleep(1)
            print('Modules loaded')
            break
        elif load == 'N' or load == 'n' or load == ' N' or load == ' n':
            print('Shutdown initiated.')
            break

答案 2 :(得分:-1)

您需要将while循环中的'或'语句更改为'和'语句。

这个例子应该告诉你原因......

while(!a或!b): //在a为真但b为假的情况下运行

while(!a和!b): //在a和b都不正确时运行