You need to enable JavaScript to run this app. Python中while循环使用'or'逻辑判断失效问题排查
优惠活动
大模型
产品
解决方案
定价
更多

Python中while循环使用'or'逻辑判断失效问题排查

Fixing the While Loop Logic in Your Python Calculator

Hey there, let's break down why your while loop is stuck asking for input no matter what valid option you pick!

The Root Problem

Your current loop condition uses or to check for invalid input, but that's logically backwards:

while (procedure != '1') or (procedure != '2') or (procedure != '3') or (procedure != '4'):

Think about it—if you enter '1', then procedure != '2' is still True, so the entire or expression evaluates to True... and the loop keeps running. This happens for any valid input, because at least three of those "not equal" checks will always be true.

The Fixes

You have two clean ways to fix this:

1. Swap or for and

With and, the loop only runs if all the "not equal" conditions are true (meaning the input isn't any of the valid options):

while (procedure != '1') and (procedure != '2') and (procedure != '3') and (procedure != '4'):
    procedure = input('Please choose the correct option')

2. Use not in for cleaner readability

A more Pythonic approach is to check if the input isn't in a list of valid choices—this is easier to read and maintain if you ever add more options later:

valid_options = ['1', '2', '3', '4']
while procedure not in valid_options:
    procedure = input('Please choose the correct option')

Full Corrected Code

Here's your complete calculator with the fix, plus adding the missing call to process() (since defining a function doesn't run it automatically):

print('Welcome to Calculator')
a = int(input('Enter your first value: '))
b = int(input('Enter your second value: '))
print('''Addition - type 1
Subtraction - type 2
Multiplication - type 3
Division - type 4''')
procedure = input('Enter an option: ')

# Fixed loop condition using `not in`
valid_options = ['1', '2', '3', '4']
while procedure not in valid_options:
    procedure = input('Please choose the correct option: ')

def process():
    if procedure == '1':
        print(a + b)
    elif procedure == '2':
        print(a - b)
    elif procedure == '3':
        print(a * b)
    elif procedure == '4':
        print(a / b)

# Don't forget to call the function!
process()

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:25:05