0% found this document useful (0 votes)
3 views30 pages

Python

The document provides an overview of Python programming concepts including data types, variables, classes, constructors, functions, and error handling. It explains the syntax and usage of various features such as the map function, membership operators, loops, and exception handling. Additionally, it covers the characteristics of Python's dynamic typing, memory management, and the importance of Unicode and hash values.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views30 pages

Python

The document provides an overview of Python programming concepts including data types, variables, classes, constructors, functions, and error handling. It explains the syntax and usage of various features such as the map function, membership operators, loops, and exception handling. Additionally, it covers the characteristics of Python's dynamic typing, memory management, and the importance of Unicode and hash values.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Basics:

Data Types:
 Int()
 Flot()
 Str()

X = “Welcome” <class ‘str’>


Print(type(x))

 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

My_string = “python” 19989733499 #Memory address


Print(id(My_string))

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.

Key characteristics of Python constructors:

 __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:

"\n" is used to move to a new line

In Python, \n is an escape character that represents a newline. When encountered within


a string or when printed, it instructs the program to move the cursor to the beginning of
the next line.

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:

def function_name(parameter1, parameter2, ...):


"""
Docstring: This is an optional string that describes the function's purpose.
"""
# Function body: This is where the code to be executed by the function resides.
# The code inside the function body must be indented.
return value # Optional: Returns a value from the function.

Note: function header/ function body

Explanation of Components:

 def keyword:

This keyword marks the beginning of a function definition.

 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 ():

These enclose the function's parameters (also known as arguments).

 parameter1, parameter2, ...: These are optional variables that the function
can accept as input. If there are multiple parameters, they are separated
by commas.

 If a function takes no parameters, the parentheses are still required and


remain empty (e.g., def greet():).

 Colon :

This signifies the end of the function header and the beginning of the function body.

Program:

def greet(name,age): # Function & Parameters()


print(f"Hi {name}, your age is {age}")
greet("saravanan",27) # calling the function and passing the arguments

Hash value [hash()]


In Python, a hash value is an integer representing an object, generated by a hash
function. This value serves as a quick "fingerprint" for the object and is primarily used for
efficient lookups and storage in hash-based data structures like dictionaries and sets.

Here are key aspects of hash values in Python:

 Immutable Objects Only:

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:

map(function, iterable, ...)

type()
type() function in python returns an object’s type when called

x=5 Class: Int


Print(type(x))
x = “welcome” Class: str
Print(type(x))
x=[“apple”, “mango”] Class: list
print(type(x))
x=(“apple”, “mango”) Class: tuple
print(type(x))

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

# Example 1: Basic floor division 4


result = 13 // 3
print(result)

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).

 iterable: A sequence like a list, tuple, or string.

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.

So, if the user inputs 3 5, the program will:

 Convert them to integers,

 Assign a = 3 and b = 5,
 Then compute c = a + b, which is 8,

 And finally print 8.

Program: covert strings to integers

numbers = ["1", "2", "3"]


result = list(map(int, numbers))
print(result) # Output: [1, 2, 3]

Program: Using a custom function

values = [1, 2, 3, 4]
squared = list(map(square, values))
print(squared) # Output: [1, 4, 9, 16]

Program: With input()

a, b = map(int, input("Enter two numbers: ").split())

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

They return Boolean value

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

X = [“apple”, “orange”] True


Print( “apple” in x)
X = [“apple”, “orange”] False
Print( “mango” in x)
X = [“apple”, “orange”] True
Print( “mango” not in x)
X = [“apple”, “orange”] False
Print( “apple” not in x)

Loops:

For Loop
Syntax:

for variable in iterable:


# code block to execute

String Alignment methods:

Python provides several methods for aligning strings within a specified width, including

 ljust(),
 rjust(),
 center(),
 format(), and
 f-strings.

Difference:

Loop For Loop While Loop


Definition  Used when we know how  Used when we have an
many times to repeat end condition
 Often with lists, tuples, sets,
or dictionaries

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.

Import the entire module


This imports the module and requires you to use the module name as a prefix to access
its contents.

Syntax:

Import module_name

Example:
import math
print([Link]) # [Link] will give the value of pi

Import specific component from module:


from module_name import component_name

Example:
from math import pi
print(pi)
Errors

Errors

Compile Time
Run Time Error Error Logical Error
(Syntax Errors)

Compile-Time Errors (Syntax Errors):


 These errors are detected by the Python interpreter during the parsing and
bytecode compilation phase, before the program actually starts executing.

 They typically arise from violations of Python's syntax rules, meaning the code is
not structured correctly according to the language's grammar.

 Examples include missing colons, incorrect indentation, misspelled keywords, or


unclosed parentheses.

 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

Runtime Errors (Exceptions):


 These errors occur during the execution of the program, after it has successfully
passed the compilation phase.

 They arise from conditions that are valid syntactically but become problematic
during execution, often due to unexpected data, invalid operations, or resource
issues.

 Examples include ZeroDivisionError (dividing by zero), NameError (referencing an


undefined variable), TypeError (performing an operation on an incompatible data
type), or FileNotFoundError (trying to open a non-existent file).

 Runtime errors are often handled using try-except blocks to prevent the program
from crashing.

Example of a Runtime Error:

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:

try and except:


The try block contains the code that might raise an exception. If an exception occurs
within the try block, the execution immediately jumps to the corresponding except block.

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

Multiple except blocks can be used to handle different types of exceptions:

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:

In Python, except Exception as e is a fundamental construct used for handling


exceptions. This syntax is part of a try-except block, which allows you to gracefully
manage errors that occur during the execution of your code, preventing your program
from crashing.

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.

Characteristics of Logical Errors:

 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.

Common Causes of Logical Errors:

 Incorrect Algorithm Implementation:

The chosen algorithm might be flawed, or it might be implemented incorrectly in the


code.

 Incorrect Conditions:

Errors in conditional statements (e.g., if, elif, else) can lead to the wrong code blocks
being executed.

 Incorrect Variable Usage:

Using the wrong variable name, or mismanaging variable scope, can lead to incorrect
calculations or data manipulation.

 Operator Precedence Issues:

Misunderstanding the order of operations in expressions can lead to incorrect


calculations.

 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.

Super Keyword (Constructor)

class a(): a
def __init__(self): b
print("a")

class b(a): #inheriting class b with class a


def __init__(self):
super().__init__() #super keyword
calls constructor from class a
print("b")

obj1=b()

Super Keyword (Method)

class A: Method from A


def method(self): Method from C
print("Method from A")

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:

 Deleting Variables/Names: del can remove a variable's binding from the


current namespace. After del var_name, attempting to access var_name will result
in a NameError if no other reference to the object exists.

x = 10
print(x) # Output: 10
del x
# print(x) # This would raise a NameError

 Deleting Elements from Data Structures:

o Lists: del can remove elements from a list by index or by slicing.

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]

del my_list[1:3] # Deletes elements from index 1 up to (but


not including) index 3
print(my_list) # Output: [1, 5]
 Dictionaries: del can remove a key-value pair from a dictionary using the key.

my_dict = {'a': 1, 'b': 2, 'c': 3}


del my_dict['b']
print(my_dict) # Output: {'a': 1, 'c': 3}
 Sets: del can be used to delete an entire set.

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]()

Dell=laptop() #Object Dell


[Link]="6GB"
[Link]="i5"
[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.

Here's a breakdown of its purpose and usage:

 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.

 Accessing Instance Attributes and Methods:

Within a method, self.attribute_name is used to access an attribute belonging to that


particular instance, and self.method_name() is used to call another method on the same
instance. This distinguishes between instance-specific data/operations and local variables
or parameters within the method.

 Convention, Not a Keyword:

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.

Key Points about Indexing:

Positive Indexing: Access elements from the beginning of the iterable.

Example: my_list[0] gives the first element.

Negative Indexing: Access elements from the end of the iterable.

o Example: my_list[-1] gives the last element.

Nested Indexing: Access elements in nested structures like lists of lists.

 Example: nested_list[1][0] accesses the first element of the second list.

Indexing:

Syntax:

s[start:stop:step]

s="abcdef"

print(s[:3]) # 'abc' (start to index 3, exclusive)


print(s[2:]) # 'cdef' (index 2 to end)

print(s[::]) # 'abcdef' (copy of the whole string)

print(s[::2]) # 'ace' (every 2nd char)

print(s[::-1]) # 'fedcba' (reversed string)

print(s[-3:-1]) # 'de' (negative indices count from the end)

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.

key aspects of the return statement:

 Exiting a Function:

When Python encounters a return statement, the function's execution immediately


stops. Any code written after the return statement within that function will not be
executed.

 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.

 Default Return Value (None):

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.

 Returning Multiple Values:

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

car = [‘nano’, ‘swift’, ’BMW’] [‘BMW’, ‘swift’, ‘nano’]


print(list(reversed(car))
Replace()
The replace() method in Python is used to replace occurrences of a specified substring
within a string with another substring. The original string remains unchanged as strings
are immutable in Python; instead, a new string with the replacements is returned.

The syntax for the replace() method is as follows:

Syntax:

[Link](old, new, count)

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.

Here's how it works:

 Syntax: list_name.append(element)

o list_name: The name of the list you want to modify.

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.).

 Functionality: When append() is called, the specified element is added as the


last item in the list_name.

 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)

TypeError: [Link]() takes exactly one argument (2 given)

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.

Key characteristics of extend():

 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).

 Appends elements individually: It iterates through the provided iterable and


appends each element individually to the target list. This is a key difference
from append(), which would add the entire iterable as a single element.

Syntax:

list_name.extend(iterable)

Program:

list1 = [1, 2, 3] [1,2,3,4,5,6]


list2 = [4, 5, 6]

[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])

List_name – Name of the list from which to remove an element

Index (optional) – The position index of the item to remove. If omitted, pop() removes and
returns the last item in the list by default.

This method returns the removed items

If the index is out of range or the list is empty, an IndexError is raised

For Lists:

 Purpose: Removes an element from a list at a specified index and returns the
removed element.

 Syntax: [Link]([index])

 Parameters:

o index (optional): The position of the element to be removed. If no index is


provided, pop() removes and returns the last element of the list by
default.

 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:

Car = {‘brand’:”Ford”, Mustang


‘model’:’Mustang’}
x = [Link](‘model’)
Print(x)
Clear()
The clear() method in Python is a built-in function used to remove all elements from a
mutable data structure, effectively emptying it. This method is available for several
common data types:

 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: []

 Dictionaries: [Link]() removes all key-value pairs from a dictionary, resulting


in an empty dictionary ({}).

Python

my_dict = {"a": 1, "b": 2}


my_dict.clear()
print(my_dict) # Output: {}

 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.

Key aspects of import math:

 Accessing Mathematical Functions:

After importing, you can use functions like [Link]() for square root, [Link]() for
power, [Link]() for sine, and many more.

 Accessing Mathematical Constants:

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

# Calculate the square root


result_sqrt = [Link](16)
print(f"Square root of 16: {result_sqrt}")

# Calculate 2 raised to the power of 3


result_pow = [Link](2, 3)
print(f"2 to the power of 3: {result_pow}")

# Use the constant pi


circumference = 2 * [Link] * 5
print(f"Circumference of a circle with radius 5: {circumference}")

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:

TypeError: can only concatenate str (not "int") to str


TypeError: can only concatenate str (not "int") to str in Python indicates an attempt to
combine a string and an integer directly using the + operator. Python, being a strongly-
typed language, does not implicitly convert data types for concatenation.

To resolve this error, explicitly convert the integer to a string before concatenation.

Here are common methods to achieve this: Using str() function.

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:

There are several ways to find the cube of an integer in Python:

#Finding cube of a number cube of the number using exponential


#using exponential operator operator: 125
num = 5 cube of the number using pow() fun:
cube_val = num ** 3 125
print("cube of the number using cube of the number using
exponential operator:",cube_val) multiplication: 125
cube of the number using [Link]
#using pow() built in function fun: 125
num = 5
cube_val1 = pow(num,3)
print("cube of the number using pow()
fun:",cube_val1)

#using multiplication
num = 5
cube_val2 = num * num * num
print("cube of the number using
multiplication:",cube_val2)

#using [Link] function


#Note that [Link]() returns a float,
even if the input is an integer.
import math
num = 5
cube_val3 = [Link](num,3)
print("cube of the number using
[Link] fun:",int(cube_val3))

TypeError: map() must have at least two arguments


he map() function in Python requires at least two arguments:

 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.

Example of the error:

def square(x):
return x * x

# This will raise a TypeError because only one argument is provided


print(map(square))
Correct usage:

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

AttributeError: 'student' object has no attribute 'display'

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:

 Built-in Collection Types:

These are fundamental data structures available directly in Python:

 Lists: Ordered, mutable sequences of elements enclosed in square


brackets []. They can contain heterogeneous data types and allow
duplicate elements.

 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.

 Sets: Unordered collections of unique elements enclosed in curly


braces {}. They do not allow duplicate elements and are primarily used for
membership testing and mathematical set operations.

 Dictionaries: Unordered collections of key-value pairs enclosed in curly


braces {}. Keys must be unique and immutable, while values can be any
data type and can be duplicated.

Counter

In Python, a Counter is a specialized dictionary subclass found within


the collections module. Its primary purpose is to efficiently count the occurrences of
hashable objects within an iterable.

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.

 Can Contain Mixed Data Types:

A single list can hold elements of different data types (e.g., integers, strings, floats,
booleans, or even other lists).

Creating a List:

Lists are created by enclosing a comma-separated sequence of items within square


brackets [].

# An empty list
empty_list = []

# A list of integers
numbers = [1, 2, 3, 4, 5]

# A list of strings
fruits = ["apple", "banana", "cherry"]

# A list with mixed data types


mixed_list = ["hello", 123, True, 3.14]

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)

Negative indexing [-value]


In Python, [-2] when used with a list (or other sequence types like strings or tuples) refers
to negative indexing, which allows you to access elements from the end of the
sequence.

Specifically, list_name[-2] will access the second-to-last element of the list.

Here's how negative indexing works:

 list_name[-1] refers to the last element.

 list_name[-2] refers to the second-to-last element.

 list_name[-3] refers to the third-to-last element, and so on.


Program:

my_list = [10, 20, 30, 40, 50]

# Accessing elements using negative indexing


print(my_list[-1]) # Output: 50 (the last element)
print(my_list[-2]) # Output: 40 (the second-to-last element)
print(my_list[-3]) # Output: 30 (the third-to-last element)

[Link]() method:

My_list = [1,2,3,4] [5,4,3,2,1]


My_list.reserse()
print(My_list)

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)

Error: AttributeError: 'tuple' object has no attribute 'append'

Program: Tuple index retrieval

.index(3) returns the index position of the element 3 in the tuple

My_tuple = (1,2,3,4,5) 2
Print(My_tuple.index(3)

Note: Tuple can be converted to list

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:

my_dict = {"brand": "Ford", "model": "Mustang", "year": 1964}


print(my_dict)
Condition Statements:

 If
 If else
 elif
 Nested if

Control Flow Statements:

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 using boolean expression

while(true/false)

true: the while loop executes

false: exit the while loop

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:

Using the # symbol for each line.


This method involves placing a hash symbol (#) at the beginning of each line you wish to
comment out. While this is effectively a series of single-line comments, it achieves the
goal of disabling a block of code.

# This line of code will not be executed.


# print("Hello, World!")
# x = 10 + 5

Using triple quotes for multi-line strings (often used as docstrings):


Although not strictly "comments" in the same way # is, multi-line strings enclosed in
triple single quotes (''') or triple double quotes (""") can effectively serve as block
comments. If these strings are not assigned to a variable or used as a docstring for a
function/class, the Python interpreter will ignore them during execution.

'''
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.

 Definition: The factorial of a number n, written as n!, is calculated by multiplying


n by every positive whole number less than it, down to 1.

 Formula: The general formula is: n! = n * (n-1) * (n-2) * ... * 2 * 1.

 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.

PyPy3 is an alternative implementation of the Python 3 language. Unlike CPython, which


directly executes Python bytecode, PyPy focuses on performance improvements through
Just-In-Time (JIT) compilation. This means that PyPy translates Python code into machine
code during runtime, often resulting in significant speedups for long-running programs or
computationally intensive tasks. PyPy also aims for high compatibility with CPython,
meaning most Python code written for CPython will run on PyPy3, although some minor
differences exist, particularly concerning low-level implementation details or specific C
extensions.

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

i.e. from collections import Counter

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

2. Dynamically typed vs statically typed

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:

 Data type of the variable is compile time


 Faster to execute due to type checking at compile time
3. List items cannot be removed after the list has been created – true
or false
False – list are mutable only after the list has been created

You might also like