What is Python?
A strongly typed dynamic language.
What are valid characters for Python names?
Letters, digits, and underscore; cannot start with a digit.
What naming convention is used for variables and functions in Python?
Lowercase with words separated by underscores (e.g., do_it_like_this).
How are class names written in Python?
Upper CamelCase (e.g., ClassNameHere).
How to handle exceptions in Python?
Use try-except blocks.
What is a module in Python?
A file containing Python code, usually with a .py extension.
What is a package in Python?
A namespace containing multiple modules, often with an init.py file.
What is the purpose of the init.py file in Python packages?
Contains package initialization logic.
How to create a virtual environment in Python?
Use the venv module: python3 -m venv /path/to/new/virtual/environment.
What is the difference between lists and tuples in Python?
Lists are mutable, tuples are immutable.
How to create a dictionary in Python?
Use curly braces {} with key-value pairs.
What is a lambda function in Python?
An anonymous function expressed as a single statement.
How to iterate over a dictionary in Python?
Use .items() to get key-value pairs, .keys() for keys, and .values() for values.
How to install an external package in Python?
Use pip: pip install package_name.
What is a list comprehension in Python?
A compact way to process all or part of the elements in a collection and return a list of results.
What is a set in Python?
An unordered collection of unique elements.
How to open a file in Python?
Use the open() function: open(filename, mode).
What does the 'w' mode do in open() function in Python?
Opens a file for writing, creates the file if it does not exist.
What is the purpose of the with statement in Python file handling?
Ensures that the file is properly closed after its suite finishes, even if an exception is raised.
What is the difference between the append() and extend() methods in lists?
append() adds its argument as a single element to the end of a list. extend() iterates over its argument adding each element to the list, extending the list.
How to check if a key exists in a dictionary?
Use the in keyword: 'key' in my_dict.
What is the output of print(1, 2, 3, sep='-', end='\n') in Python?
1-2-3 followed by a newline.
How to concatenate two lists in Python?
Use the + operator or the extend() method.
What does the range function in Python do?
Generates a sequence of numbers.
How to convert a list to a tuple in Python?
Use the tuple() function: tuple(my_list).
What is the purpose of the pass statement in Python?
It is a null statement used to define an empty block of code.
How to remove items from a list in Python?
Use the remove() method for a specific value or pop() for an index.
How to reverse a list in Python?
Use the reverse() method or the slicing syntax list[::-1].
What does the ** operator do in Python?
Performs exponentiation.
What is the difference between == and is in Python?
== checks if values are equal, is checks if objects are the same (identity).
What does the enumerate function in Python do?
Adds a counter to an iterable and returns it.
How to create a shallow copy of a list?
Use the copy() method or the slicing syntax list[:].
What is a deep copy in Python?
A copy where all objects are duplicated recursively, not just the top-level container.
How to format strings in Python?
Use f-strings or the format() method.
What does the zip function in Python do?
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
How to handle multiple exceptions with a single except block?
Use a tuple of exceptions in the except clause.
What is the purpose of the global keyword in Python?
To declare that a variable inside a function is global (not local).
What is the purpose of the 'raise' keyword in Python?
To throw an exception.
How can multiple exceptions be caught in Python?
Using several 'except' clauses.
try: xxxx
except: (blaError1, blaError2) as error:
print(“oopsie”)
What does the 'else' clause in try-except block specify?
Code that should only be run when no exceptions have occurred.
good for readability
finally
add a block of code that is allways executed
e.g close connection to server/database
multiple assignment
x, y = y, x
a,b,c,d,e,f,g,… = “Hello World!”
How are multiple (tuple, iterable) assignments used in Python?
For unpacking iterable objects into multiple variables.
What is the use of arbitrary number of arguments in functions?
To allow a function to accept a variable number of arguments.
*args
it is possible to combine *args with keyword arguments
*args, power =1
What module is used in Python for mathematical operations?
The math module.
ceil(5.6) -> 5
floor(5.6) -> 5
sqrt(81) -> 9
factorial(6) -> 720
comb(10,3) -> 120
perm(10,3) -> 720
cos(x)
degrees(x)
How do you add items to a list in Python?
Using methods like append, extend, or insert.
What makes tuples different from lists in Python?
Tuples are immutable.
How can you remove items from a set in Python?
Using methods like remove, discard, or pop.
What is a decorator in Python?
A function that modifies the behavior of another function.
How do class methods differ from static methods?
Class methods take a 'cls' parameter that points to the class, while static methods do not.
What is the purpose of context managers in Python?
To manage resources like file streams with the 'with' statement.
How can you implement a custom iterator in Python?
By defining __iter__() and __next__() methods.
What are magic methods in Python?
Special methods with double underscores used to emulate the behavior of built-in types.
What is the difference between __str__ and __repr__?
__str__ is for readable output, __repr__ is for unambiguous output.
How do you define a property in Python?
Using the @property decorator to define getter, setter, and deleter.
What is memoization in the context of decorators?
Caching the results of expensive function calls.
How can you ensure a function accepts only strings as input?
Using a decorator to check argument types.
What is the purpose of the 'super()' function?
To call methods of a parent class from the child class.
How do you enforce private variables in Python?
By prefixing the variable name with double underscores (__).
How can custom exceptions be defined in Python?
By subclassing Exception or a derived class.
What is exception chaining in Python?
Using the 'from' keyword to chain exceptions, providing context to the original exception.
How do keyword-only arguments in functions enhance code clarity?
By forcing some arguments to be specified by their names, improving readability.
What are function annotations in Python, and how are they used?
Annotations provide a way to attach metadata to function parameters and return values, mainly for documentation purposes.
How does the iterable protocol work in Python?
By implementing __iter__() to return an iterator object, which then implements __next__() to access elements one at a time.
What is the difference between __iter__ and __next__ in the context of iterators?
__iter__ returns the iterator object itself, __next__ moves to the next item in the sequence.
How can magic methods like __add__ or __len__ be used in Python classes?
To enable operators and built-in functions like + or len() to work with custom objects.
What is the significance of the __call__ magic method?
It allows an instance of a class to be called as a function.
How do decorators enhance functions or methods in Python?
By wrapping another function, allowing for the extension or modification of its behavior without directly modifying it.
What is the 'with' statement, and how does it relate to context managers?
The 'with' statement simplifies resource management by automatically handling setup and cleanup operations, using context managers.
Conditional expression
allows us to achieve the same result with a one‐liner:
mushroom_growth = 'Good' if raining else 'Bad'
dafault paprameters
Keyword arguments
We can unpack collections and pass their values as arguments to a function
We can do the same with dictionaries and keyword arguments:
Functions as Objects
Lambdas
Lambdas allow us to create a function inline (in place) where it’s needed:
complex numbers
decimals
Fraction
Fraction(1,2)
Fraction(1.5) = Fraction(3,2)
interessting modules python
statistic
random
lists
clear
copy
clear -> removes all items
copy -> creates a shallow copy (wenn man die Kopie verändert verändert sich auch das original da sie auf die gleichen elemente zeigen)
index
count
list : sort (not) in place
slicing
my_list = ['a', 'b', 'c', 'b', 'a', 'a']
my_list[0:3]
my_list[3:-1]
my_list[:3]
my_list[3:]
my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
my_list[1:8:2]
my_list[::-1]
my_list[0:3] -> [a, b, c]
my_list[3:-1] -> [b, a]
my_list[:3] -> [a, b, c]
my_list[3:] -> [b, a, a]
my_list[1:8:2] -> [b, d, f, h]
my_list[::-1] -> ['i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
List Comprehensions
more on tupels
dictionarys
access key that is not in dictionary
More on sets
set comprehensions
More on Strings
String formating
f-strings
str.format
named Tuple
to group variables (properties, attributes) together
Counter
to count collections’ items
most_common(3)
OrderedDict
to make sure the insertion order is preserved and checked
deque
to get efficient stack‐like and queue‐like functionality
deque allows us to efficiently add elements to both ends of the data structure as opposed to regular Python lists. However, keep in mind that there is no golden pill (or silver bullet, if you like), and gaining efficiency in some operations probably means losing efficiency with others. Which operations does a deque perform less efficiently than a regular list?
iter() and __iter__()
Iterators
what’s an iterator?
how exactly does one create it?
why custom iterator?
An iterator is an object representing a stream of data.
Iterators are required to implement two methods:
__next__
__iter__
The __iter__ method should return the iterator object itself to allow using an iterator with a for...in loop.
Why custom iterator:
However, consider parsing a 10 GB FASTA file. We probably don’t want to load all the records in memory at once, so we might use an iterator (iterators are lazy). In other situations we might actually need an infinite number of values, or the iteration might have complex logic.
Iterables
iterators, but how exactly are they created?
The __iter__ method must return an iterator object.
Oh, and by the way, objects that have the __iter__ method are iterables.
Iterables and Iterators: Overview
an iterable is an object that is capable of returning its elements one by one and implements an __iter__ method;
an iterator is an object that represents a stream of data and implements an __iter__ method and a __next__ method;
when we use an iterable in a for...in loop, an iterator is automatically created and is used to produce values until exhaustion;
an iterator SHOULD NOT change the corresponding iterable.
magic/dunder methods
__init__
__repr__ -> allows us to change the way an object is
represented
__str__ -> allows us to tune casting an object to a string.
__eq__ -> wann sind elemente gleich
__len__
__abs__, __add__, __and__, __bool__, __ceil__
__repr__ and __str__ method fallback?
__repr__ is used as a fallback method for casting to a string when __str__ is not available
__str__, on the other hand, is not used as a fallback method for representation.
callables
make instances of our classes callable like functions
Decorating Functions
To decorate a function means to modify its behaviour, to execute some code before or after the function itself is executed.
Decorators (Class-Based)
Vorteile:
wiederholten COde vermeiden -> ABER wieso keine methoden (würde die Methode aufblähen)
Decorator außen -> übersichtliche und intuitiver
Decorators Usage
Decorators allows us to create specialized reusable chunks that can be applied to other functions. They help us to avoid writing boilerplate code. When used correctly, they make reasoning about code easier.
We probably want to use decorators in the following cases:
authentication / authorization
logging
benchmarking
validating input;
sanitizing input
changing function’s output
registering functions.
Class Methods
Class Methods - Factories
Static Methods
Access Control
Single Leading Underscore
Double Leading Underscore
Properties
Context Manager
to work with files, time benshmarking, database connection
__enter__ and__exit__ methods
Generators
Keyword: yield
A generator is a function that returns a generator iterator:
enumerate
enumerate(xx, 5) -> start index value 5
index += 1
Increment
zip
zip wraps two (or more) iterables with a lazy generator that yields tuples containing pairs of next values from each iterable.
zip macht nur so lange bis die kleiner liste aufgebraucht ist
map&filter
Context manager
function vs. class based
we can create a context manager using a function that yields and acontextmanager decorator
Decorators (Function-Based)
Can we create functions that accept functions and return functions? - Nested Functions
Accessing Variables of the Outer Function
Closure
use cases:
data hiding/protection (not bulletproof)
implementing function factories (creating functions at runtime)
decorators
We can use closures to implement function factories that create functions at runtime
Closures: Data hiding/protection
*args and **kwargs
Decorators with Parameters
Decorators are great, however, there is one problem:
Function-Based Decorators: Overview
Type Hints
type hints allow us to specify types for variables, function parameters, and function return values
IDEs/editors and 3rd party tools can perform static type checking
libraries like pydantic allow us to perform validation based on type hints
Type Hints - Validation with Pydantic
Data Classes
@dataclass decorator
Last changed10 months ago