- Variables
- Variable Name
- Assignment
- References
- Comments
- Single Line
- Multiline
- Console I/O
- Input
- Flow Control
- Condition
- Loop
- Pass
- Pattern Matching
- Exceptions
- Exception Raising
- Exception Handling
- Manual Program Termination
- Assertions
- Functions
- Parameters
- Return Values
- Variable Scope
- Decorators
- Anonymous Functions
- Modules
- Logging
- Only be one word with no spaces.
- Only contain letters, numbers, and the underscore character.
- Only begin with something other than a number.
An assignment statement with an operator = stores values in variables.
Multiple assignment is supported using , to separate variable names and values.
Conditional assignment is supported using if and else with the condition in between and values ahead and behind.
Variables do not directly store values. Instead, they store references to computer memory locations where the values are stored.
Object identity
This reference, i.e. the identity of memory locations, can be obtained by id() function.
Shallow and deep copy
In contrast with C, where each variable occupy certain memory space,
Normally variable assignment in python are through copying the reference. Thus when modifying mutable values, every variable will be affected.
To avoid this behavior, use copy.copy() in the copy module to make a duplicate copy of a mutable value, or copy.deepcopy() for inner mutable values as well.
Garbage collection
- The memory consumption of an object in bytes can be retrieved through
sys.getsizeof(object). - The reference count of the object can be retrieved through
sys.getrefcount(object).
An object with with a reference count of 0 will get cleaned up by the Python garbage collector.
Use del statements to manually delete objects (recursively).
Any text for the rest of the line following a hash mark # is part of a comment and will be ignored by Python interpretor during executions.
Multiline strings are often used for comments that span multiple lines.
print(object, sep=' ', end='\n', file=sys.stdout, flush=False) prints the object to where the file parameter points at and returns None.
Multiple objects (possibly of different types) can be printed if they are listed together as multiple arguments.
input(prompt) prints the prompt to standard output and returns the content from standard input as a string.
An if statement executes when its conditional expression is evaluated as True.
It consists of the following:
- The
ifkeyword - A conditional expression
- A colon
- An indented block of code (the
ifclause)
An elif statement executes when the last previous if or elif statement is conditioned as False, and its conditional expression is evaluated as True.
It consists of the following:
- The
elifkeyword - A conditional expression
- A colon
- An indented block of code (the
elifclause)
An else statement executes when the last previous if or elif statement is conditioned as False.
It consists of the following:
- The
elsekeyword - A colon
- An indented block of code (the
elseclause)
A while statement executes repeatedly as long as its conditional expression is evaluated as True.
It consists of the following:
- The
whilekeyword - A conditional expression
- A colon
- An indented block of code (the
whileclause)
A for statement iterates over a sequence, executes once at each step of iteration, and exits after the iteration finishes.
It consists of the following:
- The
forkeyword - An iterative expression
- A colon
- An indented block of code (the
forclause)
A break statement causes the execution to immediately exit the loop.
A continue statement causes the execution to immediately jump back to the start of the loop and reevaluate the conditional expression.
An else statement that follows a loop executes when the loop exits normally (i.e. not caused by a break statement).
A pass statement is a null statement. pass is not ignored by the interpreter. However, nothing happens when it is executed.
A match statement takes an expression and compares its value to successive patterns given as one or more case blocks; only the first pattern that matches gets executed, and none executed if no matches.
It consists of the following:
- The
matchkeyword - An evaluable expression
- A colon
- An indented block of code with one or more
caseclauses, each with code to be executed when the pattern is matched
Literals in the case statement can be combined by | to form a single pattern; _ or any identifier acts as a wildcard that always matches.
Errors detected during execution are called exceptions (in contrast with syntax errors).
A raise statement allows the programmer to force a specified exception to occur.
A try statement can be used to handle selected exceptions. It can have 4 types of clauses:
- The code that could potentially casue an error is put in the
tryclause. - The program execution moves to the corresponding
exceptclause if an error happens. - An optional
elseclause following allexceptclauses will be executed if the try clause does not raise an exception. - An optional
finallyclause will be unconditionally executed as the last task before thetrystatement completes.
If an exception occurs which does not match any exception named in the except clauses, it is passed on to outer try statements.
A raise statement inside an except clause re-raise the handled exception.
sys.exit(arg=0) specifically raises a SystemExit exception, signaling an intention to exit the interpreter.
An assertion is a sanity check performed by assert statements. If the check fails, an AssertionError is raised. It consists of the following:
- The
assertkeyword - A conditional expression
- A comma
- A string to display when the condition is False and the exception raised
A function returns a value based on the given arguments with potentially generated side effects.
A def statement indicates a function definition.
It consists of the following:
- The
defkeyword - The function name
- Parameters of the function in a pair of round brackets, with positional parameters in front of keyword parameters
- A colon
- An indented block of code (the function body)
Values passed to a function during the function call are called arguments, identified by either position or keyword. Parameters are variables that contain arguments.
Arguments can be variable in length by adding * for positional arguments and ** for keyword arguments.
Arguments in place of *args will be combined to a tuple-like object and **kwargs to a dict-like object.
In general, the value that a function call evaluates to is called the return value of the function (Sweigart, 2015).
A return statement specify the return value of a function.
It consists of the following:
- The
returnkeyword - The value or expression that the function should return
Multiple values can be returned if listed together, separated by ,.
Normally, global variables can be read from a local scope, but local variables cannot be used in the global scope or other local scopes.
In a local scope, whenever a variable is to be written (at the left side of = sign), it will be initialized and treated as a local variable.
A global statement can change the default behavior and make local assignments directly refer to the global variable. No local variable will be initialized then.
A function decorator is a special function that wraps another function. It takes a function as the only argument, and completes tasks based on the supplied function.
If a decorator requires other arguments, define an outer function that handles the arguments to the decorator and returns the decorator.
import functools
def converter(default=None):
def decorator(func):
@functools.wraps(func)
def wrapper(value):
try:
result = func(value)
return result
except (ValueError, TypeError):
return default
return wrapper
return decoratorfunctools.wraps(wrapped) is a decorator that helps keep the information of the original function.
To use a decorator, decorate a function during its definition by
@converter(default=0)
def integer(value):
return int(value)Or decorate an already defined function by
Int = converter(default=0)(int)An anonymous function is a function that is defined without a name by lambda keyword in the form of lambda arguments: expression.
A lambda function can have any number of arguments but only one expression, which is evaluated and returned.
Each python program is a module. Usually the module name is just the file name omitting the .py suffix.
To use a module:
-
Import the module through
import module.- The module namespace must then be stated in a invocation, likely
module.function(). - Optional
asfollowing an imported module bounds the module a new name. - Multiple modules can be imported together with their names separated by
,.
- The module namespace must then be stated in a invocation, likely
-
Import specific variables, functions or classes from the module through
from module import identifier.- The identifier can then be called without namespace.
- Optional
asfollowing an imported identifier bounds the identifier a new name. - Multiple identifiers can be imported together with their names separated by
,, and*represents everything.
The logging module makes it easy to create a record of custom messages.
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('Test of debug msg')
logging.info('Test of info msg')
logging.warning('Test of warning msg')
logging.error('Test of error msg')
logging.critical('Test of critical msg')
logging.disable(logging.CRITICAL)logging.basicConfig(*, level, format, filename=None, filemode='a')does basic configuration for the logging system.logging.disable(level=CRITICAL)suppress all log messages at that level or lower.
| Level | Numeric value | Description |
|---|---|---|
| logging.CRITICAL | 50 | The lowest level. Used for small details. |
| logging.ERROR | 40 | Used to record information on general events or confirm that things are working at their point. |
| logging.WARNING | 30 | Used to indicate a potential problem that might prevent the program from working in the future. |
| logging.INFO | 20 | Used to record an error that causes the program to fail to do something. |
| logging.DEBUG | 10 | The highest level. Used to indicate a fatal error that causes the program to stop running entirely. |
Base convertion
def base_convert(num, base1, base2):
'''
Converts numbers in base 1 to base 2.
'''
if base2 == base1:
return num
elif num == 0:
return 0
else:
return num % base2 + base_convert(num // base2, base1, base2) * base1Ordinal
def ordinal(num):
'''
Converts numbers to ordinals.
'''
if type(num) != int:
raise TypeError("ordinal() arg must be int")
elif num < 0:
raise ValueError("no ordinals for negative integers")
elif num // 10 % 10 != 1 and 0 < num % 10 < 4:
suffix = {1:'st', 2:'nd', 3:'rd'}[num % 10]
else:
suffix = 'th'
return str(num) + suffixSweigart, A. (2015). Automate the Boring Stuff With Python: Practical Programming for Total Beginners. San Francisco, CA: No Starch Press.

