🐍 Python - Control Structures
Updated at 2017-01-02 23:22
if
-statement.
x: int = 10
if x > 0:
print('over zero!')
elif x < 0:
print('under zero!')
else:
print('zero!')
if
can be used as an expression.
greeting = 'Hello!' if 4 > 5 else 'Yo!'
assert greeting == 'Yo!'
assert ('yes!' if 3 > 2 else 'no!') == 'yes!'
Prefer truthy and falsy checks. In Python world, this is a common practice.
name = 'Safe'
pets = ['Dog', 'Cat', 'Hamster']
owners = {'Safe': 'Cat', 'George': 'Dog'}
# bad
if name != '' and len(pets) > 0 and owners != {}:
print('We have pets!')
# good
if name and pets and owners:
print('We have pets!')
Use implicit line joining of ()
to form multiline condition statements.
width: int = 100
height: int = 0
color: str = 'red'
emphasis: str = 'strong'
if (width and not height and
color and emphasis == 'strong'):
print('Nice work!')
Prefer try
over if
. Catching exceptions is cheap in Python and will result in more pythonic code.
from typing import Dict
# bad
d: Dict[str, str] = {'x': '5'}
if 'x' in d and isinstance(d['x'], str) and d['x'].isdigit():
value = int(d['x'])
else:
value = None
assert value == 5
# good
d: Dict[str, str] = {'x': '5'}
try:
value = int(d['x'])
except (KeyError, TypeError, ValueError):
value = None
assert value == 5