Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions python-operators-expressions/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Operators and Expressions in Python

This folder provides the code examples for the Real Python tutorial [Operators and Expressions in Python](https://realpython.com/python-operators-expressions/).

## Running the Examples

The tutorial presents its examples in the interactive REPL. Here, each section
of the tutorial has its own self-contained script that runs the same code in
the same order and prints the results. The examples only use the standard
library, so there's nothing to install. Run any of them with Python 3.14 or
later:

```sh
$ python arithmetic.py
```

| File | Tutorial section |
| ------------------------------ | --------------------------------------------------- |
| `getting_started.py` | Getting Started With Operators and Expressions |
| `assignment.py` | The Assignment Operator and Statements |
| `arithmetic.py` | Arithmetic Operators and Expressions in Python |
| `comparison.py` | Comparison Operators and Expressions in Python |
| `comparison_integers.py` | Comparison of Integer Values |
| `comparison_floats.py` | Comparison of Floating-Point Values |
| `comparison_strings.py` | Comparison of Strings |
| `comparison_sequences.py` | Comparison of Lists and Tuples |
| `boolean_operands.py` | Boolean Expressions Involving Boolean Operands |
| `boolean_context.py` | Evaluation of Regular Objects in a Boolean Context |
| `boolean_other_operands.py` | Boolean Expressions Involving Other Types of Operands |
| `short_circuit.py` | Compound Logical Expressions and Short-Circuit Evaluation |
| `short_circuit_idioms.py` | Idioms That Exploit Short-Circuit Evaluation |
| `chained_comparisons.py` | Compound vs Chained Expressions |
| `conditional_expressions.py` | Conditional Expressions or the Ternary Operator |
| `identity.py` | Identity Operators and Expressions in Python |
| `membership.py` | Membership Operators and Expressions in Python |
| `concatenation_repetition.py` | Concatenation and Repetition Operators and Expressions |
| `walrus.py` | The Walrus Operator and Assignment Expressions |
| `bitwise.py` | Bitwise Operators and Expressions in Python |
| `precedence.py` | Operator Precedence in Python |
| `augmented_assignment.py` | Augmented Assignment Operators and Expressions |

A few of the tutorial's snippets can't live in a script: the bare `-`, `==`,
and `or` operators are a `SyntaxError`, and several snippets are syntax
sketches with placeholder names. Those are noted in comments where they
belong. Where the tutorial shows a traceback, the script catches the
exception and prints its message so that you can still see the error.
26 changes: 26 additions & 0 deletions python-operators-expressions/arithmetic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
a = 5
b = 2

print(+a)
print(-b)
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)
print(a // b)
print(a**b)

# The division operator always returns a floating-point number
print(10 / 5)
print(10.0 / 5)

# With complex numbers, division returns a complex number
print(10 / 5j)

# Floor division always rounds down
print(10 // 4)
print(-10 // -4)

print(10 // -4)
print(-10 // 4)
9 changes: 9 additions & 0 deletions python-operators-expressions/assignment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
number = 42
day = "Friday"
digits = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
letters = ["a", "b", "c"]

print(number)
print(day)
print(digits)
print(letters)
14 changes: 14 additions & 0 deletions python-operators-expressions/augmented_assignment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
total = 10
total = total + 5
print(total)

# Accumulating into an undefined variable raises a NameError
try:
count = count + 1
except NameError as error:
print(error)

# The augmented addition operator does the same job
total = 10
total += 5
print(total)
15 changes: 15 additions & 0 deletions python-operators-expressions/bitwise.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Bitwise AND
# 0b1100 12
# & 0b1010 10
# --------
# = 0b1000 8
print(bin(0b1100 & 0b1010))
print(12 & 10)

# Bitwise OR
# 0b1100 12
# | 0b1010 10
# --------
# = 0b1110 14
print(bin(0b1100 | 0b1010))
print(12 | 10)
21 changes: 21 additions & 0 deletions python-operators-expressions/boolean_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Numeric values: zero is falsy, everything else is truthy
print(bool(0), bool(0.0), bool(0.0 + 0j))
print(bool(-3), bool(3.14159), bool(1.0 + 1j))

# Strings: the empty string is falsy
print(bool(""))
print(bool(" "))
print(bool("Hello"))

# Containers: empty containers are falsy
print(bool([]))
print(bool([1, 2, 3]))

print(bool(()))
print(bool(("John", 25, "Python Dev")))

print(bool(set()))
print(bool({"square", "circle", "triangle"}))

print(bool({}))
print(bool({"name": "John", "age": 25, "job": "Python Dev"}))
34 changes: 34 additions & 0 deletions python-operators-expressions/boolean_operands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
age = 20

is_adult = age > 18
print(is_adult)

print(type(is_adult))

number = 42

validation_conditions = (
isinstance(number, int),
number % 2 == 0,
)

print(all(validation_conditions))

print(callable(number))
print(callable(print))

# The and operator with Boolean operands
print(5 < 7 and 3 == 3)
print(5 < 7 and 3 != 3)
print(5 > 7 and 3 == 3)
print(5 > 7 and 3 != 3)

# The or operator with Boolean operands
print(5 < 7 or 3 == 3)
print(5 < 7 or 3 != 3)
print(5 > 7 or 3 == 3)
print(5 > 7 or 3 != 3)

# The not operator with a Boolean operand
print(5 < 7)
print(not 5 < 7)
16 changes: 16 additions & 0 deletions python-operators-expressions/boolean_other_operands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# The and operator returns one of its operands
print(3 and 4)
print(0 and 4)
print(3 and 0)

# The or operator also returns one of its operands
print(3 or 4)
print(0 or 4)
print(3 or 0)

# When both operands are falsy, or returns the right-hand one
print(0 or [])

# The not operator always returns a Boolean value
print(not 3)
print(not 0)
10 changes: 10 additions & 0 deletions python-operators-expressions/chained_comparisons.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# A compound expression joined with the and operator
number = 5
print(number >= 0 and number <= 10)

number = 42
print(number >= 0 and number <= 10)

# The equivalent chained comparison
number = 5
print(0 <= number <= 10)
8 changes: 8 additions & 0 deletions python-operators-expressions/comparison.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Comparing objects of different types for equality
print(2 == "2")

# Non-equality comparisons between different types raise a TypeError
try:
print(5 < "7")
except TypeError as error:
print(error)
9 changes: 9 additions & 0 deletions python-operators-expressions/comparison_floats.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from math import isclose

x = 1.1 + 2.2

print(x == 3.3)
print(1.1 + 2.2)

# Compare floating-point values for approximate equality instead
print(isclose(x, 3.3))
19 changes: 19 additions & 0 deletions python-operators-expressions/comparison_integers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
a = 10
b = 20

print(a == b)
print(a != b)
print(a < b)
print(a <= b)
print(a > b)
print(a >= b)

x = 30
y = 30

print(x == y)
print(x != y)
print(x < y)
print(x <= y)
print(x > y)
print(x >= y)
33 changes: 33 additions & 0 deletions python-operators-expressions/comparison_sequences.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
print([2, 3] == [2, 3])
print((2, 3) == (2, 3))

print([5, 6, 7] < [7, 5, 6])
print((5, 6, 7) < (7, 5, 6))

print([4, 3, 2] < [4, 3, 2])
print((4, 3, 2) < (4, 3, 2))

# You can compare lists to tuples for equality...
print([2, 3] == (2, 3))
print([2, 3] != (2, 3))

# ...but the order comparisons raise a TypeError
try:
print([2, 3] > (2, 3))
except TypeError as error:
print(error)

try:
print([2, 3] <= (2, 3))
except TypeError as error:
print(error)

# Sequences of different lengths
print([5, 6, 7] < [8])
print((5, 6, 7) < (8,))

print([5, 6, 7] == [5])
print((5, 6, 7) == (5,))

print([5, 6, 7] > [5])
print((5, 6, 7) > (5,))
15 changes: 15 additions & 0 deletions python-operators-expressions/comparison_strings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
print(ord("A"))
print(ord("a"))

print("A" == "a")
print("A" > "a")
print("A" < "a")

# Lexicographical ordering, character by character
print("Hello" > "HellO")

print(ord("o"))
print(ord("O"))

# Strings of different lengths
print("Hello" > "Hello, World!")
11 changes: 11 additions & 0 deletions python-operators-expressions/concatenation_repetition.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# The concatenation operator
print("Hello, " + "World!")
print(("A", "B", "C") + ("D", "E", "F"))
print([0, 1, 2, 3] + [4, 5, 6])

# The repetition operator
print("Hello" * 3)
print(3 * "World!")

print(("A", "B", "C") * 3)
print(3 * [1, 2, 3])
7 changes: 7 additions & 0 deletions python-operators-expressions/conditional_expressions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
day = "Sunday"
open_time = "11AM" if day == "Sunday" else "9AM"
print(open_time)

day = "Monday"
open_time = "11AM" if day == "Sunday" else "9AM"
print(open_time)
19 changes: 19 additions & 0 deletions python-operators-expressions/getting_started.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# The minus sign as a unary and as a binary operator
print(-273.15)
print(5 - 2)

# The equality operator
print(42 == 42)

# Operators by themselves aren't valid syntax. The tutorial's bare `-`, `==`,
# and `or` examples raise a SyntaxError, so they only work in the REPL.

# Expressions built with operators
print(7 + 5)
print(42 / 2)
print(5 == 5)

# Expressions that don't need an operator
print(abs(-7))
print(pow(2, 8))
print("Hello, World!")
33 changes: 33 additions & 0 deletions python-operators-expressions/identity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Heads-up: the tutorial runs these examples in the REPL, where each
# statement is compiled on its own, so the two 1001 literals below become two
# separate objects and x is y is False. In a script, Python compiles the whole
# module at once and reuses a single 1001 object for both names, so this file
# prints True where the tutorial prints False. The equality results and the
# string examples are the same either way.

x = 1001
y = 1001

print(x == y)
print(x is y)

# The id() numbers differ on every machine and every run
print(id(x))
print(id(y))

a = "Hello, Pythonista!"
b = a

print(id(a))
print(id(b))

print(a is b)

# The is not operator is the opposite of is
x = 1001
y = 1001
print(x is not y)

a = "Hello, Pythonista!"
b = a
print(a is not b)
7 changes: 7 additions & 0 deletions python-operators-expressions/membership.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# The in operator
print(5 in [2, 3, 5, 9, 7])
print(8 in [2, 3, 5, 9, 7])

# The not in operator
print(5 not in [2, 3, 5, 9, 7])
print(8 not in [2, 3, 5, 9, 7])
13 changes: 13 additions & 0 deletions python-operators-expressions/precedence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
print(20 + 4 * 10)

print(2 * 3**4 * 5)

# Parentheses override the default operator precedence
print((20 + 4) * 10)

print(2 * 3 ** (4 * 5))

# The tutorial closes with a readability example that uses placeholder
# names, so it isn't runnable on its own:
# (a < 10) and (b > 30)
# a < 10 and b > 30
Loading
Loading