Skip to content

Commit 86387bc

Browse files
committed
Add conditional expression and short circuiting
1 parent a5d72b0 commit 86387bc

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

python.rst

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1552,6 +1552,7 @@ and an optional ``else`` statement at the end. In Python, the word ``elif`` is D
15521552

15531553
Python supports the following tests: ``>``, ``>=``, ``<``, ``<=``, ``==``, and ``!=``. For boolean operators use ``and``, ``or``, and ``not`` (``&``, ``|``, and ``^`` are the bitwise operators).
15541554

1555+
15551556
Note that Python also supports *range comparisons*::
15561557

15571558
>>> x = 4
@@ -1605,6 +1606,31 @@ The following table lists *truthy* and *falsey* values:
16051606
| ``'0'`` | |
16061607
+-------------------+---------------------------------+
16071608

1609+
Short Circuiting
1610+
----------------
1611+
1612+
The ``and`` statement will short circuit if it evaluates to false::
1613+
1614+
>>> 0 and 1/0
1615+
0
1616+
1617+
Likewise, the ``or`` statement will short circuit when something evaluates to true::
1618+
1619+
>>> 1 or 1/0
1620+
1
1621+
1622+
Ternary Operator
1623+
------------------
1624+
1625+
Python has its own ternary operator, called a *conditional expression* (see PEP 308). These are handy as they can be used in comprehension constructs and ``lambda`` functions::
1626+
1627+
>>> last = 'Lennon' if band == 'Beatles' else 'Jones'
1628+
1629+
Note that this has similar behavior to an ``if`` statement, but it is an expression, and not a statement. Python
1630+
distinguishes these two. An easy way to determine between the two, is to remember that an expression follows a ``return`` statement. Anything you can ``return`` is an expression.
1631+
1632+
1633+
16081634

16091635

16101636
Exceptions
@@ -2278,14 +2304,14 @@ You can import a package or a module::
22782304
import packagename
22792305
import packagename.module1
22802306

2281-
Assume there is a ``fib`` function in ``module1``. You have access to everything in the namespace of the module you imported::
2307+
Assume there is a ``fib`` function in ``module1``. You have access to everything in the namespace of the module you imported. To use this function you will need to use the fully qualified name, ``packagename.module1.fib``::
22822308

22832309
import packagename.module1
22842310

22852311
packagename.module1.fib()
22862312

2287-
To use this you will need to use the fully qualified name, ``packagename.module1.fib``.
2288-
If you only want to import the ``fib`` use the ``from`` variant::
2313+
2314+
If you only want to import the ``fib`` function, use the ``from`` variant::
22892315

22902316
from packagename.module1 import fib
22912317

0 commit comments

Comments
 (0)