Python Cheat Sheet - Learn the basics of Python

Prasun Das| June 24, 2022 at 8:38 AM | 10 minutes Read


Python is a high-level programming language with dynamic binding and high-level inherent data structures. It's an object-oriented programming language with an interpreted syntax. Python stands out from other programming languages because of its simple to write and comprehend syntax, which appeals to both novices and experts. Python's broad applicability and library support enable developers to create extremely flexible and scalable software and products in the real world.

The Zen of Python: Tim Peters, a long-time Python programmer, condenses the BDFL's guiding principles for Python's design into 20 aphorisms, of which only 19 have been written down. Peters's Zen of Python was included as entry number 20 in the language's official Python Enhancement Proposals and was released into the public domain.[3] It is also included as an Easter egg in the Python interpreter, where it can be displayed by entering importthis. In the May of 2020, Barry Warsaw wrote the lyrics to the music.

We will start with the basics of python, on this cheatsheet.

Python Basics:

The Arithmetic Operators in the below table are in Lowest to Highest precedence.

The preceding operations are coded in interactive shell as follows:

Data Types:

Data Types


13, 68 , -108

“a”, “prep”, “1234”, “the hub .” 
True, False

Floating Point Numbers
16.0, -11.9, 2021.1

Variables: Variables are names for data elements that can take on one or more values throughout the execution of a program. Variables come into existence when you assign

a value to them.

Rules for naming a variable:

  1. It cannot begin with a number.
  2. It must be a single word.
  3. It must consist of letters and _ symbols only.
  4. Variables in Python which start with _ (underscore) are considered as “useless”.



hence, spam should not be used in the code for a second time.

Comments: Comments are lines of text or code in a program that the compiler ignores during execution. They are used to explain a certain line of code to the viewer. Different types of comments in python are as follows : 

  1. Inline comment

  1. Multiline comment


  1. Docstring comment:

Basic Functions:

 Standard Functions:

  1. print() function : The print() function outputs a message to the screen or a standard output device as requested. This function can print strings, integers, or any other object. Using the print() function, we can print several tokens and specify that the data be separated by different delimiters.

  1. input() function : In Python, the input() function is used to accept any type of input from the user/standard input device, which can then be processed appropriately in the program. It's an add-on to the print() function.

  1. len() function : The len() function is used find the length(number of elements) of any python container like string, list, dictionary, tuple, etc.

  1. ord() function : In Python, the ord() method returns an integer that represents the Unicode Character that was provided to it. It only accepts one character as a parameter.

Python Type Casting :

type casting can be defined as a conversion of variables of a particular datatype into some other datatype, with the guarantee that the conversion is valid.

Type casting can be of two types: 

  1. Implicit
  2. Explicit

Implicit Type Casting: Implicit type casting occurs when the Python compiler internally typecasts one variable into another type without the user's intervention.

Explicit Type Casting: When the user uses explicit type casting, the compiler is forced to transform a variable from one type to another. Different types of typecasting are :

  1.  Integer to String or Float: To typecast an integer into a string type, we use the str() method. Similarly, to typecast it into a float type, we use the float() method.
  2. Float to Integer: To typecast a float datatype into an integer datatype, we use the int() method.

Program Flow Control in Python:

The following Table gives a list of relational operators in Python along with their functions:

8. Boolean Operators in Python: boolean operations available in python are as follows:

 Conditional Statements in Python:

  1. If Statements: If statement is a condition statement that will perform some operation, if the expression given in it evaluates to true as shown below:

  1. Elif Statements:  This statement is generally used in conjunction with the if statement to add another condition which is evaluated if the condition in the if statement returns false.

  1. Else Statements:  This statement is used to perform some operation, if all the if and elif statements evaluates to be false.

Loop Statements in Python : In Python, loops are statements that allow us to repeat an operation unless a given condition is met.

For Loops: The for loop is used to iterate across iterables like as strings, tuples, lists, and so on and it is used to repeat a set of statements or a section of a program multiple times

  1. For loops with range: This loop iterates overall numbers from 0 to Limit - 1. The following example prints numbers from 0 to 4.

  1. For with range (start, stop, step): This will run the loop from start to stop - 1, with step size = step in each iteration. In the below example, the start is 2, end point is 10 while the step size given is 2. Hence it prints 2,4,6,8

  1. For with in: This is used to iterate through all of the elements of a Python container, such as a list, tuple, dictionary, and so on.

While Loops:

This iterates over all of the items in a Python container, such as a list, tuple, dictionary, and so on.

Jump Statements in Python:

Break : break statements are used to exit the current loop and allow the following statement to be executed.

Continue: the continue statement allows us to return control to the loop's beginning while skipping all lines of code below it.

Functions in Python:

Functions are used to structure and improve the readability and reusability of our code. The def keyword is used to define a function in Python. Depending on the use case, a function can return a value or not. The return statement (which has been discussed) is utilized if it has to return a value.


 Global Statement: To modify a global variable from inside a function, we use the global statement.

The value of "value" has been set to Global. We use the global keyword in conjunction with "value" to change its value to local and then print it from within the function.

Importing Modules in Python: Python contains a number of third-party libraries providing helpful tools and functions. To use these modules, we must use the import keyword to import them into our code. For example, if we wish to use the math module's features, we may import it using import math in our Python code, as seen in the example below.

If we need to perform any string manipulations, we can use the string module as the import string in python. More on this in the String Manipulation section below.

Exception Handling in Python: Exception Handling is used to handle situations in our program flow, which can inevitably crash our program and hamper its normal working. It is done in Python using try-except-finally keywords.

  1. try: The code in try section is the specific part of the code where the code will be tested for exceptions.
  2. except: Here, the cases in the original code, which can break the code, are written, and what to do in that scenario by the program.
  3. finally: The code in the finally block executes whether or not an exception has been encountered by the program.

Lists in Python: Lists are used to store multiple items in a single variable. Their usage and some functions are shown below with examples:

Accessing elements in a List: Getting the value of an element at any arbitrary index in a list is called accessing elements in a list. In Python, indexes are assigned on a 0 basis. In Python, we may also use negative indexes to retrieve elements. Negative indexes denote elements that are counted from the list's back (end).

Slicing a List: Slicing is the process of accessing a part or subset of a given list. The slicing is explained in the image below:

Changing Values in a List: We can modify the value of an element in a list by accessing it with [] and then setting it to a different value.

List Concatenation and Replication: Concatenation is the process of combining the contents of two lists into one.

Replication: List replication is the process of copying the contents of a list a finite number of times into the same or another list.

Delete values from Lists: Using the del keyword, we can remove a specific element from a list.

Looping through Lists: The below example shows how we can iterate over all the elements present in a list.

in and not in keywords: We can use the in keyword to see if a specific element is present in a Python variable.We can check if a specific element is not present in the specified Python variable, similarly to the not in keyword.

Adding Values in Lists:

  1. insert(): This function inserts an element into a particular index of a list.
  2. append(): This function appends an element at the back of a list


Sorting a List: Sorting a list entails organising the list's contents in a specific order. The sort() method is used to sort a list.

Tuples in Python: Tuples are Python entities that behave in a similar way to lists, but they have one major difference: they are immutable.

The members of the tuple are initialised by writing them with (, separated by commas).

 Type Converting between Tuples, Lists, and Strings:

Python Dictionaries: Dictionaries in Python are equivalent to Maps in C++/JAVA. They are used to store data in key-value pairs.

Printing key and values in dictionaries: To print the keys of the dictionary, use the .keys() method and to print the values, use .values() method.


Update key value in dictionary:

  1. Update Key which is not in dictionary: We can update a key value in a dictionary by accessing the key withing [] and setting it to a value.
  2. Update key value which is present in the dictionary: When a key is present in a dictionary, we can change its value in the same way that we update a key when the key is not present in the dictionary.

  1. Delete key-value pair from dictionary: Using the del keyword and the key value to be deleted contained in [, we can delete a key-value pair from a dictionary.
  2. Merging 2 dictionaries: We can merge 2 dictionaries into 1 by using the update() method.

Sets in Python:

  1. Initializing Sets: Sets are initialized using curly braces {} or set() in python. A python set is basically an unordered collection of unique values, i.e. it will automatically remove duplicate values from the set.

  1. Inserting elements in set: We can insert a single element into a set using the add function of sets. To insert multiple elements into a set, we use the update function and pass a list of elements to be inserted as parameters.

  1. Deleting elements from the set: The remove() and discard() functions can be used to remove elements from a set.

Comprehensions in Python:

  1. List Comprehensions: It is a shorter syntax to create a new list using values of an existing list.
  2. Set Comprehension: It is a shorter syntax to create a new set using values of an existing set.
  3. Dict Comprehension: It is a shorter syntax to create a new dictionary using values of an existing dictionary.

String Manipulation in Python:

  1. Escape Sequences: Escape Sequences are used to print certain characters to the output stream which carry special meaning to the language compiler.

  1. Multiline Strings: Multiline Strings are used in python through triple quotes 
  2. Strings Indexing: Strings are indexed in Python in the same manner as a list of characters is, using a 0-based indexing system. The [] operators can be used to access elements of a string at a specific index.

  1. Strings Slicing: Slicing is also done the same way as in lists.

  1. Case Conversion Functions:
  2. The upper() and lower() functions are used to convert a string of letters into uppercase or lowercase respectively.
  3. The isupper() and islower() functions are used to check if a string is in all uppercase or lowercase respectively.

Some other functions :

join() and split() Functions: The join() function joins elements of a list with a delimiter string and returns a string as the result.

split() function splits the into tokens, based on some delimiters and returns the result as a list:

String Formatting: String Formatting is done with the str.format() function.

Template Strings: When formatting strings provided by users, it is advised that you use it. They simplify the code and make it easier to grasp. Importing the Template class from the string module allows you to use them.

Date and Time: To handle date and time operations in Python, we use the datetime module.

  1. time class: We can represent time values using the time class.
  2. date class: We can represent date values using the date class.
  3. Conversion from date to time: We can convert a date to its corresponding time using the strptime() function.
  4. time.strftime() in Python: It converts a tuple or struct_time representing the time into a string object.

Debugging in Python:

Raising Exceptions with raise statement: The raise statement is used to raise exceptions and consists of 3 components:

  1. raise keyword
  2. Exception() function call
  3. Parameter of the Exception() function, which usually contains an error message.

Traceback as String

In Python, there is a method called traceback. When a raised Exception is not treated as a String type, format exc() produces the traceback presented by Python. This will necessitate the import of the Traceback Module.

Assert Statements in Python: Assert Statements/Assertions are commonly used for debugging programs and determining whether the code is executing an operation that is clearly incorrect based on the program's logic. The unique feature of assert is that when it fails, the program crashes quickly, letting us to focus our search for the fault.

The following elements are included in the creation of an assert statement:

  1. assert keyword
  2. a condition that results in a boolean value
  3. a display message for when the assertion fails
  4. a comma separating the condition and the display message.

Logging in Python:

Logging enables us to keep track of certain events that occur when software is run. It plays a critical role in software development, debugging, and running.

26. Lambda Function in Python: These are anonymous python functions that take any number of inputs but only return one expression.

considering the function which multiplies 2 numbers:

In equivalent the lamba function will be:

Ternary Operator in Python: The ternary operator is a one-liner statement that can be written as an alternative to if-else conditionals.

*args and **kwargs in Python: Using special symbols called *args and **kwargs, we can pass a variable number of arguments to a function.

  1.   *args: For non-keyword arguments,
  2. **kwargs: For keyword arguments.
#python#cheatsheet#fundamentals to learn
View Count:4.2k


Similar Articles

Busting myths about web3

WHAT IS WEB3?Web3 is the catch-all term for the vision of an upgraded version of the internet aimed at giving power back to the users. It is truly the......

Cover image


Operating Systems is one of the core subjects for a computer science student. As such a lot of important questions are asked on this subject in interv......

Cover image

Cloud Computing Cheatsheet

Getting started with cloud computing ?The words "cloud" and "web" will be interchangeable. What kind of business operates today without the internet? ...

Cover image

Software Engineering — SOFTWARE MAINTENANCE [Part-4]

SOFTWARE MAINTENANCE:Software Maintenance can be defined as the process of modifying a software product after its delivery. The main purpose of softwa...

Cover image

Software Engineering — Software Process Activities [Part - 3]

A quick summary upto what we did this far  from this series:Software EngineeringSoftware engineering is a discipline of engineering concerned wit...

Cover image

Understanding Time Complexity with Interview Examples

Introduction:Understanding time complexity of a function is imperative for every programmer to execute a program in the most efficient manner. Time co...

Cover image

Software Engineering — Software Development lifecycle and software process(Part 2)

 Software MethodologyA software methodology (which is also known as software process) is a set of related development Phases that leads to the pr...

Cover image

Software Engineering [Part 1] - Introduction

Software Engineering is a subject that requires when you are a software developer as well as when you are in your college preparing for a semester or ...

Cover image

SQL Interview Questions

Are you getting ready for your SQL developer job interview?You've come to the correct place.This tutorial will assist you in brushing up on your SQL s...

Cover image


Introduction: What is SQL?To understand SQL, we must first understand databases and database management systems (DBMS).Data is essentially a collectio...

Cover image

Computer Networking Cheatsheet (Last Minute Notes)

 Networking: Importance in real life!Using a computer for work, as well as for personal use, ha...

Cover image

Last Minute Preparation Cheat Sheet for Quantitative Aptitude

FORMULA LIST:ALGEBRA :1.Sum of first n natural numbers = n(n+1)/22.Sum of the squares of first n nat...

Cover image

Database Management System Last Minute Notes [Part - 2]

ER-DiagramWhat are ER Models ?An Entity Relationship Diagram (ERD) is a visual representation of dif...

Cover image

Database Management System Last Minute Notes [Part - 1]

What is actually DBMS?A Database Management System (DBMS) is system software used to manage the orga...

Cover image

C Cheatsheet

C CHEATSHEETINTRODUCTION:C programming language was developed by Dennis Ritchie of Bell Labs in 1972...

Cover image

C Interview Questions — 2022

C is a general purpose high-level language most popular amongst coders, it is the most compatible, e...

Cover image

C++ STL Cheat Sheet

C++ programming language has templates which basically allows functions and classes to work with gen...

Cover image


C++ was conceived in the late 1970s to overcome the limitations of C. It  is an extension of th...

Cover image

Python [Advanced] Interview Questions — 2022

Interview Questions are a great source to test your knowledge about any specific field. But remember...

Cover image

Basic Python [Core] Interview Questions for Freshers and Short Sample Answers — 2022

The most popular high-level, multipurpose programming language right now is Python.Python supports p...

Cover image

Basic Java Interview Questions for Freshers and Short Sample Answers — 2022

Interview Questions are a great source to test your knowledge about any specific field. But remember...

Cover image

Java OOP Cheat Sheet — A Quick Guide to Object-Oriented Programming in Java

Object-Oriented Programming or better known as OOPs is one of the major pillars of Java that has lev...

Cover image

Learn Java: Basics to Advanced Concepts [Java Cheatsheet]

Java is a high-level programming language known for its robustness, object-oriented nature, enhanced...

Cover image