DEV Community

Cover image for The Ultimate Python Cheatsheet
Abhiraj Bhowmick
Abhiraj Bhowmick

Posted on • Originally published at abhirajb.hashnode.dev

The Ultimate Python Cheatsheet

The Ultimate Python CheatSheet

Basics
Basic syntax from the python programming language

Showing Output To User
the print function is used to display or print output

print("Content that you wanna print on screen")
Enter fullscreen mode Exit fullscreen mode

Taking Input From User
the input function is used to take input from the user

var1 = input("Enter your name: ")
Enter fullscreen mode Exit fullscreen mode

Empty List
This method allows you to create an empty list

my_list = []
Enter fullscreen mode Exit fullscreen mode

Empty Dictionary
By putting two curly braces, you can create a blank dictionary

my_dict = {}
Enter fullscreen mode Exit fullscreen mode

Range Function
range function returns a sequence of numbers, eg, numbers starting from 0 to n-1 for range(0, n)

range(int_value)
Enter fullscreen mode Exit fullscreen mode

Comments
Comments are used to make the code more understandable for programmers, and they are not executed by compiler or interpreter.

Single line comment

#This is a single line comment
Enter fullscreen mode Exit fullscreen mode

Multi-line comment

'''This is a
multi-line
comment'''
Enter fullscreen mode Exit fullscreen mode

Escape Sequence
An escape sequence is a sequence of characters; it doesn't represent itself when used inside string literal or character.

Newline
Newline Character

\n
Enter fullscreen mode Exit fullscreen mode

Backslash
It adds a backslash

\\
Enter fullscreen mode Exit fullscreen mode

Single Quote
It adds a single quotation mark

\'
Enter fullscreen mode Exit fullscreen mode

Tab
It gives a tab space

\t
Enter fullscreen mode Exit fullscreen mode

Backspace
It adds a backspace

\b
Enter fullscreen mode Exit fullscreen mode

Octal value
It represents the value of an octal number

\ooo
Enter fullscreen mode Exit fullscreen mode

Hex value
It represents the value of a hex number

\xhh
Enter fullscreen mode Exit fullscreen mode

Carriage Return
Carriage return or \r is a unique feature of Python. \r will just work as you have shifted your cursor to the beginning of the string or line.

\r
Enter fullscreen mode Exit fullscreen mode

Strings
Python string is a sequence of characters, and each character can be individually accessed. Using its index.

String
You can create Strings by enclosing text in both forms of quotes - single quotes or double-quotes.

variable_name = "String Data"
Enter fullscreen mode Exit fullscreen mode

Slicing
Slicing refers to obtaining a sub-string from the given string.

var_name[n : m]
Enter fullscreen mode Exit fullscreen mode

String Methods isalnum() method
Returns True if all characters in the string are alphanumeric

string_variable.isalnum()
Enter fullscreen mode Exit fullscreen mode

isalpha() method
Returns True if all characters in the string are alphabet

string_variable.isalpha()
Enter fullscreen mode Exit fullscreen mode

isdecimal() method
Returns True if all characters in the string are decimals

string_variable.isdecimal()
Enter fullscreen mode Exit fullscreen mode

isdigit() method
Returns True if all characters in the string are digits

string_variable.isdigit()
Enter fullscreen mode Exit fullscreen mode

islower() method
Returns True if all characters in the string are lower case

string_variable.islower()
Enter fullscreen mode Exit fullscreen mode

isspace() method
Returns True if all characters in the string are whitespaces

string_variable.isspace()
Enter fullscreen mode Exit fullscreen mode

isupper() method
Returns True if all characters in the string are upper case

string_variable.isupper()
Enter fullscreen mode Exit fullscreen mode

lower() method
Converts a string into lower case

string_variable.lower()
Enter fullscreen mode Exit fullscreen mode

upper() method
Converts a string into upper case

string_variable.upper()
Enter fullscreen mode Exit fullscreen mode

strip() method
It removes leading and trailing spaces in the string

string_variable.strip()
Enter fullscreen mode Exit fullscreen mode

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

List

var_name = [element1, element2, and so on]
Enter fullscreen mode Exit fullscreen mode

List Methods index method
Returns the index of the first element with the specified value

list.index(element)
Enter fullscreen mode Exit fullscreen mode

append method
Adds an element at the end of the list

list.append(element)
Enter fullscreen mode Exit fullscreen mode

extend method
Add the elements of a list (or any iterable) to the end of the current list

list.extend(iterable)
Enter fullscreen mode Exit fullscreen mode

insert method
Adds an element at the specified position

list.insert(position, element)
Enter fullscreen mode Exit fullscreen mode

pop method
Removes the element at the specified position and returns it

list.pop(position)
Enter fullscreen mode Exit fullscreen mode

remove method
The remove( ) method removes the first occurrence of a given item from the list

list.remove(element)
Enter fullscreen mode Exit fullscreen mode

clear method
Removes all the elements from the list

list.clear()
Enter fullscreen mode Exit fullscreen mode

count method
Returns the number of elements with the specified value

list.count(value)
Enter fullscreen mode Exit fullscreen mode

reverse method
Reverse the order of the list

list.reverse()
Enter fullscreen mode Exit fullscreen mode

sort method
Sorts the list

list.sort(reverse=True|False)
Enter fullscreen mode Exit fullscreen mode

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

Tuple Creation

variable_name = (element1, element2, ...)
Enter fullscreen mode Exit fullscreen mode

Tuple Methods count method
It returns the number of times a specified value occurs in a tuple

tuple.count(value)
Enter fullscreen mode Exit fullscreen mode

index method
It searches the tuple for a specified value and returns the position.

tuple.index(value)
Enter fullscreen mode Exit fullscreen mode

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

Set Creation: Way 1

var_name = {element1, element2, ...}
Enter fullscreen mode Exit fullscreen mode

Set Creation: Way 2

var_name = set([element1, element2, ...])
Enter fullscreen mode Exit fullscreen mode

Set Methods: add() method
Adds an element to a set

set.add(element)
Enter fullscreen mode Exit fullscreen mode

clear() method
Remove all elements from a set

set.clear()
Enter fullscreen mode Exit fullscreen mode

discard() method
Removes the specified item from the set

set.discard(value)
Enter fullscreen mode Exit fullscreen mode

intersection() method
Returns intersection of two or more sets

set.intersection(set1, set2 ... etc)
Enter fullscreen mode Exit fullscreen mode

issubset() method
Checks if a Set is Subset of Another Set

set.issubset(set)
Enter fullscreen mode Exit fullscreen mode

pop() method
Removes an element from the set

set.pop()
Enter fullscreen mode Exit fullscreen mode

remove() method
Removes the specified element from the Set

set.remove(item)
Enter fullscreen mode Exit fullscreen mode

union() method
Returns the union of Sets

set.union(set1, set2...)
Enter fullscreen mode Exit fullscreen mode

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.

Dictionary

<dictionary-name> = {<key>: value, <key>: value ...}
Enter fullscreen mode Exit fullscreen mode

Adding Element to a dictionary
By this method, one can add new elements to the dictionary

<dictionary>[<key>] = <value>
Enter fullscreen mode Exit fullscreen mode

Updating Element in a dictionary
If the specified key already exists, then its value will get updated

<dictionary>[<key>] = <value>
Enter fullscreen mode Exit fullscreen mode

Deleting Element from a dictionary
del let to delete specified key: value pair from the dictionary

del <dictionary>[<key>]
Enter fullscreen mode Exit fullscreen mode

Dictionary Functions & Methods len() method
It returns the length of the dictionary, i.e., the count of elements (key: value pairs) in the dictionary

len(dictionary)
Enter fullscreen mode Exit fullscreen mode

clear() method
Removes all the elements from the dictionary

dictionary.clear()
Enter fullscreen mode Exit fullscreen mode

get() method
Returns the value of the specified key

dictionary.get(keyname)
Enter fullscreen mode Exit fullscreen mode

items() method
Returns a list containing a tuple for each key-value pair

dictionary.items()
Enter fullscreen mode Exit fullscreen mode

keys() method
Returns a list containing the dictionary's keys

dictionary.keys()
Enter fullscreen mode Exit fullscreen mode

values() method
Returns a list of all the values in the dictionary

dictionary.values()
Enter fullscreen mode Exit fullscreen mode

update() method
Updates the dictionary with the specified key-value pairs

dictionary.update(iterable)
Enter fullscreen mode Exit fullscreen mode

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

if Statement

if(conditional expression):
   statements
Enter fullscreen mode Exit fullscreen mode

if-else Statement

if(conditional expression):
   statements
else:
   statements
Enter fullscreen mode Exit fullscreen mode

if-elif Statement

if (conditional expression) :
    statements
elif (conditional expression) :
    statements
else :
    statements
Enter fullscreen mode Exit fullscreen mode

Nested if-else Statement

if (conditional expression):
   statements
else:
   statements
else:
   statements
Enter fullscreen mode Exit fullscreen mode

Iterative Statements
An iteration statement, or loop, repeatedly executes a statement, known as the loop body, until the controlling expression is false (0).

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.

for <variable> in <sequence>:
statements_to_repeat
Enter fullscreen mode Exit fullscreen mode

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

while <logical-expression> :
loop-body
Enter fullscreen mode Exit fullscreen mode

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.

for <var> in <sequence> :
statement1
if <condition> :
break
statement2
statement_after_loop
Enter fullscreen mode Exit fullscreen mode

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

for <var> in <sequence> :
statement1
if <condition> :
continue
statement2
statement3
statement4
Enter fullscreen mode Exit fullscreen mode

Functions
A function is a block of code that performs a specific task. You can pass parameters into a function. It helps us to make our code more organized and manageable.

Function Definition

def my_function(parameters):
# Statements
Enter fullscreen mode Exit fullscreen mode

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

var_name = open("file name", "opening mode")
Enter fullscreen mode Exit fullscreen mode

close() function

var_name.close()
Enter fullscreen mode Exit fullscreen mode

Read () function
The read functions contains different methods, read(),readline() and readlines()

read() #return one big string
Enter fullscreen mode Exit fullscreen mode

It returns a list of lines

read-lines
Enter fullscreen mode Exit fullscreen mode

It returns one line at a time

readline
Enter fullscreen mode Exit fullscreen mode

Write () function
This function writes a sequence of strings to the file.

write () #Used to write a fixed sequence of characters to a file
Enter fullscreen mode Exit fullscreen mode

It is used to write a list of strings

writelines()
Enter fullscreen mode Exit fullscreen mode

Append () function
The append function is used to append to the file instead of overwriting it. To append to an existing file, simply open the file in append mode (a):

file = open("Hello.txt", "a")
Enter fullscreen mode Exit fullscreen mode

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

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

try:
[Statement body block]
raise Exception()
except Exception as e:
[Error processing block]
Enter fullscreen mode Exit fullscreen mode

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

class
The syntax for writing a class in python

class class_name:
#Statements
Enter fullscreen mode Exit fullscreen mode

class with a constructor
The syntax for writing a class with the constructor in python

class Abhiraj:

# Default constructor
def __init__(self):
self.name = "Abhiraj"

# A method for printing data members
def print_me(self):
print(self.name)
Enter fullscreen mode Exit fullscreen mode

object
Instantiating an object

<object-name> = <class-name>(<arguments>)
Enter fullscreen mode Exit fullscreen mode

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

filter(function, iterable)
Enter fullscreen mode Exit fullscreen mode

issubclass function
Used to find whether a class is a subclass of a given class (classinfo) or not

issubclass(class, classinfo)
Enter fullscreen mode Exit fullscreen mode

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

Iterator
Used to create an iterator over an iterable

iter_list = iter(['Harry', 'Aakash', 'Rohan']) 
print(next(iter_list)) 
print(next(iter_list)) 
print(next(iter_list))
Enter fullscreen mode Exit fullscreen mode

Generator
Used to generate values on the fly

# A simple generator function
def my_gen():
n = 1
print('This is printed first')
# Generator function contains yield statements
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
Enter fullscreen mode Exit fullscreen mode

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

property Decorator (getter)

@property
def name(self):
return self.__name
Enter fullscreen mode Exit fullscreen mode

setter Decorator
It is used to set the property 'name'

@name.setter
def name(self, value):
self.__name=value
Enter fullscreen mode Exit fullscreen mode

Deletor Decorator
It is used to delete the property 'name'

@name.deleter #property-name.deleter decorator
def name(self, value):
print('Deleting..')
del self.__name
Enter fullscreen mode Exit fullscreen mode

You can support my blogs by buying me a coffee by clicking below...
bmc

Top comments (5)

Collapse
 
ejm profile image
EJM97

There seems to be an syntax issue in the Nested if-else Statement. 1 if but 2 else statements.

Collapse
 
abhirajb profile image
Abhiraj Bhowmick

That is not a syntax error. That is called nesting in computer programming. Any number of these statements can be nested inside one another. If I would give only one else statement then there would not be any difference between nested statements and normal if-else statements
Hope I was able to clear it for you :)

Collapse
 
ejm profile image
EJM97

Apprecieate the explanation, but unfortunately I still don't get it. Could you please explain further, my current understanding of nested if statements is as follows.

if condition 1:
    statements
    # a nested if-else
    if condition 2:
        statements
    else:
        statements
else:
    statements
    # another nested if-else     
    if condition 3:
        statements
    else:
        statements    

I tried using 2 else statements witihn one 'if' indented in diferrent ways but it always threw an error.
for exaple i tried -->

if condition 1:
    statements
    else:
        statements
else:
    statements

Using 2 else statements after a single if seems logically pointless even if it were syntactically correct as all the statements under both else conditions seems to be executed only when the if condition is False    

Collapse
 
tngeene profile image
Ted Ngeene

Nice article! For the conditional statements bit, could you show the indentation. Since this is meant for beginners, I feel it would be important to indent the examples.

Collapse
 
michaelcurrin profile image
Michael Currin

And the classes need indentation too