Python
Python
Data Types:
Int()
Flot()
Str()
Complex()
We can use complex () function to convert an int or float to the complex number.
But we cant convert a complex() number to int or float
X = 10 10+Oj
Print(complex(x)) <class ‘complex’>
Print(type(x))
bool
bool() is a built-in function tat converts a value to True or False
non-empty strings are always considered as True
empty strings are considered as False
String: Output:
Print(bool(“test”) True
Print(bool(“”) False
Int:
Print(bool(0)) False
Print(bool(1)) True
Variables:
Variables are used to store data values. They act as named containers or labels for
information that the program can access and manipulate
Key characteristics:
Assignment: variables are created the moment a value is assigned to them using
the = operator.
Name = ‘Alice’
age = 30
Dynamic Typing: py is dynamically typed, meaning you don’t need to specify the
data type or a variable when you declare it. The interpreter automatically infers
the type based on the assigned value; variable’s type can change during the
program execution by assigning a value of a different type.
X = 10 #x is a string
X = ‘hello’ #now x is a string
Naming conventions:
1. Variable name must start with a letter or an underscore
2. Can contain alphanumeric characters
3. Case sensitive
Memory management:
Variables in py are store reference to objects in memory. When you assign a value
to a variable, you are essentially linking that variable name to memory location
where the value is stored. The id() function is used to retrieve the memory
address of an object
Class:
class keyword, followed by the class name, and a colon.
The class body, including function, objects, variables, attributes and methods, is
then defined with indentation.
Syntax:
class ClassName:
This line declares a class named ClassName. Class names conventionally use CamelCase
(e.g., MyClass).
Variables:
1. Global Variable
2. Private Variable
Program:
class goa:
name=""
drink=""
def party(self):
print("Lets Party")
def beach(self):
print("lets go to beach")
ramesh = goa()
suresh = goa()
[Link]="Ramesh"
[Link]="suresh"
[Link]="Yes"
[Link]="No"
print([Link])
print([Link])
print([Link])
print([Link])
constructor
In Python, a constructor is a special method used to initialize new objects of a class. It is
automatically invoked when an object of the class is created. The primary purpose of the
constructor is to set up the initial state of the object by assigning values to its attributes
or performing any necessary setup logic.
__init__ Method:
In Python, the constructor is defined using the special method __init__. This method is
identified by its double underscores (__) before and after the name, making it a "dunder"
method or "magic" method.
Automatic Invocation:
The __init__ method is automatically called when a new instance (object) of a class is
created. You do not explicitly call it like a regular method.
self Parameter:
The first parameter of the __init__ method is always self. This parameter refers to the
instance of the class being created and allows you to access and modify the instance's
attributes. Python automatically provides this argument when the constructor is called.
Initialization of Attributes:
Within the __init__ method, you typically initialize the instance variables (attributes) of
the object. This ensures that when an object is created, it starts with a defined state.
Optional Parameters:
Constructors can take additional parameters beyond self to allow for custom initialization
values when creating an object. This enables the creation of objects with varying initial
states.
No Return Value:
The __init__ method does not explicitly return any value. Its purpose is solely for
initialization, and attempting to return a non-None value will result in a TypeError.
Program:
# constructor
class laptop:
def __init__(self): #constructor is called automatically when the object is created for
the class
print("constructor")
def display(self):
print("function")
hp=laptop()
class laptop:
def __init__(self):
print("Constructor function")
def test(self):
print("Normal function")
hp=laptop() # Object for class laptop
[Link]() #[Link] name
Class Methods:
class method
instance
class methods
method
static method
Escape character:
print("print this in the first line,\nprint this print this in the first line,
in the second line") print this in the second line
Functions:
Passing arguments inside function:
In Python, arguments are values passed into a function when it is called. These
values are assigned to parameters defined within the function's signature. There are
several ways to pass arguments to a function: positional arguments.
Arguments are passed based on their order in the function call, matching the order of
parameters in the function definition.
Syntax:
Explanation of Components:
def keyword:
function_name:
This is the name you assign to your function. It should follow Python's naming
conventions (lowercase with underscores separating words, e.g., calculate_sum).
Parentheses ():
parameter1, parameter2, ...: These are optional variables that the function
can accept as input. If there are multiple parameters, they are separated
by commas.
Colon :
This signifies the end of the function header and the beginning of the function body.
Program:
Only immutable objects (whose values cannot change after creation) can be hashed in
Python. Examples include integers, floats, strings, and tuples containing only hashable
elements. Mutable objects like lists, dictionaries, and sets are not hashable because their
content can change, which would alter their hash value and break the integrity of hash-
based data structures.
Purpose:
Hash values are crucial for the performance of dictionaries and sets. When you add an
item to a dictionary or a set, Python calculates the hash value of the key (for dictionaries)
or the element (for sets) to determine its storage location, enabling fast retrieval.
hash() function:
Python provides a built-in hash() function to calculate the hash value of an object.
my_string = "hello"
hash_value = hash(my_string)
print(hash_value)
Map:
ap() is a built-in function that applies a specified function to each item in an iterable (like
a list, tuple, or set) and returns an iterator containing the results. It's a powerful tool for
transforming data without needing explicit for loops, promoting a more functional
programming style.
Syntax:
type()
type() function in python returns an object’s type when called
len()
The len() function in Python is a built-in function used to determine the length of an
object
Syntax:
len(object/Variable Name)
Program:
a="abracadabra" 11
print(len(a))
Ord()
Unicode:
Unicode is a standard encoding system that assigns a unique numeric value to every
character, regardless of the platform, program, or language
Unicode in python:
In Python, "Unicode" refers to the standard for representing characters from virtually all
the world's writing systems. It assigns a unique numeric value, called a code
point, to each character. Python's built-in str type (strings) are inherently Unicode
in Python 3.
Division Operator //
To perform division in Python and obtain a result without decimals, you can use the floor
division operator //. This operator performs division and rounds the result down to
the nearest whole number (integer). d
Map()
the map() function is used to convert multiple input values into integers in a
concise way. Here's a breakdown of what happens:
Syntax:
map(function, iterable)
Parameters:
function: A function that you want to apply to each item in the iterable
(e.g., int, str, float, or a custom function).
program:
a , b = map(int, input().split())
c=a+b
print(c)
1. input().split():
This takes a single line of input (e.g., "3 5") and splits it into a list of strings: ["3",
"5"].
2. map(int, ...):
This applies the int function to each element of the list, converting ["3",
"5"] into [3, 5].
3. a, b = ...:
This unpacks the two integers into variables a and b.
Assign a = 3 and b = 5,
Then compute c = a + b, which is 8,
values = [1, 2, 3, 4]
squared = list(map(square, values))
print(squared) # Output: [1, 4, 9, 16]
Membership Operator:
Membership operators are used to check if a sequence is present in an object [string, list,
tuple, set or dictionary], The in and not in
Syntax:
Value in sequence
Program:
my_list = [1,2,3,4,5]
print(3 in my_list) #Output: True
print(9 in my_list) #Output: False
Program:2
Loops:
For Loop
Syntax:
Python provides several methods for aligning strings within a specified width, including
ljust(),
rjust(),
center(),
format(), and
f-strings.
Difference:
Import:
In Python, modules are imported using the import statement. There are several ways to
import a module or specific components from it: Importing the entire module.
Syntax:
Import module_name
Example:
import math
print([Link]) # [Link] will give the value of pi
Example:
from math import pi
print(pi)
Errors
Errors
Compile Time
Run Time Error Error Logical Error
(Syntax Errors)
They typically arise from violations of Python's syntax rules, meaning the code is
not structured correctly according to the language's grammar.
The interpreter will raise a SyntaxError and prevent the program from running
until these errors are corrected.
if True
print("Hello") # Missing colon after True
They arise from conditions that are valid syntactically but become problematic
during execution, often due to unexpected data, invalid operations, or resource
issues.
Runtime errors are often handled using try-except blocks to prevent the program
from crashing.
x = 10
y=0
result = x / y # Division by zero
Exception Handling:
Exception handling in Python utilizes the try, except, else, and finally blocks.
Syntax:
Program:
try: 10
a = int(input()) asd
b = int(input()) Value error expection has be handled
print(a+b)
except ValueError:
print("Value error expection has be
handled")
Note: post except we need to mention the actual exception name in order, if we give
random name is not defined will be displayed
try: 10
# Code that might raise an exception 0
a = int(input()) Zero division exception is handled
b = int(input())
print(a/b)
except ValueError:
# Code to handle ValueError
print("Value error exception has be
handled")
except ZeroDivisionError:
print("Zero division exception is
handled")
try: 10
# Code that might raise an exception Abc
a = int(input()) Value division error has been handled
b = int(input())
print(a/b)
except ValueError:
# Code to handle ValueError
print("Value error exception has be
handled")
except ZeroDivisionError:
print("Zero division exception is
handled")
Exception as e:
try: 10
a = int(input()) abc
b = int(input()) Exception occured: invalid literal for int()
print(a+b) with base 10: 'abc'
except Exception as e:
print("Exception occured:",e)
Logical Error:
A logical error in Python, also known as a semantic error, occurs when a program runs
without crashing or producing any error messages, but it produces an incorrect or
unexpected output. Unlike syntax errors, which are caught by the Python interpreter
during parsing, logical errors stem from flaws in the program's algorithm or the way the
code is structured to solve a problem.
No Error Messages:
The program executes successfully from the interpreter's perspective, as there are no
syntax violations or unhandled exceptions.
Incorrect Output:
The primary indication of a logical error is that the program's output does not match the
expected or desired result.
Difficult to Detect:
Since there are no explicit error messages, logical errors can be challenging to identify
and debug, often requiring careful examination of the code's logic and step-by-step
verification of intermediate results.
Incorrect Conditions:
Errors in conditional statements (e.g., if, elif, else) can lead to the wrong code blocks
being executed.
Using the wrong variable name, or mismanaging variable scope, can lead to incorrect
calculations or data manipulation.
Off-by-One Errors:
Common in loops or when dealing with array/list indices, where a calculation is off by one
unit.
Incorrect Indentation:
In Python, incorrect indentation can drastically alter the program's logic, leading to
unexpected behavior.
# Intended to calculate the average of two numbers
num1 = 5
num2 = 10
average = num1 + num2 / 2 # Logical error due to operator precedence
print(f"The average is: {average}")
# Expected output: 7.5
# Actual output: 10.0 (because division happens before addition)
# Corrected code:
average = (num1 + num2) / 2
print(f"The corrected average is: {average}")
Keywords:
Super Keyword:
In Python, super() is a built-in function that provides a way to access methods and
properties of a parent or superclass from within a child or subclass. It returns a temporary
proxy object that represents the parent class.
Calling Parent Class Methods: The primary use of super() is to call methods defined in
the parent class, especially the __init__ method (constructor), from the subclass. This
ensures that the parent class's initialization or other functionalities are properly executed
when creating an instance of the subclass.
class a(): a
def __init__(self): b
print("a")
obj1=b()
class B:
def method(self):
print("Method from B")
class C(A, B):
def method(self):
super().method() # Calls A's method
first based on MRO
print("Method from C")
obj1=C()
[Link]()
Del keyword
n Python, del is a keyword used for deleting objects and references. It serves several
purposes:
x = 10
print(x) # Output: 10
del x
# print(x) # This would raise a NameError
my_list = [1, 2, 3, 4, 5]
del my_list[2] # Deletes element at index 2 (value 3)
print(my_list) # Output: [1, 2, 4, 5]
my_set = {1, 2, 3}
del my_set
# print(my_set) # This would raise a NameError
Self-keyword
Self-keyword is used to denote or refer the current object
Program: Output:
# Self-keyword
class laptop: ram: 8GB
def __init__(self): #self-keyword is processor: i7
used by class to identify the object in ram: 6GB
the class processor: i5
[Link]=""
[Link]=""
def display(self):
print("ram:",[Link])
print("processor:",[Link])
hp=laptop() #Object hp
[Link]="8GB"
[Link]="i7"
[Link]()
In Python, self is a conventional name for the first parameter of a method within a class
definition. It serves as a reference to the instance of the class on which the method is
being called.
Instance Reference:
When you define a method inside a class, self is automatically passed by Python as the
first argument, representing the specific object (instance) that the method is acting
upon. This allows the method to access and manipulate the instance's attributes (data)
and other methods.
While self is the widely accepted and recommended name for this parameter, it is not a
reserved keyword in Python. You could technically name it something else
(e.g., this_instance), but using self is a strong convention that enhances code readability
and understanding for other Python developers.
In __init__ (Constructor):
In the special __init__ method (the constructor), self refers to the newly created object
that is being initialized. It's used to set up the initial state of the instance by assigning
values to its attributes.
Pass keyword
The pass keyword in Python is a null operation or a placeholder statement. It is used
when a statement is syntactically required but no action needs to be performed at that
point in the code.
Program: Output:
a=488
b=45
if(a>b):
pass
else:
print("test")
not keyword:
Syntax:
not expression
Program:
a = True
print(not a) # Output: False
b = False
print(not b) # Output: True
Indexing/Slicing:
Indexing in Python refers to accessing individual elements of an iterable (like a list,
tuple, string, or array) using their position or index. Python uses zero-based indexing,
meaning the first element is at index 0, the second at 1, and so on.
Indexing:
Syntax:
s[start:stop:step]
s="abcdef"
Statements:
Return:
In Python, the return statement is used within a function to send a value back to the part
of the code that called the function. It effectively terminates the function's execution and
hands over control, along with the specified value, to the caller.
Exiting a Function:
Returning a Value:
The return statement can be followed by an expression or a literal value. This value is
then "returned" to the caller. The caller can then store this returned value in a variable,
use it in an expression, or pass it as an argument to another function.
If a function does not explicitly use a return statement, or if a return statement is used
without specifying a value (e.g., return), the function implicitly returns the special
value None. None is a unique constant in Python representing the absence of a value.
Python functions can effectively return multiple values by packaging them into a
tuple. The return statement can then return this tuple, and the caller can unpack the
individual values.
Methods:
Reversed
Reversed function in python lets us go through a sequence like list, tuple, or string in
reverse order without making a new copy. Instead, a storing the reversed sequence, it
gives us an iterator that yields elements one by one , saving memory
Syntax:
comp_name="google" Guugle
comp_name_update=comp_name.replace("o"
,"u",2)
print(comp_name_update)
Append()
In Python, append() is a built-in method used with lists to add a single element to the end
of the list. This method modifies the list in place, meaning it directly changes the existing
list rather than creating a new one.
Syntax: list_name.append(element)
o element: The single item you want to add to the end of the
list. This element can be of any data type (integer, string, float, another
list, etc.).
Return Value: The append() method does not return any value; it only modifies
the list.
Example:
Python
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
Insert()
In Python, the insert() function is a built-in method primarily used with lists to add an
element at a specific, user-defined position within the list.
Syntax:
[Link](index, element)
Program:
a=[,20.30,40,50]
[Link](0,10)
print(a)
extend()
The extend() method in Python is a built-in list method used to add all elements from an
iterable (such as another list, tuple, string, or set) to the end of the current list.
Modifies in-place: Unlike methods that return a new list, extend() modifies the
original list directly. It does not return any value (implicitly returns None).
Syntax:
list_name.extend(iterable)
Program:
[Link](list2)
print(list1)
Update()
set1 ={1,2,3,5}
set2 = {6,7,8,9}
[Link](set2)
print(set1)
Split()
The split() method in Python is a string method used to divide a string into a list of
substrings based on a specified delimiter.
Syntax:
[Link](separator, maxsplit)
pop()
The pop() method in Python is a built-in function primarily used with lists and dictionaries
to remove an item and return it.
Syntax:
List_name.pop([index])
Index (optional) – The position index of the item to remove. If omitted, pop() removes and
returns the last item in the list by default.
For Lists:
Purpose: Removes an element from a list at a specified index and returns the
removed element.
Syntax: [Link]([index])
Parameters:
Return Value: The element that was removed from the list.
For Dictionaries:
Get()
The get () method in python is primarily associated with dictionaries and provides a
safe way to retrieve the value associated with a specified key.
Syntax:
[Link](key, default_value)
Program: Op:
Lists: [Link]() removes all items from a list, leaving it as an empty list ([]).
Python
my_list = [1, 2, 3, 4]
my_list.clear()
print(my_list) # Output: []
Python
Sets: [Link]() removes all elements from a set, leaving it as an empty set
(set()).
Python
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # Output: set()
[Link]
In Python, import math is a statement used to bring the built-in math module into your
current program's scope. This allows you to access and utilize the various mathematical
functions and constants defined within the math module.
After importing, you can use functions like [Link]() for square root, [Link]() for
power, [Link]() for sine, and many more.
The math module also provides useful mathematical constants like [Link] (for pi)
and math.e (for Euler's number).
Module-Specific Namespace:
When you use import math, you need to prefix the functions and constants
with math. (e.g., [Link](25)). This helps avoid naming conflicts if you have other
variables or functions with the same names in your code.
Built-in Module:
The math module is a standard, built-in part of Python, meaning you don't need to install
it separately; it's always available for use.
import math
Print()
If you mention print() function without any values inside the print function it will move to
next line
for i in range(5):
print()
print(i)
Errors:
To resolve this error, explicitly convert the integer to a string before concatenation.
Program Output
age = 30 ERROR!
message = "My age is " + age + " years Traceback (most recent call last):
old." File "<[Link]>", line 2, in
print(message) <module>
TypeError: can only concatenate str
Note: when trying to concatenate a string with (not "int") to str
the integer the TypeError occurs can be
resolved using Typecasting Function
i.e. str(age)
age = 30 My age is 30 years old.
message = “My age is” + str(age)+”years
old.”
print(message)
Finding cube of a integer:
#using multiplication
num = 5
cube_val2 = num * num * num
print("cube of the number using
multiplication:",cube_val2)
A function: This is the function that will be applied to each item of the
iterable(s).
One or more iterables: These are the sequences (e.g., lists, tuples, strings)
whose elements will be passed to the function.
def square(x):
return x * x
To resolve this error, provide both a function and at least one iterable to map().
def square(x):
return x * x
numbers = [1, 2, 3, 4]
squared_numbers = list(map(square, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16]
TypeError: not all arguments converted during the string formatting
Collections (Arrays)
In Python, "collections" refers to container data types used for storing and organizing
data. These can be broadly categorized into two main groups:
Counter
List[]
In Python, a list is a built-in data structure used to store an ordered collection of
items. Lists are highly versatile and possess several key characteristics:
Ordered:
Items in a list maintain their insertion order. This means the order in which you add
elements is preserved.
Mutable:
Lists are changeable, meaning you can modify, add, or remove elements after the list
has been created.
Allow Duplicates:
Lists can contain duplicate values, as each item is accessed by its index.
A single list can hold elements of different data types (e.g., integers, strings, floats,
booleans, or even other lists).
Creating a List:
# An empty list
empty_list = []
# A list of integers
numbers = [1, 2, 3, 4, 5]
# A list of strings
fruits = ["apple", "banana", "cherry"]
a=[10,20,30,40]
Values of a 10 20 30 40
variable
Index value 0 1 2 3
of list
Program:
a = [1,2,3,4,5] [1, 2, 3, 4, 5]
print(a)
[Link]() method:
Tuple()
Tuples: Ordered, immutable sequences of elements enclosed in parentheses (). Like
lists, they can contain heterogeneous data types and allow duplicates, but their contents
cannot be changed after creation
# Tuple
a=(1,2,3,4,5) #syntax a=()
#[Link](6) we cannot modify a tuple
print(a)
My_tuple = (1,2,3,4,5) 2
Print(My_tuple.index(3)
Set{}
Do not allow duplicates, duplicate values will be removed
Any type of data can be stored
We cannot modify the set item but we can add or remove items
Sets are un ordered
Add(),update(),remove(),pop()
Dictionaries{}
In Python, a dictionary is a built-in data structure that stores data in key-value
pairs. Dictionaries are ordered, changeable, and do not allow duplicate keys. They are
also known as associative arrays or hashmaps in other programming languages.
Program:
If
If else
elif
Nested if
While loop:
A while loop in Python is a control flow statement that repeatedly executes a block of
code as long as a specified condition remains True
while(true/false)
Syntax:
while condition:
# code to be executed repeatedly
# (indented block)
i=0
while(i==0):# i(0)==0 true, i(1)==0 False (loop ends)
print(i)
i=i+1;
Comment out
In Python, there are two primary ways to "comment out" a sequence of code:
'''
This entire block of text
will be ignored by the Python interpreter
unless it's a docstring or assigned to a variable.
'''
"""
Another way to comment out
multiple lines of code.
"""
Math Concepts
Factorial:
The factorial of a non-negative integer n, denoted as n!, is the product of all positive
integers less than or equal to n. For example, 5! (read as "5 factorial") is 5 * 4 * 3 * 2 * 1
= 120. The factorial function is a fundamental concept in mathematics, particularly
in combinatorics and probability.
Example: 4! = 4 * 3 * 2 * 1 = 24.
Oneful pair:
A Oneful Pair is a pair of positive integers (a, b) that satisfy the equation a + b + (a * b) =
111
i.e. 1 and 55
Absolute Difference:
Area of a rectangle:
Area of a rectangle: = Length * width
Versions:
Pypy3 vs Python 3
Python 3 refers to the latest major version of the Python programming language and, by
common usage, also refers to its reference implementation, CPython. CPython is the
standard and most widely used implementation of Python, written in C. When one installs
"Python" from [Link] or through package managers, they are typically installing
CPython.
OOPS Concepts:
Inheritance
1. Single Inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid Inheritance
Polymorphism
Polymorphism in Python, derived from the Greek words "poly" (many) and "morph"
(forms), refers to the ability of an entity (like a function, method, or operator) to take on
different forms or behave differently depending on the context or the type of object it is
operating on. This concept is a fundamental principle of Object-Oriented Programming
(OOP) and enhances code flexibility, reusability, and maintainability.
#Polymorphism 3
def add(a,b,c=0): 6
print(a+b+c)
add(1,2)
add(1,2,3) #3 value will be overridden in
variable c with 0 so output will be printed
as 1+2+3=6
Data Structures:
Collections:
In Python, a "collection" refers to any data structure designed to store and organize
multiple items. These are also known as container data types. Python provides built-
in collections and a specialized collections module for more advanced use cases.
Note: to use the counter class we need import the collections module
Counter class:
Interview Questions:
1. can we pass a function as an argument in python?
Yes, several arguments can be passed to a function, including objects, variables (same or
distinct data types) and functions.
Functions can be passed as parameters to other functions because they are objects.
Higher -order functions are functions that can take other functions as arguments
Dynamically typed
The data type of the variable is determined at runtime not at compile time
No need to declare data type
Easier and faster to code
Languages - python, jawa script
x = 10 # x is an integer
x = “Good day” # x is an string
Statically typed: