You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

输入action_type为1时触发Exception: action out of range异常的咨询

Why Your Code Throws "action out of range" When action_type is 1

Hey there, let's get to the bottom of this weird issue you're seeing. The problem boils down to a logical operator mistake in your condition check.

The Root Cause

Look at this line in your code:

if(action_type!=1 or action_type!=2):

Let's walk through what happens when action_type is 1:

  • action_type !=1 evaluates to False
  • But action_type !=2 evaluates to True
    Since you're using or, the entire condition returns True (because only one side needs to be true for or to trigger). That means the code jumps into this if block and raises the "action out of range" exception—even though 1 is supposed to be a valid value!

The same issue would happen if action_type was 2: action_type !=1 would be True, so the condition still passes. This check will always be true, no matter what integer you input.

The Fix

You need to check if the action type is neither 1 nor 2. To do that, replace or with and:

if action_type != 1 and action_type != 2:

Or for better readability, use the in operator:

if action_type not in (1, 2):

Corrected Full Code

Here's your code with the fix applied:

def main():
    action_type = input("enter action type")
    input_string = input("enter input string")
    try:
        action_type = int(action_type)
    except:
        raise ValueError("invalid action type")
    if action_type not in (1, 2):
        raise Exception("action out of range")
    elif action_type == 1:
        print(input_string)

Now when you enter 1, the condition action_type not in (1,2) is False, so it skips the exception and runs the elif block as expected.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:13:06