Python is a high-level, general-purpose
programming language. Its design philosophy emphasizes code readability
with the use of significant indentation via the off-side rule.
Python is dynamically typed and garbage-collected. It supports multiple
programming paradigms, including structured (particularly procedural),
object-oriented and functional programming. It is often described as a
“batteries included” language due to its comprehensive standard library.
Guido_van_Rossum began working on Python in the late 1980s as a successor to
the ABC programming language and first released it in 1991 as Python 0.9.0.
Python 2.0 was released in 2000. Python 3.0, released in 2008, was a major
revision not completely backward-compatible with earlier versions.
Python is a multi-paradigm programming language. object-oriented
programming and structured programming are fully supported, and many of
their features support functional programming and aspect-oriented
programming (including metaprogramming and metaobjects). Many other paradigms
are supported via extensions, including design by contract and logic
programming.
Python uses dynamic typing and a combination of reference counting and a
cycle-detecting garbage collector for memory management. It uses dynamic name
resolution (late binding), which binds method and variable names during
program execution.
Its design offers some support for functional programming in the Lisp
tradition. It has filter, map and reduce functions; list comprehensions,
dictionaries, sets, and generator expressions. The standard library has two
modules (itertools and functools) that implement functional tools borrowed
from Haskell and Standard ML.
— Wikipedia
In next sections I cover basics of Python language with Q/A flashcards based on
learnxinyminutes 1 cheatsheet.
1. Primitive Datatypes and Operators
How to write comments, their types and usage?
What is the result of this division 10.0 / 3?
The result of division is always float, 10.0 / 3 => 3.3333333333333335
What is the modulo operation?
Mathematical operation that finds the remainder of an integer division.
What is exponentiation and how to use it in Python?
Raise a number to a power. In python exist special operator **, 2**3 => 8,
x**y, x to the y’th power.
How to enforce custom precedence in Python?
Need to use parentheses:
5 // 3 # => 1
-5 // 3 # => -2
5.0 // 3.0 # => 1.0 # works on floats too
-5.0 // 3.0 # => -2.0
Most basic and efficient data type in Python (and other languages) is?
Boolean values, they are primitives (Note: the capitalization)
`
How do you negate a Boolean value?
With not.
Boolean Operators in python?
“and” and “or”, case-sensitive
How do True and False relate to numerical values?
True and False are actually 1 and 0 but with different keywords.
How do comparison operators actually work?
Look at the numerical value of True and False or boolean representations of
values.
How do you evaluate None, 0, and empty
strings/lists/dicts/tuples/sets?
None, 0, and empty strings/lists/dicts/tuples/sets all evaluate to False. All
other values are True.
How do boolean logical operators (and, or) on ints work (casting), bool(X)?
Using boolean logical operators (and/or) on ints casts them to booleans for evaluation,
but their non-cast value is returned. Don’t mix up with bool(ints) and bitwise
and/or (&,|).
How to use equality in Python?
Equality is the == operator.
How to use inequality in Python?
Inequality is the != operator.
How to use more or less than operators in Python?
How do you see whether a value is in a numeric range (1..100)?
You can use following comparations:
What is the difference between is and ==?
How do you create strings?
Strings are created with ” or ‘.
How do you add (concatenate) strings?
Can be string treated like a list of characters?
How do you find the length of a string or array?
What are f-strings?
Since Python 3.6, you can use f-strings or formatted string literals, to place
variables inside a string (sort of template).
Is None an object?
Yes, like any other data.
How do you compare objects to None and why?
is checks to see if the object is the same object, while == just checks if
they are equivalent, some classes have custom comparison methods that treat == None differently from is None.
Don’t use the equality ”==” symbol to compare objects to None Use “is” instead.
This checks for equality of object identity.
2. Variables and Collections
What is the print function?
Prints text to the console
How do you get input from the console?
Is there a declaration in Python (cpython)?
There are no declarations (Python type hints are not declarations), only assignments.
Convention in naming variables is?
snake_case style and not starting with number
What happens if you access an unassigned variable?
Accessing a previously unassigned variable is an exception.
See 3. Control Flow and Iterables to learn more about exception handling.
How can you use if as an expression (like ternary operator)?
Equivalent of C’s ?: ternary operator.
What are lists, how to create them?
Data structure which store sequences.
How do you add elements to a list and remove them?
How do you access elements in a list?
Looking out of list bounds (accessing) is an?
index error:
How do you look at ranges in a list?
Fill this list:
You can look at ranges with slice syntax. The start index is included, the end
index is not (it’s a closed/open range for you mathy types).
Can we use slicing to create copy of list?
Yes. But be careful, we are creating shallow copy.
How do you remove arbitrary elements from a list?
Remove arbitrary elements from a list with “del”
How do you remove the first occurrence of a value in a list, what if we are
trying to remove a value that is not in the list or remove it two times?
Remove first occurrence of a value
How do you insert an element at a specific index in a list?
Need to use insert method.
How do you get the index of the first item found matching (index by value) the
argument in a list, what if index is not found?
How do you add lists (concatenate lists)?
You can concatenate lists with + operator or with extend(l) method.
How do you check for existence in a list?
With in operator.
How do you examine the length of a list? |
Examine the length with universal “len()” method (working for any iterable).
Tuples are like lists, but they are (main property)?
But they are immutable.
How do you create a tuple of length one, zero?
Note that a tuple of length one has to have a comma after the last element but
tuples of other lengths, even zero, do not.
Can do you perform list operations (get length, concatenate, slice, existence
check) on tuples?
Yes, you can do most of the list operations on tuples too
How do you unpack tuples ((1, 2, 3)), is it possible to unpack
arbitrary-lenght tuple into few variables, nested unpacking?
You can unpack tuples (or lists) into variables
Yes we can unpack tuples into few variables, extended unpacking.
Nested unpacking is possible too.
Additional information.
What are dictionaries?
Dictionaries (hash table) store mappings from keys to values.
What are the requirements for keys in dictionaries?
Keys for dictionaries have to be immutable types. This is to ensure that
the key can be converted to a constant hash value for quick look-ups.
Immutable types include ints, floats, strings, tuples.
How do you look up values in a dictionary?
Look up values with []
How do you get all keys and values from a dictionary?
Get all keys as an iterable with “keys()“. We need to wrap the call in list() to
turn it into a list. Note - for Python versions <3.7, dictionary key ordering is
not guaranteed. Your results might not match the example below exactly. However,
as of Python 3.7, dictionary items maintain the order at which they are inserted
into the dictionary.
Get all values as an iterable with “values()“. Once again we need to wrap it
in list() to get it out of the iterable. Note - Same as above regarding key
ordering.
How do you check for existence of keys in a dictionary?
Check for existence of keys in a dictionary with “in”
Looking up a non-existing key is a KeyError: filled_dict["four"] # KeyError,
how to avoid getting a KeyError and return a default value?
Use “get()” method to avoid the KeyError
How do you insert into a dictionary only if the given key isn’t present?
Need to use "setdefault()" method:
How do you add a new value to a dictionary?
By using "update()" method or using key assignment:
How do you remove keys from a dictionary?
With del:
How do you use additional unpacking options in dictionaries?
From Python 3.5 you can also use the additional unpacking options:
What sets store?
Sets store unique values of sequences.
Similar to keys of a dictionary, elements of a set have to be (requirements)?
Immutable:
How do you add elements to a set?
By using add method.
How do you perform set operations like intersection, union, difference and
symmetric difference?
How to check if a set is a superset of another set:
How do you check for existence in a set?
By using is operator:
How do you make a copy (one layer deep copy) of a set?
3. Control Flow and Iterables
How to use control flow in Python?
What are the for loops do?
For loops iterate over lists/sequences/iterables:
What is the range function?
range(number) returns an iterable of numbers from zero up to (but excluding)
the given number, how to use it?
How do you loop over a list to retrieve both the index and the value of each
list item?
How a while loops are working?
While loops go until a condition is no longer met True, even “infinitely” if
the condition is never met.
How do you handle exceptions with a try/except block, how else and finnaly in
try/except block is working?
Handle exceptions with a try/except block
How do you clean up resources without try/finally (with closing)?
Instead of try/finally to clean up resources you can use a with statement:
How do you write to a file (string or JSON)?
Writing to a file:
How do you read from a file as string, parsed JSON into dictionary?
What is an iterable?
Python offers a fundamental abstraction called the Iterable. An iterable, is an
object that can be treated as a sequence. The object returned by the range
function, is an iterable.
How do you loop over an iterable?
We can loop over it with for loop:
How do you get the next object from an iterator, what if we grabbed all data
from iterable?
Our iterator is an object that can remember the state as we traverse through
it. We get the next object with next().
How to loop over an iterable without using next?
We can loop over it with for, in fact, “for” automatically call next for us:
How to grab all the elements of an iterable or iterator?
By call list() function:
4. Functions
How to create Python function?
Use def to create new functions:
How do you call functions with parameters, keyword arguments?
Need to pass arguments/parameters in parentheses:
How do you define functions that take a variable number of positional arguments,
keyword argmunts?
Need to use *args or **kwargs, conventional, but not strict variable names
with prefixes:
How to call function with args and kwargs from some variables (expand
tuple/dict)?
Use * to expand args (tuples) and use ** to expand kwargs (dictionaries).
How do you return multiple values from a function?
Returning multiple values is can be made with tuple assignments:
What is the difference between local and global scope, how to override variable
from global scope?
Global Scope: Variables declared outside of functions are accessible everywhere
in your program. They’re like things you’ve placed in the room, anyone can see
them.
Local Scope: Variables declared inside functions are only accessible within that
function (not really true for Python). They’re like things you’ve put in the
box, only people with the box (inside the function) can see them.
But you can “move” variable from global scope with global keyword (makes the
variable visible to everything in the module).
Does python support first-class functions?
Yes, python has first class functions
Closures captures the variables it needs from its surrounding environment,
allowing you to maintain state information in a way that’s both elegant and
efficient.
How we can modify variables out of closure function in python?
We can use the nonlocal keyword to work with variables in nested scope which
shouldn’t be declared in the inner functions.
How to use anonymous functions?
We can define anonymous functions with lambda keyword.
Is Python has built-in higher order functions?
There are built-in higher order functions
Is there alternative to maps and filters?
Yes, we can use list comprehensions for nice maps and filters
List comprehension stores the output as a list (which itself may be nested).
This structures are very “Pythonic” and can be used to make code more readable.
5. Modules
How to import module, specific function from module, all from module (not
recommended)?
How do you shorten module names while importing them?
You can shorten module names with as keyword:
What are really Python modules?
Python modules are just ordinary Python files. You can write your own, and
import them. The name of the module is the same as the name of the file.
How do you find out which functions and attributes are defined in a module?
Need to use dir() function:
What happens if you have a Python script named math.py in the same directory
as your current script?
The file math.py will be loaded instead of the built-in Python module when you
import math module. This happens because the local directory has priority over
Python’s built-in libraries.
6. Classes
What is a class, how to create it, class basic structure?
We use the “class” statement to create a class, this is some standard class
example:
When a Python interpreter reads a source file (import module) it executes all
its code. How to avoid execute some code when we import module and execute it if
we run module as a script?
Need to use __name__ variable checking, this check makes sure this code block
is only executed when this module is the main program:
How do you instantiate a class and use class methods?
How to change the class shared attribute?
With dot notation:
How do you call class static methods with or without instantiating a class?
How do you get/update/delete properties of the class instance?
Need to use dot notation:
6.1 Inheritance
What is inheritance for classes?
Inheritance allows new child classes to be defined that inherit methods and
variables from their parent class. Syntax is:
What is the super function inside __init__ method?
The super function lets you access the parent class’s methods
that are overridden by the child, in this case, the init method.
This calls the parent class constructor: super().__init__(name).
Sort of combining the parent class’s __init__ method with the child’s.
How to get the class instance “Method Resolution Order” attribute used by both
getattr() and super() and why it’s needed?
This needed to get/check the order in which classes are searched for an
attribute or method. This attribute is dynamic and can be updated:
How do you define a child Superhero class inherited from Human class?
How to import this classes?
Using the Human class as the base or parent class, we can
define a child class, Superhero, which inherits variables like “species”,
“name”, and “age”, as well as methods, like “sing” and “grunt”
from the Human class, but can also have its own unique properties.
To take advantage of modularization by file you could place the classes above
in their own files, say, human.py.
To import functions from other files use the following format
from “filename-without-extension” import “function-or-class”.
from human import Human.
6.2 Multiple Inheritance
What print(Batman.__mro__), print(sup.get_species(), print(sup.fly) will
print?
7. Advanced
Sometimes you need to get values in chunks/by one, and you also don’t want to
get all of them for example (stop iteration early). This known as lazy code,
is python supported way to do it?
Yes, Python generators help you make lazy code.
Generators are memory-efficient because they only load the data needed to
process the next value in the iterable. This allows them to perform
operations on otherwise prohibitively large value ranges.
How to create a generator comprehension?
Just as you can create a list comprehension, you can create generator
comprehensions as well.
How to cast a generator comprehension directly to a list?
Need to use list() function:
What is a decorator, how wrapper works?
Decorators are a form of syntactic sugar. They make code easier to read while
accomplishing clunky syntax. Wrappers are one type of decorator. They’re really
useful for adding logging to existing functions without needing to modify them.
Which problems with code inspection (.__name__, .__code__.co_argcount) for
decorated functions you know and how to solve them?
High-level overview
Here is high-level overview of Python language, built-in data structures, data
management, etc.