Python is an interpreted high-level general-purpose computer programming language.
Category | Type |
---|---|
Text | str |
Numeric | int , float , complex |
Sequence | list , tuple , range |
Boolean | bool |
Mapping | dict |
Set | set , frozenset |
Binary | bytes , bytearray , memoryview |
None | NoneType |
Operator | Description |
---|---|
+ |
addition |
- |
subtraction |
* |
multiplication |
/ |
division |
// |
floor division |
% |
modulus |
** |
exponent |
Operator | Description |
---|---|
== |
equality |
!= |
inequality |
<> |
inequality |
> |
greater than |
< |
less than |
>= |
greater than or equal to |
<= |
less than or equal to |
Operator | Description |
---|---|
and |
logical AND |
or |
logical OR |
not |
logical NOT |
Operator | Description |
---|---|
= |
assignment |
+= |
add AND |
-= |
subtract AND |
*= |
multiply AND |
/= |
divide AND |
%= |
modulus AND |
//= |
floor division AND |
**= |
exponent AND |
Operator | Description |
---|---|
in |
true if value is found in sequence |
not in |
true if value is not found in sequence |
Built-in data structures:
A list is an ordered (indexed), mutable data structure capable of storing non-unique elements of different data types.
list = ['el1', 'el2']
Python list object methods.
A tuple is an ordered (indexed),immutable data structure capable of storing non-unique elements of different data types.
tuple = ('el1', 'el2')
A set is an unordered (non-indexed), mutable data structure capable of storing unique elements of different data types.
set = {'el1', 'el2'}
A dictionary is an unordered (non-indexed), mutable data structure capable of storing non-unique elements of different data types accessed by unique keys.
dict = {
'key1': 'value',
'key2': 'value',
}
if
statementsif a < 0:
print('Negative')
elif a > 0:
print('Positive')
else:
print('Zero')
A loop statement allows us to execute a statement or group of statement multiple times.
Type | Description |
---|---|
while |
Repeats while a given condition is true |
for |
Repeats ‘n’ number of times |
Statement | Description |
---|---|
break |
Terminates the loop |
continue |
Skips the remainder of the block but continues the loop |
pass |
Disregarded statement |
A function is a reusable block of code containing related statements that runs only when it is called.
Syntax:
def function_name(arguments):
statement(s)
The Python Standard Library built-in functions.
A lambda is a small anonymous function that can accept any number of arguments but may have only one expression.
Syntax:
lambda arguments: expression
Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made.
Syntax:
class Class
def __init__(self, arg1, arg2):
self.arg_a = arg1
self.arg_b = arg2
def method(self):
print(self.arg_a + self.arg_b)
foo_instance = Class('bar', 'baz')
foo_instance.method()
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py
appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__
.
Importing modules:
import module
module.function()
# Alias module name
import module as foo
foo.function()
# Destructure imports
from module import function
function()
Python has built-in support for TCP sockets.
import socket
# `class socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)`
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# `address` is a 2-tuple `(host, port)`
mysocket.connect(address)
urllib
is a package that collects several modules for working with URLs:
urllib.request
for opening and reading URLsurllib.error
containing the exceptions raised by urllib.requesturllib.parse
for parsing URLsurllib.robotparser
for parsing robots.txt filesBeautifulSoup is used extract information from the HTML and XML files. It provides a parse tree and the functions to navigate, search or modify this parse tree.
Virtual environments are independent groups of Python libraries. Each virtual environment has its own Python binary and can have its own independent set of installed Python packages. Packages installed for one project will not affect other projects or the operating system’s packages.
Python comes bundled with the venv
module to create virtual environments. Create a virtual environment in a project directory:
# Create an environment
python3 -m venv venv
# Activate the environment
. venv/bin/activate
# Deactivate the environment
deactivate
# Delete the environment
rm -r venv
Read the venv documentation.
A requirements file is a list of project dependencies.
pip freeze
lists the current dependencies to stdout
. Generate a requirements.txt
file by running:
pip freeze > requirements.txt
Install packages from a requirements.txt
file by running:
pip install -r requirements.txt