Python CheatSheet
Basics
Showing Output To User
The print() function displays output to the screen.
print("Content that you wanna print on screen")
Displaying the value stored in a variable:
var1 = "Shruti" print("Hi my name is: ", var1)
Taking Input From the User
The input() function takes input as a string from the user.
var1 = input("Enter your name: ") print("My name is: ", var1)
To take input as other data types, typecast them:
# Integer input var1 = int(input("Enter the integer value: ")) print(var1) # Float input var1 = float(input("Enter the float value: ")) print(var1)
Range Function
Returns a sequence of numbers. int_stop_value is compulsory; start and step default to 0 and 1.
range(int_start_value, int_stop_value, int_step_value) # Display all even numbers from 0 to 100 for i in range(0, 101, 2): print(i)
Comments & Escape Sequences
Comments
Comments make code more readable. They are not executed by the interpreter.
# Single line comment ''' Multi-line comment '''
Escape Sequences
Characters that don’t represent themselves but are translated into special characters inside string literals.
| Sequence | Name | Description |
|---|---|---|
| \n | Newline | Moves to a new line |
| \\ | Backslash | Adds a backslash |
| \’ | Single Quote | Adds a single quotation mark |
| \t | Tab | Gives a tab space |
| \b | Backspace | Adds a backspace |
| \ooo | Octal | Represents value of an octal number |
| \xhh | Hex | Represents value of a hex number |
| \r | Carriage Return | Shifts cursor to beginning of line |
print("Line1\nLine2") # newline print("Tab\there") # tab print("Back\\slash") # backslash
Strings
A Python string is a sequence of characters, each accessible by its index. Created using single or double quotes.
variable_name = "String Data" str = "Shruti" print("string is ", str)
Slicing
Obtains a sub-string from a given string.
string_var[start : stop : step] var_name[1 : 5] # includes index 1, 2, 3, 4
String Methods
| Method | Description |
|---|---|
| .isalnum() | True if all characters are alphanumeric |
| .isalpha() | True if all characters are alphabets |
| .isdecimal() | True if all characters are decimals |
| .isdigit() | True if all characters are digits |
| .islower() | True if all characters are lowercase |
| .isupper() | True if all characters are uppercase |
| .isspace() | True if all characters are whitespace |
| .lower() | Converts string to lowercase |
| .upper() | Converts string to uppercase |
| .strip() | Removes leading and trailing spaces |
Lists
Comma-separated values of any data type in square brackets. Lists are ordered, indexed, mutable — the most flexible collection in Python.
var_name = [element1, element2, ...]
my_list = [] # empty list
List Methods
| Method | Description |
|---|---|
| .index(element) | Returns index of first occurrence of the element |
| .append(element) | Adds element at the end |
| .extend(iterable) | Adds all elements of an iterable to the end |
| .insert(pos, elem) | Adds element at the specified position |
| .pop(position) | Removes & returns element at position |
| .remove(element) | Removes first occurrence of the element |
| .clear() | Removes all elements |
| .count(value) | Returns count of elements with specified value |
| .reverse() | Reverses the list in place |
| .sort(reverse=True|False) | Sorts the list |
fruits = ["apple", "banana", "cherry"] fruits.append("mango") fruits.insert(1, "kiwi") fruits.remove("banana") fruits.sort() print(fruits)
Tuples
Comma-separated values within parentheses. Tuples are ordered, indexed, immutable — the most secured collection in Python.
variable_name = (element1, element2, ...)
| Method | Description |
|---|---|
| .count(value) | Returns the number of times value occurs in tuple |
| .index(value) | Searches tuple and returns position of value |
Sets
A collection that is unordered, unindexed. Duplicate elements are NOT allowed.
# Way 1 var_name = {element1, element2, ...} # Way 2 var_name = set([element1, element2, ...])
Set Methods
| Method | Description |
|---|---|
| .add(element) | Adds an element to the set |
| .clear() | Removes all elements |
| .discard(value) | Removes the specified item |
| .intersection(s1,s2…) | Returns intersection of two or more sets |
| .issubset(set) | Checks if set is a subset of another set |
| .pop() | Removes a random element |
| .remove(item) | Removes the specified element |
| .union(set1, set2…) | Returns union of two or more sets |
Dictionaries
Ordered, mutable collection of key:value pairs. Duplicate values allowed — duplicate keys are not.
# Create my_dict = {"name": "Suzal", "course": "MCA"} # Empty mydict = {} # Add / Update my_dict["age"] = 22 # Delete del my_dict["age"]
Dictionary Methods
| Method | Description |
|---|---|
| len(dict) | Returns count of key:value pairs |
| .clear() | Removes all elements |
| .get(key) | Returns the value of the specified key |
| .items() | Returns list of tuples for each key-value pair |
| .keys() | Returns list of all keys |
| .values() | Returns list of all values |
| .update(iterable) | Updates dict with specified key-value pairs |
Conditional Statements
The if, elif and else statements implement selection constructs in Python.
# if if(condition): statements # if-else if(condition): statements else: statements # if-elif-else if (condition): statements elif (condition): statements else: statements
Nested Example
a = 15; b = 20; c = 12 if(a>b and a>c): print(a, "is greatest") elif(b>c and b>a): print(b, "is greatest") else: print(c, "is greatest")
Loops
For Loop
Processes items of any sequence one by one.
for variable in sequence: statements # Print 1 to 100 for i in range(1, 101): print(i)
While Loop
Repeats as long as the condition is true.
while condition: loop-body i = 1 while(i <= 100): print(i) i = i + 1
Break & Continue
# break — exits the loop for i in range(1, 10): if i == 5: break print(i) # continue — skips current iteration for i in [2,3,4,6]: if (i % 2 != 0): continue print(i)
Functions
A block of code that performs a specific task. Makes code organised and reusable.
# Define def my_function(): #statements # Call my_function()
Return Statement
return [value/expression]
Arguments
def my_function(arg1, arg2, argn): #statements my_function(arg1, arg2, argn) # Example def add(a, b): return a + b x = add(7, 8) print(x) # 15
File Handling
Python provides functions to read, write, and manipulate files.
var_name = open("filename", "mode")
File Modes
rRead content from filewWrite content into fileaAppend to existing contentr+Read and write — previous data overriddenw+Write and read — overrides existing dataa+Append and read — won’t override existing data
Read & Write Functions
read() # returns one big string readlines() # returns a list of all lines readline # returns one line at a time write() # writes a string to the file writelines() # writes a list of strings var_name.close() # always close after use!
Exception Handling
An exception is an unusual condition that interrupts the normal flow of a program.
# try-except try: [Statement body block] raise Exception() except ExceptionName: [Error processing block] # try-except-else try: #statements except: #statements else: # runs if no exception raised # finally — always runs try: #statements except: #statements finally: # compulsorily executed
Object Oriented Programming (OOP)
A programming approach that focuses on using objects and classes to represent real-world entities.
# Class definition class MyClass: pass # Object creation obj = MyClass() # Class with constructor class MyClass: def __init__(self): self.name = "DataSteroid" def print_me(self): print(self.name)
Inheritance
A derived/child class uses properties of a base/parent class — promotes code reusability.
class Base_class: pass class Derived_class(Base_class): pass
| Type | Description |
|---|---|
| Single | One derived class from one base class |
| Multiple | One derived class from multiple base classes |
| Multilevel | Derived class from another derived class |
| Hierarchical | Multiple derived classes from one base class |
Iterators & Generators
Iterator
Creates an iterator over an iterable. Returns elements one at a time using next().
iter_list = iter(['Harry', 'Aakash', 'Rohan']) print(next(iter_list)) # Harry print(next(iter_list)) # Aakash print(next(iter_list)) # Rohan
Generator
Uses yield to generate values on the fly without storing all values in memory.
def my_gen(): n = 1 print('First') yield n n += 1 print('Second') yield n n += 1 print('Third') yield n
Filter Function
filter(function, iterable) # Extracts items from iterable that satisfy the function condition
issubclass
issubclass(obj, classinfo) # Returns True if obj is a subclass of classinfo
Decorators
Modify the behavior of a function or class. Called before the definition of the function to be decorated.
# property (getter) @property def name(self): return self.__name # setter @name.setter def name(self, value): self.__name = value # deleter @name.deleter def name(self, value): print('Deleting..') del self.__name