Functions Flashcards

(22 cards)

1
Q

what is elif?

A

The keyword ‘elif‘ is short for ‘else if’, and is useful to avoid excessive indentation. An if … elif … elif … sequence is a substitute for the switch or case statements found in other languages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How does for statement work basically?

A

iterates over the items of any sequence.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is built-in range() function used for?

A

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you iterate over the indices of a sequence?

A
You can combine range and len as follows:
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

In most such cases, however, it is convenient to use the enumerate()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How enumarate works?

A

> > > seasons = [‘Spring’, ‘Summer’, ‘Fall’, ‘Winter’]
list(enumerate(seasons))
[(0, ‘Spring’), (1, ‘Summer’), (2, ‘Fall’), (3, ‘Winter’)]
list(enumerate(seasons, start=1))
[(1, ‘Spring’), (2, ‘Summer’), (3, ‘Fall’), (4, ‘Winter’)]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does rint(range(10)) return and why?

A

range(0, 10)
In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Define iterable and give some examples.

A

We say such an object is iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for statement is such an iterator. The function list() is another; it creates lists from iterables:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How is else clause used on Loops?

A
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:
>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is “pass” used for?

A

pass statement does nothing . Can be used as busy wait for keyboard interrupt in whle loop or as a place holder in a new function or conditional body.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is a symbol table?

A

The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.
The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object). [1] When a function calls another function, a new local symbol table is created for that call.

A function definition introduces the function name in the current symbol table. The value of the function name has a type that is recognized by the interpreter as a user-defined function. This value can be assigned to another name which can then also be used as a function. This serves as a general renaming mechanism

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

When are the default values for the functions evaluated?

A

The default values are evaluated at the point of function definition in the defining scope, so that
i = 5

def f(arg=i):
    print(arg)

i = 6
f()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How does mutable default values for functions behave?

A

The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))
This will print

[1]
[1, 2]
[1, 2, 3]
If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Give examples to keyword and positional arguments

A

In a function call, keyword arguments must follow positional arguments.

parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action=’VOOOOOM’) # 2 keyword arguments
parrot(action=’VOOOOOM’, voltage=1000000) # 2 keyword arguments
parrot(‘a million’, ‘bereft of life’, ‘jump’) # 3 positional arguments
parrot(‘a thousand’, state=’pushing up the daisies’) # 1 positional, 1 keyword

parrot() # required argument missing
parrot(voltage=5.0, ‘dead’) # non-keyword argument after a keyword argument
parrot(110, voltage=220) # duplicate value for the same argument
parrot(actor=’John Cleese’) # unknown keyword argument

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Define how *name and **name are used as function parameteres?

A

When a final formal parameter of the form **name is present, it receives a dictionary (see Mapping Types — dict) containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form name (described in the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list. (name must occur before **name.) For example, if we define a function like this:

def cheeseshop(kind, *arguments, **keywords):
print(“– Do you have any”, kind, “?”)
print(“– I’m sorry, we’re all out of”, kind)
for arg in arguments:
print(arg)
print(“-“ * 40)
for kw in keywords:
print(kw, “:”, keywords[kw])
It could be called like this:

cheeseshop(“Limburger”, “It’s very runny, sir.”,
“It’s really very, VERY runny, sir.”,
shopkeeper=”Michael Palin”,
client=”John Cleese”,
sketch=”Cheese Shop Sketch”)
and of course it would print:

– Do you have any Limburger ?
– I’m sorry, we’re all out of Limburger
It’s very runny, sir.
It’s really very, VERY runny, sir.
—————————————-
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
Note that the order in which the keyword arguments are printed is guaranteed to match the order in which they were provided in the function call.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Define Arbitrary Argument Lists functions

A

Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see Tuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur.

def write_multiple_items(file, separator, *args):
    file.write(separator.join(args))
Normally, these variadic arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the *args parameter are ‘keyword-only’ arguments, meaning that they can only be used as keywords rather than positional arguments.
>>>
>>> def concat(*args, sep="/"):
...     return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is * used for when calling functions?

A

-operator unpacks the arguments out of a list or tuple
»> list(range(3, 6)) # normal call with separate arguments
[3, 4, 5]
»> args = [3, 6]
»> list(range(
args)) # call with arguments unpacked from a list
[3, 4, 5]

17
Q

What is ** used for when calling functions?

A

dictionaries can deliver keyword arguments with the -operator
»> def parrot(voltage, state=’a stiff’, action=’voom’):
… print(“– This parrot wouldn’t”, action, end=’ ‘)
… print(“if you put”, voltage, “volts through it.”, end=’ ‘)
… print(“E’s”, state, “!”)

»> d = {“voltage”: “four million”, “state”: “bleedin’ demised”, “action”: “VOOM”}
»> parrot(
d)
– This parrot wouldn’t VOOM if you put four million volts through it. E’s bleedin’ demised !

18
Q

define lambda functions

A

They are just syntactic sugar for a normal function definition.
Like nested function definitions, lambda functions can reference variables from the containing scope:

>>>
>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

Another use is to pass a small function as an argument:
»> pairs = [(1, ‘one’), (2, ‘two’), (3, ‘three’), (4, ‘four’)]
»> pairs.sort(key=lambda pair: pair[1])
»> pairs
[(4, ‘four’), (1, ‘one’), (3, ‘three’), (2, ‘two’)]

19
Q

Define documentation strings

A

The first line should always be a short, concise summary of the object’s purpose. For brevity, it should not explicitly state the object’s name or type, since these are available by other means (except if the name happens to be a verb describing a function’s operation). This line should begin with a capital letter and end with a period.

If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description. The following lines should be one or more paragraphs describing the object’s calling conventions, its side effects, etc.

The Python parser does not strip indentation from multi-line string literals in Python, so tools that process documentation have to strip indentation if desired. This is done using the following convention. The first non-blank line after the first line of the string determines the amount of indentation for the entire documentation string. (We can’t use the first line since it is generally adjacent to the string’s opening quotes so its indentation is not apparent in the string literal.) Whitespace “equivalent” to this indentation is then stripped from the start of all lines of the string. Lines that are indented less should not occur, but if they occur all their leading whitespace should be stripped. Equivalence of whitespace should be tested after expansion of tabs (to 8 spaces, normally).

20
Q

What are function annotations?

A

Optional metadata information about functions

21
Q

How function annotations defined for arguments?

A

like def a(egg: str): …

a.__annotations__ returns {‘egg’: }

22
Q

How function annotations defined for return types?

A
with an arrow near arguments like 
def f(ham: str, eggs: str = 'eggs') -> str:...
a.\_\_annotations\_\_ return Annotations: {'ham': , 'return': , 'eggs': }