// - integer division
% - Modulo
** - exponentiation
Multiple assignment:
x += 2 is the same as x = x + 2
Same applies to *= and -=
All divisions will return a float. Can use type() to see type of variable.
Convert with int() and float()
Backslash escapes strings
+ to concat
* to repeat
lists: [1, 2, 3]
slicing a string or list: months[6:9] (from and including, to but not including)
in, not in -> membership operators
"This" in "This is a test" -> true
Tuples: Immutable, ordered: location = (12.3516, 35.2346). Parenthesis can be omitted
Tuple unpacking:
Sets - Collecting unique objects
Dictionary
Compound data structures
Syntax: if, elif, else
Here are most of the built-in objects that are considered False in Python:
None
and False
0
, 0.0
, 0j
, Decimal(0)
, Fraction(0, 1)
'""
, ()
, []
, {}
, set()
, range(0)
FOR-loops: for city in cities:
range(start, stop, step)
WHILE-loops: while condition:
BREAK to terminate a loop
CONTINUE to go to the next iteration
zip returns an iterator that combines multiple iterables into one sequence of tubles
enumerate adds indexes
list comprehension is shorthand syntax for creating lists. Can also use if/else to filter.
Define function with def function_name(arguments):
Call functions with arguments either by argument position or name
Docstrings allows to add documentation to for instance function
Lambda expressions: Anonymous functions
Iterator: Object that represents a stream of data.
Generator: Function that creates an iterator, has yield
import filename (same folder) creates an object "filename" of type "module"
import named "filename" is referred to as both a script and a module
a module is just a file with python definitions and statements
variables can be accessed with filename.variable
make an alias for imports: import some_long_filename as alias
The if main-block: use if __name__ == '__main__': to only execute code when the current file is being executed, not when it is imported. Good practice to write executable statements inside an "if name"-block. Alternatively define a main() function and run this in the "if main"-block.
Python Standard Library - ready-made modules, see docs and example code.
A package is a module that contains submodules. Example: os.path. Usage: os.path.isdir('my_path')
Import submodules with import package_name.submodule_name
Install libraries using pip: pip install pytz (a timezone package)