Over the years, the programming language which has established a reputation of ‘big name’ in Python. Python is considered a high-end programming language with a wider range of options, from web applications to data analysis. Moreover, it is thought to be a better-designed language which provides a big standard library as well as it is easier to maintain. Some of the tech giants like Instagram, YouTube, and some cloud platforms have preferred using Python.
In the year 2020, the importance and demand of Python are likely to grow even more, and there’s a possibility that it will become the most preferred programming language. If you are an IT professional from the development side, now is the time to enroll in our Python Certification to add to your armory of skills.
This cheat sheet will guide you through basic Python principles to help you prepare for the certification exam.
The Zen of Python
Tim Peters, an experienced Python professional, briefly wrote the BDFL's guiding principles for Python's design into 20 aphorisms. Out of 20, only 19 have been written down:
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! |
Learn Python at DataScienceAcademy.io with courses and certificaction preps and begin your learning journey with 7-day FREE TRIAL today!
Python Basics
Math Operators
Operators |
Operation |
Example |
** |
Exponent |
3 ** 2 = 9 |
% |
Modulus/Remainder |
32 % 6 = 2 |
// |
Integer division |
22 // 8 = 2 |
/ |
Division |
32 / 6 = 5.3 |
* |
Multiplication |
4 * 3 = 12 |
- |
Subtraction |
6 - 2 = 4 |
+ |
Addition |
5 + 4 = 9 |
Data Types
Data Type |
Examples |
Integers |
-2, -1, 0, 1, 2, 3, 4, 5 |
Floating-point numbers |
-1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25 |
Strings |
'a', 'aa', 'aaa', 'Hello!', '11 cats' |
Variables
You can give any name to a variable as long as it follows the following rules:
- It can only be a single word.
- It can only have letters, numbers, and the underscore (_) character.
- Can’t begin with a number.
- Variable names starting with an underscore (_) function are considered as "unuseful`.
Flow Control
Comparison Operators
Operators |
Meaning |
= = |
Equal to |
!= |
Not equal to |
< |
Less than |
> |
Greater Than |
<= |
Less than or Equal to |
>= |
Greater than or Equal to |
These operators are used to evaluate to True or False nature of the values you give them.
Examples:
>>> 32 = = 32 True |
>>> 32 = = 30 False |
>>> 'goat' != 'cat' True |
Boolean Evaluation
You should not use “= =” or != operator to evaluate Boolean operations. Instead, use the “is” or “is not” operators, or else use implicit Boolean evaluation.
>>> True is True True |
>>> True is not False True |
Boolean Operators
There are three Boolean operators, which include: and, or, and not.
Expression |
Evaluates |
True and True |
True |
True and False |
False |
False and True |
False |
False and False |
False |
And Operator’s Truth Table:
or Operator’s Truth Table:
Expression |
Evaluates |
True or True |
True |
True or False |
True |
False or True |
True |
False or False |
False |
not Operator’s Truth Table:
Expression |
Evaluates |
not True |
False |
not False |
True |
Functions
>>> def hello(name): >>> print('Hello {}'.format(name)) >>> >>> hello('John') >>> hello('Kim') Hello John Hello Kim |
Return Values and return Statements
While creating a function with the def statement, with a return statement, the desired return value can be specified. A return statement is made up of the following:
- The return keyword.
- The value or expression that is desired by the function to return.
Local and Global Scope
- The code used in the global scope cannot have any local variables.
- On the contrary, a local scope can access global variables.
- The code is a function’s local scope cannot use variables in any other local scope.
- The same name for different variables can be used if they are used in different scopes. For example, there can be a local variable with the name spam, and a global variable also named spam.
Exception Handling
Basic Exception Handling
>>> def spam(divideBy): >>> try: >>> return 42 / divideBy >>> except ZeroDivisionError as e: >>> print('Error: Invalid argument: {}'.format(e)) >>> >>> print(spam(2)) >>> print(spam(12)) >>> print(spam(0)) >>> print(spam(1)) 21.0 3.5 Error: Invalid argument: division by zero None 42.0 |
Start Your 7-Day FREE TRIAL with Data Science Academy.
Lists
>>> spam = ['cat', 'dog', 'lion', 'elephant']
>>> spam ['cat', 'dog', 'lion', 'elephant'] |
Individual Values in a List
>>> spam = ['cat', 'dog', 'lion', 'elephant'] >>> spam[0] 'cat'
>>> spam[1] 'dog'
>>> spam[2] 'lion'
>>> spam[3] 'elephant' |
Changing Values in a List
>>> spam = ['cat', 'dog', 'lion', 'elephant'] >>> spam[1] = 'bat'
>>> spam ['cat', 'bat', 'lion', 'elephant']
>>> spam[2] = spam[1]
>>> spam ['cat', 'bat', 'bat', 'elephant']
>>> spam[-1] = 12345
>>> spam ['cat', 'bat', 'bat', 12345] |
Using del Statements to Removing Values from Lists
>>> spam = ['cat', 'dog', 'lion', 'elephant'] >>> del spam[2] >>> spam ['cat', 'dog', 'elephant'] |
Dictionaries and Structuring Data
Dictionary Example:
myCat = {'size': 'fat', 'color': 'black', 'disposition': 'loud'} |
Keys(), Values(), and Items() Methods
Values:
>>> spam = {'color': 'red', 'age': 32} >>> for v in spam.values(): >>> print(v) red 32 |
keys():
>>> for k in spam.keys(): >>> print(k) color age |
items():
>>> for i in spam.items(): >>> print(i) ('color', 'red') ('age', 32) |
Sets
“A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.”
Source: https://docs.python.org/3/tutorial/datastructures.html
Preparing a set
There are two methods to create sets:
- using curly braces {}
- built-in function set()
>>> s = {1, 2, 3}
>>> s = set([1, 2, 3]) |
sets: defined as unordered collection of unique elements
A set automatically remove all the duplicate values
>>> s = {1, 2, 3, 2, 3, 4} >>> s {1, 2, 3, 4}>>> s = set([1, 2, 3]) |
add() and update() a set
With the use of the add() function a single element can be added to the set.
>>> s = {1, 2, 3} >>> s.add(4) >>> s {1, 2, 3, 4} |
With the use of the update() function, multiple elements can be added to the set
>>> s = {1, 2, 3} >>> s.update([4, 5, 6]) >>> s {1, 2, 3, 4, 5, 6} |
itertools Module
An itertools module is a group of tools anticipated to be quick while efficiently using memory when handling iterators.
As per the official Python 3.x document:
“The module standardizes a core set of fast, memory-efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra,” making it possible to construct specialized tools succinctly and efficiently in pure Python.”
Source: https://docs.python.org/3/library/itertools.html
The itertools module is available in the standard library, and it must be imported for use.
The operator module will be used, as well. This module is not mandatory when using itertools; however, it is needed for some of the samples below:
accumulate()
itertools.accumulate(iterable[, func]) |
Example:
>>> data = [1, 2, 3, 4, 5] >>> result = itertools.accumulate(data, operator.mul) >>> for each in result: >>> print(each) 1 2 6 24 120 |
combinations()
itertools.combinations(iterable, r) |
Example:
>>> shapes = ['circle', 'rectangle', 'square',] >>> result = itertools.combinations(shapes, 2) >>> for each in result: >>> print(each) ('circle', ' rectangle ') ('circle', 'square') (' rectangle ', 'square') |
count()
itertools.count(start=0, step=1) |
Example:
>>> for i in itertools.count(10,3): >>> print(i) >>> if i > 20: >>> break 10 13 16 19 22 |
Comprehensions
Comprehension List
>>> a = [1, 3, 5, 7, 9, 11]
>>> [i - 1 for i in a] [0, 2, 4, 6, 8, 10] |
Comprehension Set
>>> b = {"abc", "def"} >>> {s.upper() for s in b} {"ABC", "DEF} |
Comprehension Dict
>>> c = {'name': 'Pooka', 'age': 5} >>> {v: k for k, v in c.items()} {'Pooka': 'name', 5: 'age'} |
Manipulating Strings
Escape Characters
Escape character |
Prints as |
\' |
Single quote |
\" |
Double quote |
\t |
Tab |
\n |
Newline (line break) |
\\ |
Backslash |
Example:
>>> print("Hi there!\nHow are you?\nI\'m fine.") Hi there! How are you? I'm fine. |
String Formatting
String Formatting (str.format)
>>> name = 'Kim' >>> age = 25'
>>> "Hello I'm {}, my age is {}".format(name, age) "Hello, I'm Kim, my age is 25." |
>>> "Hello I'm {0}, my age is {1}".format(name, age) "Hello, I'm Kim, my age is 25." |
The official Python 3.x documentation recommends str.format instead of the % operator
“The formatting operations described here exhibit a variety of quirks that lead to several common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals or the str.format() interface helps avoid these errors. These alternatives also provide more powerful, flexible, and extensible approaches to formatting text.”
Source: https://docs.python.org/3/library/stdtypes.html?highlight=sprintf#printf-style-string-formatting
Regular Expressions
- Import the regex module with import re.
- Produce a Regex object with the re.compile() function.
- Pass the string you wish to search into the Regex object’s search() method. The string gives a Match object.
- Call the Match object’s group() method to return a string of the actual matched text.
All the Regex functions in Python are written in the re module:
>>> import re |
Handling File and Directory Paths
In Python, two types of main modules are used to deal with path manipulation:
- The path module
- The pathlib module
The pathlib module was added in Python 3.4 with a scope of offering an object-oriented method to handle file system paths.
Backslash in Windows and Forward Slash in OS X and Linux
In Windows OS, paths are written using backslashes () as the separator between folder names. In macOS, Linux, and BSDs operating systems which are Unix based, the forward-slash (/) is used as the path separator.
Joining paths can be very tricky if your code needs to work across different platforms. However, Python offers easy ways to handle this task. Some of the examples will be showcased how to deal with this with both os.path.join and pathlib.Path.joinpath
Using os.path.join on Windows:
>>> import os
>>> os.path.join('usr', 'bin', 'spam') 'usr\\bin\\spam' |
Using pathlib on Unix:
>>> from pathlib import Path
>>> print(Path('usr').joinpath('bin').joinpath('spam')) usr/bin/spam |
Reading and Writing Files
File Reading/Writing Process
To read/write to a file in Python, you will need to use the ‘with’ statement. After you are done, it will close the file.
Writing to Files
>>> with open('tomato.txt', 'w') as tomato_file: ... tomato_file.write('Hello world!\n') 13
>>> with open('tomato.txt', 'a') as tomato_file: ... tomato_file.write('Tomato is not a vegetable.') 25
>>> with open('tomato.txt') as tomato_file: ... content = tomato_file.read()
>>> print(content) Hello, world! Tomato is not a vegetable. |
JSON, YAML, and Configuration Files
JSON
Open a JSON file using:
import json with open("filename.json", "r") as f: content = json.loads(f.read()) |
Write a JSON file using:
import json
content = {"name": "Kim", "age": 25} with open("filename.json", "w") as f: f.write(json.dumps(content, indent=2)) |
YAML
As compared to JSON, YAML offers better human-controlled maintenance and enables you to add comments. It is a more convenient choice for configuring files where individuals will have to edit.
There are two main libraries permitting access to YAML files:
- PyYaml
- yaml
You can install them while using pip install on your virtual setting.
The PyYaml is easier to use; however, Ruamel, implements the YAML specification much better and enables you to modify a YAML content without changing comments.
You can open a YAML file using:
from ruamel.yaml import YAML
with open("filename.yaml") as f: yaml=YAML() yaml.load(f) |
Debugging
Raising Exceptions
Using a raise statement, you can raise exceptions. While writing the code, a raise statement must consist of the following:
- The raise keyword
- A call to the Exception() function
- A string with a supportive error message moved to the Exception() function
>>> raise Exception('This is the error message.') Traceback (most recent call last): File "<pyshell#191>", line 1, in <module> raise Exception('This is the error message.') Exception: This is the error message. |
Assertions
An assertion is defined as a rationality check to ensure that your code isn’t performing something wrong. These checks are executed through the assert statements. If the sanity check somehow fails, then an AssertionError exception is raised. While writing in the code, and assert statement consists of the following:
- The assert keyword
- A condition (an expression that evaluates to True or False)
- A comma
- A string to display when the condition is False
Check out the FREE PLAN at DataScienceAcademy.io and get free access to courses and data science certification preps.
Lambda Functions
This below function:
>>> def add(x, y): return x + y
>>> add(6, 2) 8 |
Is the equivalent of the lambda function below:
>>> add = lambda x, y: x + y >>> add(5, 3) 8 |
Ternary Conditional Operator
In different programming languages, you have a ternary operator. This operator defines a conditional expression. The most commonly used purpose is to make a brief, simple conditional assignment statement. Putting it in another way, it offers one-line code to evaluate the first expression if the condition is true, or else it evaluates the second expression.
<expression1> if <condition> else <expression2> |
Example:
>>> age = 12
>>> print('kid' if age < 18 else 'adult') kid |
Ternary operators can be chained as well:
>>> age = 15
>>> print('kid' if age < 13 else 'teenager' if age < 18 else 'adult') teenager |
args and kwargs
The terms args and kwargs are arbitrary. The important things are the * and ** operators. They can mean:
- In a function declaration, * means “pack all remaining positional arguments into a tuple named <name>,” while ** is the same for keyword arguments (except it uses a dictionary, not a tuple).
- In a function call, * means “unpack tuple or list named <name> to positional arguments at this position,” while ** is the same for keyword arguments.
For instance, you can make a function that you can use to call any other function, regardless of what parameters it has:
def forward(f, *args, **kwargs): return f(*args, **kwargs) |
Context Manager
Python's context managers are used on a wide scale. However, the purpose behind their use is understood by a few. These statements are commonly used for reading and writing files. They assist the application in supporting system memory and to improve resource management.
with statement
A context manager is defined as an object that is informed at the start and end of a context. It’s also called ‘a block of code.’ It is commonly used with the ‘with’ statement, which ensures the notifying.
For example, file objects are context managers. The file object is closed automatically when a context ends:
>>> with open(filename) as f: >>> file_contents = f.read()
# the open_file object has automatically been closed. |
__main__ Top-level script environment
__main__ is the term used for the scope in which top-level code runs. A module’s name is set equal to __main__ when it is read from a script, standard input, or from an interactive prompt.
By checking its __name__, a module can determine whether it is running in the main scope or otherwise. It permits a common phrase for conditionally executing code in a module when it is run as a script or with Python -m but not when it is imported:
>>> if __name__ == "__main__": ... # execute only if run as a script ... main() |
setup.py
Center of all activity in the building, distributing, and installing modules, the setup script works while using the Distutils. The basic function of the setup script is to describe your module distribution to the Distutils. It is done so that the different commands that operate on your modules do the exact job.
The setup.py file is the most important part of a Python project. It defines all of the metadata related to your project. To give a rich set of metadata description of the project, there are quite a few fields you can use. However, there are only three mandatory fields, which are: name, version, and packages. The name field should be unique if you are looking to publish your package on the Python Package Index (PyPI). The version field keeps a record of different releases of the project. And finally, the packages field describes the location where you’ve put the Python source code within your project.
Data classes
Data classes are python classes that are appropriate for storing data objects. This module offers a decorator and functions for adding generated special methods automatically, such as __init__() and __repr__() to user-defined classes.
Features
- They store data and represent a certain data type. Example: A number. For individuals conversant with ORMs, a model instance is a data object.
- It represents a specific kind of entity.
- It holds attributes that define or represent the entity.
- The comparison is done with the other objects of the same class. Example: A number can be greater than less than or equal to another number.
Virtual Environment
The Virtual Environment is used to test python code in controlled environments. Another usage is to avoid filling the base Python installation with libraries that are intended for only one project.
virtualenv
Install virtualenv:
pip install virtualenv |
Install virtualenvwrapper-win (Windows)
pip install virtualenvwrapper-win |
poetry
Poetry is a tool used for dependency management and packaging in Python. It allows you to announce the libraries your project depends on. It will also allow you to manage (install or update) libraries for you.
Install Poetry
pip install --user poetry |
Create a new project
poetry new my-project |
It will create the my-project directory:
my-project ├── pyproject.toml ├── README.rst ├── poetry_demo │ └── __init__.py └── tests ├── __init__.py └── test_poetry_demo.py |
For more information on Python and the benefits of learning it as a skill, connect with our experts.