Being Pythonic

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/13

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

14 Terms

1
New cards

PEP 8

  • Code style checker

  • Making code that’s easier to read

  • Can download it into Visual Studio to help you

2
New cards

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)

3
New cards

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()

4
New cards

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', 
)

5
New cards

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)

6
New cards

Indexing Arrays

Enumerator is iterable

• It produces (index, value) tuples

• We can ‘unpack’ these into variables

<p>Enumerator is iterable</p><p>• It produces (index, value) tuples</p><p>• We can ‘unpack’ these into variables</p><p></p>
7
New cards

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'}

8
New cards

sum and len

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
average = sum(numbers)/len(numbers)
print(average)
#4.0

9
New cards

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

10
New cards

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)

11
New cards

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)

12
New cards

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)

13
New cards

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)

14
New cards

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