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
34 changes: 34 additions & 0 deletions python-or-operator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Using the "or" Boolean Operator in Python

This folder provides the code examples for the Real Python tutorial [Using the "or" Boolean Operator in Python](https://realpython.com/python-or-operator/).

## Setup

The scripts only use the standard library, so there's nothing to install. The tutorial's code was tested with Python 3.15, and the scripts run on Python 3.6 or later.

## Usage

You can run each script directly by specifying its name:

```sh
$ python <filename>.py
```

Each script collects one part of the tutorial, in the order the tutorial presents it:

| Script | Tutorial section |
| --- | --- |
| [`boolean_expressions.py`](./boolean_expressions.py) | Using `or` With Boolean Expressions, Using `or` With Common Objects, Mixing Boolean Expressions and Objects |
| [`short_circuit.py`](./short_circuit.py) | Short-Circuit Evaluation |
| [`if_statements.py`](./if_statements.py) | `if` Statements |
| [`while_loops.py`](./while_loops.py) | `while` Loops |
| [`default_values.py`](./default_values.py) | Non-Boolean Contexts, Default Values for Variables, Default `return` Values |
| [`mutable_defaults.py`](./mutable_defaults.py) | Mutable Default Arguments |
| [`zero_division.py`](./zero_division.py) | Zero Division |
| [`lambda_expressions.py`](./lambda_expressions.py) | Multiple Expressions in `lambda` |

## A Note on the Examples

Most of the tutorial's examples are REPL sessions. In the scripts, values that the REPL would echo are passed to `print()`. Examples that raise an exception on purpose catch it and print the error message instead.

`if_statements.py` asks for your input once, and `while_loops.py` uses a simulated `measure_temp()` function that returns three fixed readings, so the loop takes about a minute to finish because of the 30-second pauses from the tutorial.
21 changes: 21 additions & 0 deletions python-or-operator/boolean_expressions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Using or with Boolean expressions
exp1 = 1 == 2
print(exp1)
exp2 = 7 > 3
print(exp2)
print(exp1 or exp2) # True, because exp2 is True
print(exp2 or exp1) # Also True
exp3 = 3 < 1
print(exp1 or exp3) # False, because both are False

# Using or with common objects
print(2 or 3)
print(5 or 0.0)
print([] or 3)
print(0 or {})

# Mixing Boolean expressions and objects
print(2 < 4 or 2) # Case 1
print(2 < 4 or []) # Case 2
print(5 > 10 or []) # Case 3
print(5 > 10 or 4) # Case 4
43 changes: 43 additions & 0 deletions python-or-operator/default_values.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Assigning the result of an or expression to a variable
a = 1
b = 2
var1 = a or b
print(var1)

a = None
b = 2
var2 = a or b
print(var2)

a = []
b = {}
var3 = a or b
print(var3)

# Default values for variables
a = 0
b = ""
x = a or b or None
print(x)

default = "default value"
x = a or default
print(x)

# Default return values
lst = [] # Empty list to test max() and min()
try:
max(lst)
except ValueError as error:
print(f"ValueError: {error}")
try:
min(lst)
except ValueError as error:
print(f"ValueError: {error}")

# Use Python or operator to modify this behavior
print(max(lst or [0])) # Return 0
print(min(lst or [0])) # Return 0

# The explicit alternative: the default keyword argument
print(max(lst, default=0))
19 changes: 19 additions & 0 deletions python-or-operator/if_statements.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
def answer():
ans = input("Do you...? (yes/no): ")
if ans.lower() == "yes" or ans.lower() == "y":
print(f"Positive answer: {ans}")
elif ans.lower() == "no" or ans.lower() == "n":
print(f"Negative answer: {ans}")


def my_range(x):
if x < 20 or x > 40:
print("Outside")
else:
print("Inside")


if __name__ == "__main__":
answer()
my_range(25)
my_range(18)
6 changes: 6 additions & 0 deletions python-or-operator/lambda_expressions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Running two expressions in a lambda with the or operator
lambda_func = lambda hello, world: print(hello, end=" ") or print(world) # noqa: E731
lambda_func("Hello", "World!")

result = lambda_func("Hello", "World!")
print(result)
35 changes: 35 additions & 0 deletions python-or-operator/mutable_defaults.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# A mutable default argument retains state between calls
def mutable_default(lst=[]): # Try to use a mutable value as default
lst.append(1) # Change same object each time
print(lst)


mutable_default(lst=[3, 2]) # Default not used
mutable_default() # Default used
mutable_default() # Default grows on each call
mutable_default()


# The traditional (and safest) solution
def mutable_default(lst=None): # Use None as formal default
if lst is None:
lst = [] # Default used? Then lst gets a new empty list.
lst.append(1)
print(lst)


mutable_default(lst=[3, 2]) # Default not used
mutable_default() # Default used
mutable_default()


# Almost the same, using the or operator
def mutable_default(lst=None): # Use None as formal default
lst = lst or [] # Default used? Then lst gets an empty list.
lst.append(1)
print(lst)


mutable_default(lst=[3, 2]) # Default not used
mutable_default() # Default used
mutable_default()
17 changes: 17 additions & 0 deletions python-or-operator/short_circuit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
print(True or 4 < 3)


def true_func():
print("Running true_func()")
return True


def false_func():
print("Running false_func()")
return False


print(true_func() or false_func()) # Case 1
print(false_func() or true_func()) # Case 2
print(false_func() or false_func()) # Case 3
print(true_func() or true_func()) # Case 4
19 changes: 19 additions & 0 deletions python-or-operator/while_loops.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from time import sleep

# Simulated readings, so the script runs without real equipment
READINGS = iter([95, 150, 120])


def measure_temp():
return next(READINGS)


temp = measure_temp() # Initial temperature measurement

while temp < 100 or temp > 140:
print("Temperature outside the recommended range")
print("New Temperature measure in 30 seconds")
sleep(30)
print("Measuring Temperature...")
temp = measure_temp()
print(f"The new Temperature is {temp} ºF")
19 changes: 19 additions & 0 deletions python-or-operator/zero_division.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Guarding against zero division with an if statement
def divide(a, b):
if not b == 0:
return a / b


print(divide(15, 3))
print(divide(0, 3))
print(divide(15, 0))


# A similar result using the or operator (a demo, not a pattern to copy)
def divide(a, b):
return b == 0 or a / b


print(divide(15, 3))
print(divide(0, 3))
print(divide(15, 0))
Loading