Python Crash Course Flashcards
What restrictions are there on Python variable names?
They can’t start with numbers or special symbols.
How do you use the .format function for string replacement?
‘my number is {} and my name is {}.’.format(num, name)
What naming convention do you use for functions and variables?
CamelCase and underscore naming convention respectively.
How do you avoid having to worry about variable positioning with .format?
‘my number is {a} and my name is {b}.’.format(a=num, b=name)
What does s[0:] do?
It slices the string s from the start ( index 0 ) to the end.
What does s[:3] do?
It slices the string s from the start to index 2 ( 3-1 )
How do you add values to a list?
my_list.append(‘d’)
How would you access 4 in nest = [1,2,[3,4]] ?
nest[2][1]
How would you access ‘target in nest = [1,2,[3,4,[‘target’]]] ?
nest[2][2][0]
What syntax is used for Python dictionaries?
d = {‘key1’:’value’, ‘key2’:123}
Give an example of a dictionary that contains a list.
d = {‘k1’:[1,2,3]}
Give an example of a dictionary nested inside a dictionary and access one of its innermost members.
d = {‘k1’:{‘innerkey’:[1,2,3]}}
d[‘k1’][‘innerkey’][1]
What’s the difference between tuples and lists?
Tuples are immutable, their members cannot be changed.
What syntax is used to create a set?
Braces. The distinguishing element between dictionaries and sets are colons.
Can sets contain more than one of the same value?
No. Sets by definition can only contain unique elements.
Write a for loop that uses the keyword ‘in’
seq = [1,2,3]
for item in seq:
print(item)
Print the elements of the range 0 through 4
for x in range(0,5):
print(x)
Create a list of the numbers 0 through 4 using range
list(range(5))
Simplify the following using list comprehension:
x = [1,2,3,4]
out = []
for num in x:
out.append(num**2)
print(out)
x = [1,2,3,4]
out = [num**2 for num in x ]
Write a basic function using Python
def my_func(param1):
print(param1)
Write a function with a default parameter value.
def my_func(name=’DEFAULT’):
print(‘Hello ‘ + name)
How do you access the DocStrings of a function?
Shift + Tab
How do you write a Docstring?
”””
DOCSTRING
“””
Write a map for the following:
def times2(var):
return var*2
seq = [1,2,3,4,5]
list(map(times2,seq))
=> [2,4,6,8,10]
Write a lambda expression for the following:
def times2(var):
return var*2
seq = [1,2,3,4,5]
list(map(lambda num:num*2, seq))
Write a filter expression that results in only even numbers for the following:
seq = [1,2,3,4,5]
list(filter(lambda num: num%2 == 0, seq))
how do you split an email address into its identifier and domain?
email.split(‘@’)
How do you split a string s into a list of strings by spaces?
s.split()
How do you remove the first element of a list ‘lst’ adn assign it to a variable ‘first’?
first = lst.pop()
How do you unpack a tuple?
for a,b in x:
print(b)