Python Cheat-Sheet: Your Quick Reference Guide

Python Cheat-Sheet: Your Quick Reference Guide

Arif sardar

Published on 23rd Jul, 2023

25 min read

Welcome to our comprehensive Python Cheat Sheet, designed to be your go-to quick reference guide for mastering Python programming. Whether you're a seasoned developer or just starting your coding journey, having a cheat sheet at your fingertips can significantly boost your productivity and efficiency.

Python is a versatile and powerful programming language known for its readability and ease of use. It's widely used in web development, data analysis, artificial intelligence, automation, and many other domains. With Python's extensive libraries and straightforward syntax, learning and using Python has never been more accessible.

In this blog, we have compiled a concise yet comprehensive Python Cheat Sheet, covering essential concepts, functions, and tips that every Python developer should know. From basic data types and control flow to advanced topics like object-oriented programming and file handling, this cheat sheet has you covered.

Whether you need a quick reminder of Python's syntax, a refresher on how to use lists and dictionaries effectively, or guidance on handling exceptions, our cheat sheet has it all. We've also included essential Python libraries and their usage to help you harness the power of Python's ecosystem.

Mastering Basic Syntaxes

Welcome to the Python Cheat Sheet dedicated to mastering the fundamental syntax of Python programming. Understanding the basic syntax is the first step towards becoming proficient in Python. In this section, we will cover essential Python syntax elements, from variables and data types to control structures and functions. Whether you're a beginner or need a quick refresher, this cheat sheet will serve as your invaluable companion in navigating the world of Python programming. Let's dive in and uncover the building blocks of this versatile and powerful language!

Python Syntax compared to other programming languages

  1. Python was designed for readability, and has some similarities to the English language with influence from mathematics.
  2. Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
  3. Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly brackets for this purpose.

Variables

Variables are containers for storing data values. Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

Variables do not need to be declared with any particular type and can even change type after they have been set.

Python allows you to assign values to multiple variables in one line.

Output Variables

The Python print statement is often used to output variables.

Global Variables

Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.

The global Keyword

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

Comments

Python has commenting capability for byte arrayin-code documentation. Comments start with a #, and Python will render the rest of the line as a comment:

Built-in Data Types

In programming, data type is an important concept. Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Getting the Data Type

You can get the data type of any object by using the type() function:

Here arethe  some example datatypes and their uses:

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

Type Conversion

You can convert from one type to another with the int(), float(), and complex() methods:

Python Operators

Operators are used to perform operations on variables and values. Python divides the operators into the following groups:

  1. Arithmetic operators
  2. Assignment operators
  3. Comparison operators
  4. Logical operators
  5. Identity operators
  6. Membership operators
  7. Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Python Assignment Operators

Assignment operators are used to assign values to variables:

Python Comparison Operators

Comparison operators are used to compare two values:

Python Logical Operators

Logical operators are used to combine conditional statements:

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Strings

We can define strings using single (‘ ‘) or double (“ “) quotes. To define a multi-line string, we surround our string with tripe quotes (“””).

We can get individual characters in a string using square brackets []. We can slice a string using a similar notation.

We can use formatted strings to insert values into our strings dynamically:

String Methods

To check if a string contains a character (or a sequence of characters), we use the in operator:

Escape Sequence

An escape sequence is a sequence of characters; it doesn't represent itself (but is translated into another character) when used inside a string literal or character. Some of the escape sequence characters are as follows:

Python Collections (Arrays)

There are four collection data types in the Python programming language:

  • **List** is a collection that is ordered and changeable. Allows duplicate members.
  • **Tuple** is a collection that is ordered and unchangeable. Allows duplicate members.
  • **Set** is a collection that is unordered and unindexed. No duplicate members.
  • **Dictionary** is a collection that is unordered, changeable and indexed. No duplicate members.

1. List

A List in Python represents a list of comma-separated values of any data type between square brackets.

Note: These elements can be of different datatypes.

Indexing: The position of every element placed in the string starts from the 0th position and step by step it ends at length-1 position.

The list is ordered, indexed, mutable and the most flexible and dynamic collection of elements in Python.

List Methods

2. Tuples

Tuples are represented as comma-separated values of any data type within parentheses.

Note: These elements can be of different datatypes

Indexing: The position of every element placed in the string starts from the 0th position and step by step it ends at length-1 position

Tuples are ordered, indexing, immutable and the most secured collection of elements.

Tuple Methodes

3. Sets

A set is a collection of multiple values which is both unordered and unindexed. It is written in curly brackets.

Set is an unordered, immutable,non-indexed type of collection. Duplicate elements are not allowed in sets.

Set Methods

4. Dictionaries

The dictionary is an unordered set of comma-separated key: value pairs, within , with the requirement that within a dictionary, no two keys can be the same.

A dictionary is an ordered and mutable collection of elements. The dictionary allows duplicate values but not duplicate keys.

Dictionary Methods

Python Conditions

The if, elif and else statements are the conditional statements in Python, and these implement selection constructs (decision constructs).

1. if Statement

2. if-else Statement

3. if-elif Statement

4. Nested if-else Statement

Python Loops

A loop or iteration statement repeatedly executes a statement, known as the loop body, until the controlling expression is false (0). Python has two primitive loop commands:

1. For Loop

The for loop of Python is designed to process the items of any sequence, such as a list or a string, one by one.

This is less like the keyword in other programming languages and works more like an iterator method as found in other object-orientated programming languages.

2. While Loop

A while loop is a conditional loop that will repeat the instructions within itself as long as a conditional remains true.

Break Statement

The break statement enables a program to skip over a part of the code. A break statement terminates the very loop it lies within.

Continue Statement

The continue statement skips the rest of the loop statements and causes the next iteration to occur.

Functions

A function is a block of code that performs a specific task when it is called. You can pass parameters into a function. It helps us to make our code more organized and manageable. A function can return data as a result.

Function Definition:

The “def” keyword is used before defining the function.

Function Call:

Parameters / Arguments:

Whenever we need that block of code in our program simply call that function name whenever needed. If parameters are passed during defying the function we have to pass the parameters while calling that function. example-

If you try to call the function with 1 or 3 arguments, you will get an error:

Arbitrary Arguments, *args

If you do not know how many arguments will be passed into your function, add a * before the parameter name in the function definition. This way the function will receive a tuple of arguments and can access the items accordingly:

Keyword Arguments

You can also send arguments with the key = value syntax. This way the order of the arguments does not matter.

Arbitrary Keyword Arguments, **kwargs 

If you do not know how many keyword arguments will be passed into your function, add two asterisk: ** before the parameter name in the function definition.

This way the function will receive a dictionary of arguments and can access the items accordingly. This way the order of the arguments does not matter.

Default Parameter Value

The following example shows how to use a default parameter value. If we call the function without argument, it uses the default value:

Return Values

To let a function return a value, use the return statement:

The pass Statement

Function definitions cannot be empty, but if you for some reason have a function definition with no content, put it in the pass statement to avoid getting an error.

Recursion

Python also accepts function recursion, which means a defined function can call itself.

Recursion is a common mathematical and programming concept. It means that a function calls itself**. This has the benefit of meaning that you can loop through data to reach a result.**

The developer should be very careful with recursion as it can be quite easy to slip into writing a function that never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically elegant approach to programming.

File Handling

File handling refers to reading or writing data from files. Python provides some functions that allow us to manipulate data in the files.

open() function

modes-

  1. r - to read the content from the file.
  2. w - to write the content into a file.
  3. a - to append the existing content to the file.
  4. r+:  To read and write data into the file. The previous data in the file will be overridden.
  5. w+: To write and read data. It will override existing data.
  6. a+: To append and read data from the file. It won’t override existing data.

close() function

read() function

The read functions contain different methods, read(), readline() and readlines()

write() function

This function writes a sequence of strings to the file.

Exception Handling

An exception is an unusual condition that results in an interruption in the flow of a program.

1. try and except

A basic try-catch block in Python. When the try block throws an error, the control goes to the except block.

2. else

else a block is executed if the try block has not raised any exceptions and the code had been running successfully.

3. finally

Finally, the block will be executed even if the try block of code has been running successfully or the except block of code is been executed. finally, a block of code will be executed compulsorily.

Object Oriented Programming (OOPS)

It is a programming approach that primarily focuses on using objects and classes. The objects can be any real-world entities.

1. class

The syntax for writing a class in Python.

2. Creating an object

Instantiating an object can be done as follows:

3. self parameter

The self-parameter is the first parameter of any function present in the class. It can be of a different name but this parameter is a must while defining any function into class as it is used to access other data members of the class.

4. class with a constructor

Constructor is the special function of the class which is used to initialize the objects. The syntax for writing a class with the constructor in Python.

5. Inheritance in Python

By using inheritance, we can create a class that uses all the properties and behaviour of another class. The new class is known as a derived class or child class, and the one whose properties are acquired is known as a base class or parent class.

It provides the re-usability of the code.

6. Types of inheritance-

  • Single inheritance
  • Multiple inheritance
  • Multilevel inheritance
  • Hierarchical inheritance

7. filter function

The filter function allows you to process an iterable and extract those items that satisfy a given condition.

8. issubclass function

Used to find whether a class is a subclass of a given class or not as follows:

Iterators and Generators

Here are some of the advanced topics of the Python programming language like iterators and generators

1. Iterator

Used to create an iterator over an iterable

2. Generator

Used to generate values on the fly

Decorators

Decorators are used to modify the behaviour of a function or a class. They are usually called before the definition of a function you want to decorate.

1. property Decorator (getter)

2. setter Decorator

It is used to set the property 'name'

3. deleter Decorator

It is used to delete the property 'name'

Arif Sardar

Building, learning, and sharing—one line at a time.

Stay updated with my latest content!
Subscribe to my free newsletter by entering your email:

© 2024 Arif Sardar. All Rights Reserved.

Version 4. Powered by Next.JS. Made in India.