Search code examples
pythonconditional-statementsvalueerror

Is it possible to use comparison operators on an error?


I am doing something similar to this to output if a variable contains a substing.

print("Variable contains foo" * variable.index("foo") !=None)

But when I run the program, I just get this error.

ValueError: substring not found

Of course, I am expecting variable to not contain "foo" sometimes, so is there any way to do something like this without using try and except?


Solution

  • As @IainShelvington already said you can use 'foo' in variable which will never raise an Exception, or not in for opposite condition:

    Try it online!

    variable = 'a foo'
    print("Variable contains foo" * ('foo' in variable))
    variable2 = 'a bar'
    print("Variable2 has no foo" * ('foo' not in variable2))
    

    Output:

    Variable contains foo
    Variable2 has no foo