pythonsoftware-design

Is "abc" + 5 considered an expression in python?


Since a expression in python is defined as "a combination of values, variables, and operators that evaluates to a single value".

If we take something like "abc" + 5. though it is a combination of values, variable and operators it doesn't evaluate to a single value ,it would give an error since you cannot add a string with a integer.

So would it be considered an expression why or why not?


Solution

  • Yes, it is absolutely an expression. Others have linked to the official language reference, but if that doesn't suit you, you can ask the CPython parser itself, the an authority on what constitutes a Python expression:

    >>> import ast
    >>> print(ast.dump(ast.parse('"abc" + 5'), indent=2))
    Module(
      body=[
        Expr(
          value=BinOp(
            left=Constant(value='abc'),
            op=Add(),
            right=Constant(value=5)))],
      type_ignores=[])
    

    It is an expression that will always result in an exception being raised. But that is netiher here nor there.

    Consider the following function:

    import random
    
    def foo():
        if random.random() >= 0.5:
            raise RuntimeError("Nah ah ah!")
    

    Well, then, I hope we can all agree that:

    foo()
    

    Is an expression. Even though sometimes it will raise an error. Otherwise, would have to say "we don't know if that is an expression or not until it is called."

    No. It is an expression. An expression that can raise a runtime error. Like many other expressions.

    Here is a good operational definition for an expression in Python. An expression in Python is anything that can go on the right-hand side of a simple assignment statement:

    x = <some expression>