Informatics Practices · Ch 3 — Brief Overview of Python
Operators
Operators
Every program ultimately does two things: it stores values, and it does something with them. The "doing something" part is the job of operators. An operator is a symbol that tells Python to carry out a specific mathematical or logical operation on one or more values. The values an operator acts upon are called its operands.
Consider the expression:
10 + num
Here the constant 10 and the variable num are the two operands, while the + (plus) sign is the operator that instructs Python to add them. The operator by itself does nothing — it needs operands to work on, and together they form a meaningful expression.
Categories of operators in Python
Python provides several kinds of operators, grouped by the type of work they perform. Each category is examined in detail in the sub-sections that follow:
- Arithmetic operators — perform numeric calculations such as addition, subtraction, multiplication, division, and related operations.
- Relational operators — compare two values and report the relationship between them (equal, greater, smaller, and so on).
- Assignment operators — store a value in a variable, or update the value a variable already holds.
- Logical operators — combine or reverse conditions that are either True or False.
- Membership operators — check whether a value is present inside a given sequence.
How Python compares strings
Operators do not work only on numbers — several of them also work on strings. When Python compares two strings, it does so in dictionary order, using the ASCII values of the characters. The comparison proceeds character by character:
- Python first compares the first character of both strings.
- If the first characters of both strings are the same, it moves on and compares the second characters, and so on, until it finds a position where the strings differ or one of them ends.
This is exactly how words are ordered in a dictionary, which is why this style of comparison is called dictionary order. Because the comparison rests on ASCII values, the outcome of comparing letters follows their positions in the ASCII table rather than any human judgement about the words themselves. …