1/13
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
PEP 8
Code style checker
Making code that’s easier to read
Can download it into Visual Studio to help you
Improving Visibility
#correct:
#aligned with opening delimiter
foo = long_function_name(var_one, var_two
var_three, var_four)
#add 4 spaces (an extra level of indentaiton) to distinguish arguments from the rest
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
#hanging indents should add a level
foo = long_function_name(
var_one, var_two,
var_three, var_four)
#wrong:
#arguments on first line forbidden when not using vertical alignment
foo = long_function_name(var_one, var_two
var_three, var_four)
#further indentation required as indentation is not distinguishable
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
Continuations and Line Breaks
don’t exceed 79 characters per line
#no extra indentation
if (this_is_one_thing and
that_is_another_thing):
do_something()
#add a comment, which will provide some distinction in editors supporting syntax highlighting
if (this_is_one_thing and
that_is_another_thing):
#since both conditions are true, we can frobnicate
do_something()
#add some extra indentation on the conditional continuation line
if (this_is_one_thing
and that_is_another_thing):
do_something()
Breaking Before or After Binary Operators
The closing brace/bracket/parenthesis on multiple constructs may either line up under the first non whitespace character of the last line of list, as in:
my_list = [
1, 2, 3,
4, 5, 6
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)
or it may be lined up under the first character of the line that starts the multiline construct, as in:
my_list = [
1, 2, 3,
4, 5, 6
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)
Breaks Before or After Operators
#wrong:
#operators sit far away from their operands
income = (gross_wages +
taxable_interest +
(dividends - qualified_dividends) -
ira_deduction -
student_loan_interest)
#correct:
#easy to match operators with operands
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)
Indexing Arrays
Enumerator is iterable
• It produces (index, value) tuples
• We can ‘unpack’ these into variables
zip
people = ['Adrian', 'Joe', 'Saad']
colours = ['red', 'green', 'blue', 'yellow']
n = min(len(people), len(colours))
for i in range(n):
print(people[i], '-->', colours[i])
#or
for person, colour in zip(people, colours):
print(person, '-->', colour)
and even
people = ['Adrian', 'Joe', 'Saad']
colours = ['red', 'green', 'blue', 'yellow']
my_dict = dict(zip(people, colours))
print(my_dict)
{'Adrian': 'red', 'Joe': 'green', 'Saad': 'blue'}
sum and len
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
average = sum(numbers)/len(numbers)
print(average)
#4.0
for…else
def find (seq, target):
found = False
for i, value in enumerate(seq):
if value == target:
found = True
break
if not found:
return -1
return i
def find (seq, target):
for i, value in enumerate(seq):
if value == target:
break
else:
return -1
return i
Note: In Python, for can take ‘else’. This code is equivalent!
In python if you have loops inside a function, any variables normally only accessible inside the loop are now accessible inside the whole function
Can replace break with return i to make code shorter, may want to keep it this way to make more readable, keep returns at the end of a function
Keys
from collections import defaultdict
names = ['Adrian', 'Saad', 'Joe', 'Nigel']
d = defaultdict(list)
for names in names:
key = len(name)
d[key].append(name)
print(d)
Function Parameters
find_robot('Marvin', True, True)
find_robot('Marvin', android = True, paranoid = True)
can be addressed by name so then order doesn’t matter, is true for returns too
doctest.testmod()
(0, 4)
doctest.testmod()
TestResults(failed = 0, attempted = 4)
finally
always gets done - so you don’t leave the resource open if there’s an error
f = open('file.txt', mode = 'r')
try:
data = f.read()
finally:
f.close()
print(data)
Context Manager
automatically closes the resource when done, so you don’t have to
with open('file.txt', mode = 'r') as f:
data = f.read()
print(data)
Generator Expression
An iterator that incrementally yields the values one at a time
Used extensively to avoid creating intermediate data structures
yield is like a return from the function, but maintaining state
yield makes the function start from where it ended last time if the function is called again
Each call yields the next value (in the loop in this case)
def generator():
for i in range(10):
yield i**2