Chapter 6 - Functions and stuff Flashcards
What is the general form of a function?
def functionname(parameters):
“"”Docstring”””
#function body
keyword def
starts the header for a function, and header must end in : like all good things in python
what is a docstring?
a string in triple quotes under a function header, when called with keyword def
def sqrt(sidelen):
“”"”DOCSTRING””””
will return docstring
can you return multiple things from a function?
kind of, returns a single tuple but you can use that tuple to set equal to like a, b, c
formal vs actual parameters
formal = in header, actual is in function
what do functions with no return statement return?
special value None
what is a lambda function?
short one line functions w/o the need for the def keyword, created via lambda keyword
lambda argument(s): expression
ex.
times3 = lambda num: num*3
times3(4)
would return 12
confined to only one simple expression
can a function print and return?
yes, but bad form so avoid it
Write a function that will shuffle the elements in a tuple and return the result.
from random import shuffle
def tup_shuffle(tup):
“"”shuffles elements of a tuple and returns result”””
tuplist = list(tup)
shuffle(tuplist)
return tuple(tuplist)
tup_shuffle((1, 4, 3))
rmr, shuffle function shuffles IN PLACE! and ONLY ON MUTABLES!
write a one-line lambda function to add “, eh?” to a string
pluscanada = lambda userin: userin + “, eh?”
what will this print:
list1 = [1, 2, 3, 4, 5]
list2 = list1
list1[0] = 45
print(list1, list2)
[45, 2, 3, 4, 5] [45, 2, 3, 4, 5]
when MUTABLE type, location remains unchanged, and so list2 still points at the same place list1 points at post-modification.
no new list is created, thus they stay linked to the same mem. location
whats up with slicing and memory location?
for MUTABLE TYPES, slicing, even if it slices through everything and returns what looks like the exact same result, refers to a different memory location.
IMMUTABLE types like strings and tuples dont give af, will remain the same
when does memory location remain the same under a change in place like +, -, *, append, etc.?
when it is a mutable type! immutable types are immutable, and thus the variables are assigned a completely new value, rather than being mutated.
how would you swap two variables without a temporary variable?
a, b = b, a
simultaneous assignment is simultaneous, happens all in one instant and thus the switch will complete successfully
what is the ONLY way to modify an argument passed in/referred to in a function within the function?
by altering the argument through append() or smth, cannot simply reassign new (thus, immutable things like integers cannot be modified at all)