- Applications of Python
- Characteristics of Python
- Best Python IDE’s
- Online Python Compilers or Interpreters
- Python Implementations
- Standard Data Types in Python
- Base Type
- Container Type
- Python List
- List Operations
- Python Tuples
- Python Arrays
- Python Sets
- Basic Set Operations
- Dictionary
- Python String Escape Characters
- Python String Formatting
- Example
- Output
- Example
- Output
- Python Operators
- Arithmetic Operators
- output
- Comparison Operators
- Output
- Logical Operators
- Output
- Python Identifiers and Keywords
- Identifiers Rules
- Python Keywords
- Variable Assignment
- Python I/O
- Type Conversion
- Indexing Calling in Python
- Boolean Logic in Python
- Types of Boolean
- Generator Comprehension
- Example
- Python File Handling
- Example 1
- Example 2
- Open and write into a file
- Example 3
- Open and append into a file
- Packages and Modules in Python
- Modules Name and Import
- Python Math Module
- Conditional Statement
- Ternary operator
- Example
- Loops
- Break
- Example
- Continue
- Example
- Function
- Example
- Exception Handling
- Example
- Python Class
- Magic Methods of class
- Class Private Members
- Inheritance
- Example
- Multiple Inheritance
- Basic Generic Operations on Containers
- Virtual Environment in Python
- To Sum it Up All
Python is one of the most popular programming languages and its popularity is growing more and more. One of the best things about Python is that you can use it for a wide variety of purposes, such as web development, software development, game development, etc. Here are some of the key highlights of the Python programming language:
- Python is a multi-paradigm, general-purpose, object-oriented programming language.
- It is a cross-platform programming language, which means that a Python file can run across multiple platforms or operating systems in the same way.
- It is easy to learn.
- Simple syntax and akin to pseudocode.
- Comes with the Automatic Garbage Collection feature.
- Open-source and free to use.
In this Python cheat sheet, we will cover a wide range of Python concepts that you should remember as a Python developer. Also, we have provided relevant examples to help you understand the concepts better. Now, let's start this Python cheat sheet by discussing the applications and characteristics of Python.
Applications of Python
Python is a highly versatile language and it has applications in many IT fields such as:
- Web Development (back-end)
- Desktop Applications
- Data Science
- Machine Learning
- Artificial Intelligence
Characteristics of Python
Following are the major characteristics of Python:
- Simple programming language.
- Python has the most libraries.
- Supports object-oriented programming.
- Robust and secure.
- Highly scalable.
- Uses interpreter.
- Dynamic programming language.
- Supports multi-threading.
Best Python IDE’s
There are many IDEs available for Python, however, the following ones are the most recommended:
- PyCharm (By Jetbrains)
- Atom (Powered by GitHub)
- Visual Studio Code (By Microsoft)
- Spyder
- Jupyter Notebook
Online Python Compilers or Interpreters
We can use online Python compilers or interpreters to run a Python source code on any device without installing the Python. Following is a list of the best online Python compilers:
- OnlineGDB
- Replit
- Ideone
- JDoodle
Python Implementations
The most widely used Python3 offered by python.org is CPython, which is written in the C programming language. Apart from CPython, there are many other implementations of Python, such as the ones listed below:
- IronPython (Runs on .NET)
- Jython (Runs on Java Virtual Machine)
- PyPy
- Stackless Python (CPython Branch that supports micro threads )
- MicroPython (Runs on Micro Controller)
Standard Data Types in Python
Python has two data types:
- Base Type
- Container Type
Base Type
Data Type Name | Data Type Syntax | Size |
Integer Number | int | 14 |
Floating Point Numbers | float | 16 |
Boolean | bool | 14 |
string | str | 26 |
bytes | b | 21 |
Examples
Container Type
Data Type Name | Data Type Syntax | Example |
List (Ordered) | list() |
[1,2,3] or list(range(1,4))
|
Tuple (Ordered) | tuple() |
(1,2,3)
|
Dictionary (Unordered) | dict() |
{0:1, 1:2, 2:3}
|
Set (unordered) | set() |
{1,2,3}
|
Examples
Python List
A list is a collection of different data types, and it stores all elements in a contagious memory location.
- Create a list
To create a list we use square brackets [ ].
Example:
- Indexing
Python lists support indexing. With the help of indexing, we can access a specific element of a list.
Example:
- List Slicing
With list slicing, we can access a sequence of elements present in a list.
Example:
- List Unpacking
- Loop through a List
- Add Elements in a list
- Remove Elements from a list
- If condition with a list
- List Comprehension
- Condition inside a list comprehension
- Zip function to combine two lists
- Map and Filter on a list
List Operations
Operation | Description |
lst.append(val) | Add items at the end |
lst.extend(seq) | Add sequence at the end |
lst.insert(indx,val) | Add value at a specific index |
lst.remove(val) | To delete the specific value from a list |
lst.pop() | To remove the last value from the list |
Lst.sort() | To sort the list |
Python Tuples
A tuple in Python is similar to a list. However, the only difference between a tuple and a list is that tuples are immutable.
- Create a tuple
- Convert a list into a tuple
- Indexing In tuple
Python Arrays
Python does not have inbuilt support for arrays, but it has a standard library for the array data structure.
- Create an Array
Python Sets
A Python set is similar to a set in mathematics. Also, a Python set does not hold duplicate items and we can perform the basic set operations on set data types.
- Create a Set
Basic Set Operations
Operation Name | Operator | Example |
Union | | | s1 | s2 |
Intersection | & | s1 & s2 |
Difference | - | s1 - s2 |
Asymmetric Difference | ^ | s1 ^ s2 |
Dictionary
A dictionary is a collection of key-value pairs , and the key could only be an immutable data type.
- Create a dictionary
- Convert a list into a dictionary
- Accessing Dictionary Elements
We use a key to access its corresponding value in the dictionary.
- Looping through a dictionary
Python String Escape Characters
An Escape character allows us to insert illegal characters in a string, such as a tab, single quote inside a single quote string, etc.
Escape character | Prints as |
\' | Single quote |
\" | Double quote |
\t | Tab (4 spaces) |
\n | Newline |
\\ | Backslash |
Python String Formatting
With string formating, we can put variables data value inside strings.
- String formatting using f prefix
The latest versions of Python support string formating using the f prefix.
Example
Output
The value of a is 2 and the value of b is 3
- String formatting using format method
The string object also supports the format method to format a string value.
Example
Output
Python Operators
Arithmetic Operators
There are various arithmetic operators in Python that are listed in the table below:
Operator Name | Operator | Example |
Addition or concatenation | + |
1+2 #3
|
Subtraction | – |
40 – 10 #30
|
Multiplication | * |
40 * 10 #400
|
division | / |
10/5 #2.0
|
Floor division | // |
10 // 5 #2
|
Modulo | % |
10 % 5 #0
|
Exponential | ** |
2**3 #8
|
Example
output
Comparison Operators
There are several operators in Python that you can use to compare two objects or values and return a Boolean value, i.e. True or False:
Operator Name | Operator | Example |
Smaller than | < |
2 < 3 #True
|
Greater than | > |
3 > 2 #True
|
Smaller than and equal to | <= |
2 <= 2 #True
|
Greater than and equal to | >= |
3 >= 3 #True
|
Not equal to | != |
2 != 3 #True
|
Equal to comparison | == |
2 ==2 #True
|
Examples
Output
Logical Operators
Python has three logical operators:
- and (returns True if and only if both the conditions are True)
- or (returns True if either of the conditions is True)
- not (returns True if the condition is False and vice versa)
Examples
Output
Python Identifiers and Keywords
An identifier is a name given to an object. Identifiers are also known as variable names. There are some rules associated with an identifier or variable name. By using identifiers, we can give a name to variables, functions, modules, and classes.
Identifiers Rules
- The first letter of an identifier could be a lowercase or uppercase alphabet or _ (underscore symbol), and it could be followed by any alphabet, digit (0,9) and _.
- There should be no special symbol in an identifier except _ (underscore).
- You cannot use reserved Python keywords as identifiers.
Python Keywords
Keywords are the reserved names in Python, and there are a total of 33 keywords in Python 3 that are listed below:
False | else | import | pass | |
None | break | except | in | raise |
True | class | finally | is | return |
and | continue | for | lambda | try |
as | def | from | nonlocal | while |
assert | del | global | not | with |
elif | if | or | yield |
Variable Assignment
We use the equal to "=" symbol to assign an object to an identifier. The identifier name should be on the left side and the value on the right side of the assignment operator.
Example
x =20
Python Assignment | Assignment Operator | Example |
Simple and Single Assignment | = |
x = 20
|
Assignment to the same value | = |
x = y = z =100
|
Multiple Assignment | = |
x, y, z = 10, 20, 30
|
Swap values with the Assignment operator | = |
x, y = y, x
|
Unpacking sequence using Assignment operator | = |
x, *y = [20,10,30,70]
|
Assignment operator for increment | += |
x+=20
|
Assignment operator for Decrement | -= |
x -=20
|
Python I/O
I/O Method | Description |
print() | To print out the output |
input() | To take input from the user |
Example
By default input() accepts a value as a string.
Type Conversion
There are many reserved keywords in Python you can use to convert the data type of a variable.
Type Conversion | Python Syntax | Example |
Float to integer Numeric string to integer Boolean to integer | int() |
int(20.11)
int("200")
int(True)
|
Integer to float Numeric string to float Boolean to float | float() |
float(100)
float("100.6")
float(True)
|
Integer to string float to string Boolean to string | str() |
str(100)
str(100.00)
str(True)
|
ASCII Code to character | chr() |
chr(64) # @
|
Character to ASCII code | ord() |
ord('@') # 64
|
Convert a container data type and a string to a list | list() |
list('Hello') #['Hello']
|
Convert a container datatype to a dict | dict() |
dict([(1,2), (2,3)]) #{1:2, 2:3}
|
Convert a container data type to a set | set() |
set([1,2,3,4,5,5]) #{1,2,3,4}
|
Indexing Calling in Python
In Python, string, list, and tuple objects support indexing calling. An index is an integer number. Indexes of the items within an object are available from
0
to
n-1
, where
n
is the total number of items or characters present in the object.
Example:
Boolean Logic in Python
In Python, we often encounter Boolean values when we deal with comparison operators and conditional statements.
Types of Boolean
There are two types of Boolean values:
- True
- False
Boolean Operator | Description | Example |
False | In Python, False, 0, empty container data type, and None are treated as Boolean False. |
bool(0) # False
bool([]) # False
bool({}) # False
bool(None) # False
|
True | Anything except 0, None, and empty data type in Python are considered as Boolean True. |
bool(100) # True
|
Generator Comprehension
Like a list comprehension, we have generator comprehension for which we use parenthesis () instead of square brackets [].
Example
Python File Handling
To read or write data to a file, we can use the Python context manager
with
keyword. By using the
with
keyword and open function, we can open a file in different modes mentioned in the table below:
Mode | Description |
r | Read mode |
r+ | Read and Write mode |
w | Write mode |
w+ | Write and Read mode |
rb | Read in binary mode |
rb+ | Read and write in binary mode |
wb | Write in binary mode |
wb+ | Write and read in binary mode |
a | Append mode |
ab | Append in binary mode |
a+ | Append and read mode |
ab+ | Append and read in binary mode |
x | Exclusive creation of file mode. |
Example 1
To open and read from a file
Example 2
Open and write into a file
Example 3
Open and append into a file
Packages and Modules in Python
A package in Python is a collection of multiple Python modules. On the other hand, a Python module is a Python file that contains source code. To define a Python package, we have to create an empty
__ini__.py
file in the package directory. To use the modules from different packages, we have to import them into our script using
from
and
import
keywords.
Modules Name and Import
Purpose | Syntax |
To Import the complete module |
import module
|
To Import a complete module with all its objects |
from module import *
|
Import specific objects or classes from a module |
from module import name_1, name_2
|
Import modules from a package |
from package_name import module
|
Python Math Module
Math is the most important and widely used standard module of Python. It provides many methods related to mathematical operations.
Math Module | E xample |
|
|
cos()
|
cos(90)
-0.4480736161291701
|
sin()
|
sin(200)
-0.8732972972139946
|
pi
|
3.141592653589793
|
pow()
|
pow(2,3) # 8.0
|
ceil()
|
ceil(12.1) #13
|
floor()
|
floor(12.9) #12
|
round()
|
round(12.131,2) #12.13
|
abs()
|
abs(-29)
# 29
|
Conditional Statement
A conditional statement in Python consists of 3 keywords - if, elif, and else.
Example
Ternary operator
Python Ternary operator is a shorthand to write the conditional statement as a single line of code.
Example
Loops
There are two loops statements available in Python:
- for loop
- while loop
Example
#for loop
#while loop
Break
It is a statement used inside the loop statement to terminate the loop flow and exit from the loop immediately.
Example
Continue
Continue is the opposite of break, and it is used in loop statements to directly jump to the next iteration.
Example
Function
To create a user-defined function in Python, we use the def keyword. Also, to exit from a function, we return a value using the return keyword.
Example
Exception Handling
With exception handling, we deal with runtime errors. There are many keywords associated with exception handling, such as the ones mentioned in the following table:
Keyword | Description |
try | Normal processing block |
except | Error processing block |
finally | Final block executes for both tries or except. |
raise | To throw an error with a user-defined message. |
Example
Python Class
Classes enable Python to make use of object-oriented programming concepts.
- Create a class
- Create a constructor for a class:
The constructor is a special method of classes that gets executed automatically during the object creation of a class.
Magic Methods of class
Magic Method | Description |
__str__() | String representation of the object |
__init__() | Initialization or Constructor of the class |
__add__() | To override addition operator |
__eq__() | To override equal to method |
__lt__() | To override less than operator |
Class Private Members
Conventionally, to declare a private attribute, we write its name starting with __ (double underscore). Example
Inheritance
With inheritance, we can use the methods and properties of another class:
Example
Multiple Inheritance
Basic Generic Operations on Containers
Operator | Description |
len(lst) | Item count |
min(lst) | To find the minimum item |
max(lst) | To find the maximum item |
sorted(lst) | List sorted copy |
enumerate (c) | Iterator on (index, item) |
zip(lst_1,lst_2) | Combine two list |
all(c) | If all items are True it returns True else false |
any(c) | True at least one item of c is true else false |
Virtual Environment in Python
A Python virtual environment creates an isolated environment for a project where we can install and uninstall packages, frameworks, and libraries without affecting the actual Python environment. To create a Python environment, we can use the built-in Python
venv
module.
The above terminal command will generate a new virtual environment in the directory myProject . After creating the virtual environment, we need to activate it. The activation script of the virtual environment exists inside the virtual environment's Script directory.
The above command will activate the newly created virtual environment in the
myProject
directory. To deactivate the environment, we can simply execute the
deactivate
command on the terminal or command prompt.
To Sum it Up All
We hope that this comprehensive Python Cheat Sheet will help you learn various important concepts in Python. Also, with this cheat sheet, you can easily go through the important aspects of Python that are essential for writing Python code. If you have any suggestions or queries related to this Python cheat sheet, you can share them with us in the comments section below.
People are also reading:
Leave a Comment on this Post