Skip to content
Merged
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
33 changes: 33 additions & 0 deletions python-conditional-statements/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Conditional Statements in Python

This folder provides the code examples for the Real Python tutorial [Conditional Statements in Python](https://realpython.com/python-conditional-statements/).

You can run all of the scripts directly by specifying their name:

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

The scripts only use the standard library, so there's nothing to install.

## The Scripts

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

| Script | Tutorial section |
| --- | --- |
| [`if_statement.py`](./if_statement.py) | Introduction to the `if` Statement |
| [`foo.py`](./foo.py) | Python: It's All About the Indentation (the script file `foo.py`) |
| [`blocks.py`](./blocks.py) | Python: It's All About the Indentation (the script file `blocks.py`) |
| [`else_elif.py`](./else_elif.py) | The `else` and `elif` Clauses |
| [`one_line_if.py`](./one_line_if.py) | One-Line `if` Statements |
| [`conditional_expressions.py`](./conditional_expressions.py) | Conditional Expressions (Python's Ternary Operator) |
| [`pass_statement.py`](./pass_statement.py) | The Python `pass` Statement |

## 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()`, and strings are printed with `repr()` so that the output matches the quoted form the REPL shows.

A few examples deliberately keep their original layout, with the formatter switched off: the commented "Does line execute?" table in `blocks.py`, the one-line `if` statements, and the chained conditional expression. Formatting them would remove what those examples demonstrate. PEP 8 recommends against one-line `if` statements, so don't copy that style into your own code.

The tutorial also shows a script that raises an `IndentationError` because its `if` block is empty. It can't run, so it isn't reproduced here. `pass_statement.py` is the fixed version.
23 changes: 23 additions & 0 deletions python-conditional-statements/blocks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""Nested blocks, where each indent opens a block and each outdent ends one.

The script file blocks.py from the "Python: It's All About the Indentation"
section of the tutorial.
"""

# fmt: off
# Does line execute? Yes No
# --- --
if "foo" in ["foo", "bar", "baz"]: # x
print("Outer condition is true") # x

if 10 > 20: # x
print("Inner condition 1") # x

print("Between inner conditions") # x

if 10 < 20: # x
print("Inner condition 2") # x

print("End of outer condition") # x
print("After outer condition") # x
# fmt: on
56 changes: 56 additions & 0 deletions python-conditional-statements/conditional_expressions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""Conditional expressions, Python's ternary operator.

Code from the "Conditional Expressions (Python's Ternary Operator)" section
of the tutorial. Where the REPL echoed a value, the script calls print().
"""

raining = False
print("Let's go to the", "beach" if not raining else "library")
raining = True
print("Let's go to the", "beach" if not raining else "library")

age = 12
s = "minor" if age < 21 else "adult"
print(repr(s))

print(repr("yes" if ("qux" in ["foo", "bar", "baz"]) else "no"))

# Finding the larger of two numbers with an if statement...
a = 5
b = 8
if a > b:
m = a
else:
m = b
print(m)

# ...and with a conditional expression.
m = a if a > b else b
print(m)

# The conditional expression has lower precedence than + ...
x = y = 40
z = 1 + x if x > y else y + 2
print(z)
z = (1 + x) if x > y else (y + 2)
print(z)

# ...so group it with parentheses to evaluate it first.
z = 1 + (x if x > y else y) + 2
print(z)

# Short-circuit evaluation: the 1 / 0 terms are never evaluated.
print(repr("foo" if True else 1 / 0))
print(repr(1 / 0 if False else "bar"))

# Chained conditional expressions.
x = 3
# fmt: off
s = ("foo" if (x == 1) else
"bar" if (x == 2) else
"baz" if (x == 3) else
"qux" if (x == 4) else
"quux"
)
# fmt: on
print(repr(s))
54 changes: 54 additions & 0 deletions python-conditional-statements/else_elif.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""Choosing between alternatives with else and elif.

Code from "The else and elif Clauses" section of the tutorial.
"""

# else: exactly one of the two suites runs.
x = 20
if x < 50:
print("(first suite)")
print("x is small")
else:
print("(second suite)")
print("x is large")

x = 120
if x < 50:
print("(first suite)")
print("x is small")
else:
print("(second suite)")
print("x is large")

# elif: Python runs the suite of the first condition that's true.
name = "Joe"
if name == "Fred":
print("Hello Fred")
elif name == "Xander":
print("Hello Xander")
elif name == "Joe":
print("Hello Joe")
elif name == "Arnold":
print("Hello Arnold")
else:
print("I don't know who you are!")

# A more Pythonic alternative using dict.get().
names = {
"Fred": "Hello Fred",
"Xander": "Hello Xander",
"Joe": "Hello Joe",
"Arnold": "Hello Arnold",
}
print(names.get("Joe", "I don't know who you are!"))
print(names.get("Rick", "I don't know who you are!"))

# Short-circuit evaluation: once a condition is true, the remaining ones
# aren't tested, so neither the division by zero nor the undefined name
# var raises an error.
if "a" in "bar":
print("foo")
elif 1 / 0:
print("This won't happen")
elif var: # noqa: F821
print("This won't either")
13 changes: 13 additions & 0 deletions python-conditional-statements/foo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""A block that is skipped because its condition is false.

The script file foo.py from the "Python: It's All About the Indentation"
section of the tutorial. The four indented print() calls form the block,
and only the last line runs.
"""

if "foo" in ["bar", "baz", "qux"]:
print("Expression was true")
print("Executing statement in suite")
print("...")
print("Done.")
print("After conditional")
32 changes: 32 additions & 0 deletions python-conditional-statements/if_statement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""The simplest form of the if statement.

Code from the "Introduction to the if Statement" section of the tutorial.
Each condition is marked as truthy or falsy. Only the truthy ones print.
"""

x = 0
y = 5

if x < y: # Truthy
print("yes")

if y < x: # Falsy
print("yes")

if x: # Falsy
print("yes")

if y: # Truthy
print("yes")

if x or y: # Truthy
print("yes")

if x and y: # Falsy
print("yes")

if "aul" in "grault": # Truthy
print("yes")

if "quux" in ["foo", "bar", "baz"]: # Falsy
print("yes")
44 changes: 44 additions & 0 deletions python-conditional-statements/one_line_if.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""Writing an if statement, or each of its clauses, on a single line.

Code from the "One-Line if Statements" section of the tutorial. The one-line
layout is the point of this section, so the formatter is switched off and
the style warnings are silenced. PEP 8 recommends against writing code
like this.
"""

# fmt: off
# The statements after the colon form one suite: all of them run, or none.
if "f" in "foo": print("1"); print("2"); print("3") # noqa: E701, E702
if "z" in "foo": print("1"); print("2"); print("3") # noqa: E701, E702

for x in (2, 3):
if x == 1: print("foo"); print("bar"); print("baz") # noqa: E701, E702
elif x == 2: print("qux"); print("quux") # noqa: E701, E702
else: print("corge"); print("grault") # noqa: E701, E702
# fmt: on

# Most people find the multi-line form easier to read.
x = 3
if x == 1:
print("foo")
print("bar")
print("baz")
elif x == 2:
print("qux")
print("quux")
else:
print("corge")
print("grault")


# A simple one-line if is usually acceptable.
def foo():
print("Calling foo()")


debugging = True # Set to True to turn debugging on.

# fmt: off
if debugging: print("About to call function foo()") # noqa: E701
# fmt: on
foo()
11 changes: 11 additions & 0 deletions python-conditional-statements/pass_statement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
"""Using pass as a placeholder where a statement is syntactically required.

The fixed version of foo.py from "The Python pass Statement" section of the
tutorial. Without the pass line, the empty if block raises an
IndentationError, so that version isn't reproduced here.
"""

if True:
pass

print("foo")
Loading