输入action_type为1时触发Exception: action out of range异常的咨询
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 !=1evaluates toFalse- But
action_type !=2evaluates toTrue
Since you're usingor, the entire condition returnsTrue(because only one side needs to be true fororto 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

