bhylu.com

Advertisements

Python Operators

Operators combine or compare values. Read them as part of an expression with a specific type and meaning, rather than assuming a familiar symbol behaves identically on every object.

Understand the idea

The + operator adds numbers but concatenates strings and lists. Comparison operators produce logical results, and membership asks whether a container includes a value. Parentheses help explain a mixed expression. Custom classes can define some operator behaviour, which is covered later through special methods.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

print(4 + 3)
print("4" + "3")
print(3 in [1, 3, 5])

Read the result

The outputs are 7, 43, and True. The two plus expressions use different operations because their operands have different types.

Try one change

Compare adding two lists with adding two numbers, then describe the result type of each expression.