...

/

Other Recommendations

Other Recommendations

In this lesson, we will see some recommended techniques of writing a Pythonic code.

If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority.

Press + to interact
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

Function annotations should use the normal rules for colons and always have spaces around the -> arrow if present.

Press + to interact
def munge(input: AnyStr):
...
def munge() -> AnyStr:
...

Don’t use spaces around the = sign when used to indicate a keyword argument, or when used to indicate a default value for an unannotated function parameter.

Press + to interact
def complex(real, imag=0.0):
return magic(r=real, i=imag)

When combining an argument annotation with a default value, however, do use spaces around the = sign:

Press + to interact
def munge(sep: AnyStr = None):
...
def munge(input: AnyStr, sep: AnyStr = None, limit=1000):
...

Compound statements (multiple statements on the same line) are generally discouraged.

Press + to interact
if foo == 'blah':
do_blah_thing()
do_one()
do_two()
do_three()