The Python Tutorial: Chapter 4 - More Control Flow Tools Flashcards

1
Q

What do continue and break do?

A

Continue forces the end of the current iteration and starts the next one in a loop
Break end the current loop entirely, this can be useful in things like nested loops. This even applies if the break is buried in an if statement within the loop.

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

What’s an example of using *args and **kwargs?

A

Args allows unlimited arguments, and likewise with keywords

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:

OUTPUT:

– 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

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

When used in a function definition, what do the slash and asterisk characters mean?

A

/
- In a function, if this is passed as a parameter, this means the parameter can be positional or keyword if the parameter follows the slash. If it comes before, then it is positional only
- Only available in Python 3.8 or higher
*
- In a function, this restricts the parameter to keyword only
Only available in Python 3.8 or higher

E.g.
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
———– ———- ———-
| | |
| Positional or keyword |
| - Keyword only
– Positional only

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

What operators are used to unpack lists and dictionaries/keyword arguments?

A
  • for lists and ** for dictionaries/keyword arguments
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Give an example of typing hinting/annotations

A
def hello_name(name: str) -> str:
    return(f"Hello {name}")
Source: https://realpython.com/documenting-python-code/
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are the attributes to access docstrings and annotations?

A

Docstrings are stored in the __.doc__ attribute

Annotations are stored in the __.annotations__ attribute

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