Made by Abhishek Aggarwal
Python
Python Introduction
Python is a widely used high-level, interpreted programming language. It
was created by Guido van Rossum in 1991 and further developed by the
Python Software Foundation. It was designed with an emphasis on code
readability, and its syntax allows programmers to express their concepts in
fewer lines of code.
Python is widely used language
Python is used for:
● Web Development: Frameworks like Django, Flask.
● Data Science and Analysis: Libraries like Pandas, NumPy, Matplotlib.
● Machine Learning and AI: TensorFlow, PyTorch, Scikit-learn.
● Automation and Scripting: Automate repetitive tasks.
● Game Development: Libraries like Pygame.
● Web Scraping: Tools like BeautifulSoup, Scrapy.
● Desktop Applications: GUI frameworks like Tkinter, PyQt.
● Scientific Computing: SciPy, SymPy.
● Internet of Things (IoT): MicroPython, Raspberry Pi.
● DevOps and Cloud: Automation scripts and APIs.
● Cybersecurity: Penetration testing and ethical hacking tools.
Key Features of Python
Python is Easy to Learn and Use: There is no prerequisite to start Python, since it is
Ideal programming language for beginners.
High Level Language: Python don’t let you worry about low-level details, like
memory management, hardware-level operations etc.
Python is Interpreted: Code is executed line-by-line directly by interpreter, and no
need for separate compilation. Which means –
● You can run the same code across different platforms.
● You can make the changes in code without restarting the program.
Dynamic Typed: Python is a dynamic language, meaning there are no need to
explicitly declare the data type of a variable. Type is checked during runtime, not at
compile time.
X=5
X = “hello”
print(X)
Object Oriented: Python supports object-oriented concepts like classes,
inheritance, and polymorphism etc. OOPs empowers Python with modularity,
reusability and easy to maintain code.
Extensive Library are Available: Python has huge set of library and modules, which
can make development lot easier and faster.
Open-Source with Huge community Support: Along with opensource, Python is
blessed with very large community contributing to its further development.
Cross Platform: Same Python code can run on Windows, macOS and Linux,
without any modification in code.
Good Career Opportunities: Python is in high demand across industries like
Software development, AI, finance, and cloud computing etc.
What can you do with Python?
Python can be used to develop full-stack web applications and RESTful APIs.
Python can be used to create AI models and machine learning applications.
Python can be used for financial modeling and algorithmic trading.
Python can build chatbot and voice assistant applications with NLP.
Python can be used for blockchain development and cryptocurrency
platforms.
Why Learn Python?
Whether you are a beginner or an experienced developer, both have their own
benefits.
For Beginners:
● Easy Syntax: Python syntax is like plain English, which allows you to
focus on logic instead of worrying about complex rules.
● Built-in Libraries for Beginners: Python has beginner friendly libraries
like random, re, os etc, which can be used while learning fundamentals.
● Error Friendly: Python’s error messages are easy to understand and
debug.
● Project Oriented Learning: You can start making simple projects while
learning the Python basics.
For Experienced:
● Easy Career Transition: If you know any other programming language,
moving to Python is super easy.
● Great for Upskilling: Moving to Python expends your skill sets and gives
opportunity to work in areas like AI, Data Science, web development etc.
● High Demand of Python in Emerging tech: Python is widely used in
trending domains, like Data Science, Machine Learning, Cloud Computing
etc.
● Bridge Between Roles: For software developers working with different
language, learning Python can help you integrate advanced features like
AI in your projects.
Limitation of Python
Performance Limitations: Python is an interpreted language which makes it slower
than compiled languages like C++ or Java.
Not preferred for Mobile Apps and Front End: Python isn’t preferred for Front End
dev or mobile apps because of slower execution speeds and limited frameworks
compared to JavaScript or Swift.
Memory Expensive: Python consumes more memory because of its high-level
nature and dynamic typing.
Lack of Strong Typing: Dynamic typing makes Python easy to code, but it can lead
to runtime errors that would be caught at compile time in statically typed languages
like Java or C#.
Not Suitable for Game development: Python lacks the high speed and low-level
hardware control needed for game engines.
Famous Application Build using Python
● YouTube: World’s largest video-sharing platform uses Python for features
like video streaming and backend services.
● Instagram: This popular social media app relies on Python’s simplicity for
scaling and handling millions of users.
● Spotify: Python is used for backend services and machine learning to
personalize music recommendations.
● Dropbox: The file hosting service uses Python for both its desktop client
and server-side operations.
● Netflix: Python powers key components of Netflix’s recommendation
engine and content delivery systems (CDN).
● Google: Python is one of the key languages used in Google for web
crawling, testing, and data analysis.
● Uber: Python helps Uber handle dynamic pricing and route optimization
using machine learning.
● Pinterest: Python is used to process and store huge amounts of image
data efficiently.
List of Companies Using Python
1. Google (Components of Google spider and Search Engine)
2. Yahoo(Maps)
3. YouTube
4. Mozilla
5. Dropbox
6. Microsoft
7. Cisco
8. Spotify
9. Quora
Printing Output using print() in Python
print("Hello, World!")
Printing variables
s = "Hello "
print(s)
Output → Hello
Printing Multiple variables
s = "Alice"
age = 25
city = "New York"
print(s, age, city)
More examples using end and sep function
# end Parameter with '@'
print("Python", end='@')
print("IILM")
# Seprating with Comma
print('I', 'I', 'L', 'M', sep='-')
I-I-L-M
# for formatting a date
print('01', '2025', sep='-')
Output → 01-2025
Printing using f-String
Wrong code
name = 'Tushar'
age = 23
print("Hello, My name is {name} and I'm {age} years old.")
Correct code using f-string function
name = ‘IILM’
age = 10
print(f"Hello, My name is {name} and I'm {age} years old.")
Now what does this f-string function do?
f-strings provides a concise and intuitive way to embed expressions and
variables directly into strings. The idea behind f-strings is to make string
interpolation simpler.
Take Input in Python
# Taking an integer input
integer_input = int(input("Enter an integer: "))
# Taking a string input
string_input = input("Enter a string: ")
# Displaying the outputs
print("The integer entered is:", integer_input)
print("The string entered is:", string_input)
Take Conditional Input from user in Python
# Prompting the user for input
age_input = input("Enter your age: ")
# Converting the input to an integer
age = int(age_input)
# Checking conditions based on user input
if age < 0:
print("Please enter a valid age.")
elif age < 18:
print("You are a minor.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")
Another format
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
Small Project →
Google Text to speech
● Importing Libraries
● Giving input
● Setting up the language
● Creating an object
● Saving the file
● output
Pip install gtts
from gtts import gTTS
import os
# Text you want to convert to speech
text = "Hello, welcome to Google Text to Speech example in
Python!"
# Language for the speech (e.g., 'en' for English)
language = 'en'
# Create a gTTS object
speech = gTTS(text=text, lang=language, slow=False)
# Save the speech to a file
speech.save("output.mp3")
# Play the generated speech (optional, works on many systems)
#os.system("start output.mp3") # For Windows
os.system("open output.mp3") # For macOS
gtts: This is the Google Text-to-Speech library. It allows you to convert text into spoken
audio using Google's Text-to-Speech API.
gTTS: This is the main class in the gtts module that handles the conversion of text into
speech.
Python Variables
What are variables in Python?
Variables act as placeholders for data. They allow us to store and reuse values in our
program.
# Variable 'x' stores the integer value 5
x = 5
# Variable 'name' stores the string "Samantha"
name = "Samantha"
Rules for Naming Variables
To use variables effectively, we must follow Python’s naming rules:
● Variable names can only contain letters, digits and underscores (_).
● A variable name cannot start with a digit.
● Variable names are case-sensitive (myVar and myvar are different).
● Avoid using Python keywords (e.g., if, else, for) as variable names.
Valid Example
age = 21
_colour = "lilac"
total_score = 90
InValid Example
1name = "Error" # Starts with a digit
class = 10 # 'class' is a reserved keyword
user-name = "Doe" # Contains a hyphen
Assigning Values to Variables
Basic Assignment
Variables in Python are assigned values using the = operator.
x = 5
y = 3.14
z = "Hi"
Dynamic Typing
Python variables are dynamically typed, meaning the same variable can hold different types
of values during execution.
x = 10
x = "Now a string"
Multiple Assignments
Python allows multiple variables to be assigned values in a single line.
a = b = c = 100
print(a, b, c)
Assigning Different Values
x, y, z = 1, 2.5, "Python"
print(x, y, z)
Casting a Variable
Casting refers to the process of converting the value of one data type into another.
Python provides several built-in functions to facilitate casting, including int(), float()
and str() among others.
Basic Casting Functions
● int() – Converts compatible values to an integer.
● float() – Transforms values into floating-point numbers.
● str() – Converts any data type into a string.
# Casting variables
s = "10" # Initially a string
n = int(s) # Cast string to integer
cnt = 5
f = float(cnt) # Cast integer to float
age = 25
s2 = str(age) # Cast integer to string
# Display results
print(n)
print(cnt)
print(s2)
Getting the Type of Variable
In Python, we can determine the type of a variable using the type() function. This built-in
function returns the type of the object passed to it.
# Define variables with different data types
n = 42
f = 3.14
s = "Hello, World!"
li = [1, 2, 3]
d = {'key': 'value'}
bool = True
# Get and print the type of each variable
print(type(n))
print(type(f))
print(type(s))
print(type(li))
print(type(d))
print(type(bool))
Scope of a Variable
There are two methods how we define scope of a variable in python which are local
and global.
Variables defined inside a function are local to that function.
def f():
a = "I am local"
print(a)
f()
# print(a) # This would raise an error since 'local_var' is not
accessible outside the function
Global Variables:
Variables defined outside any function are global and can be accessed inside functions
using the global keyword.
a = "I am global"
def f():
global a
a = "Modified globally"
print(a)
f()
print(a)
Practice Problems
1. Swapping Two Variables
a, b = 5, 10
a, b = b, a
print(a, b)
2. Counting Characters in a String
word = "Python"
length = len(word)
print("Length of the word:", length)
KeyWords
Operators
Types of Operators in Python
Arithmetic Operators in Python
# Variables
a = 15
b = 4
# Addition
print("Addition:", a + b)
# Subtraction
print("Subtraction:", a - b)
# Multiplication
print("Multiplication:", a * b)
# Division
print("Division:", a / b)
# Floor Division
print("Floor Division:", a // b)
# Modulus
print("Modulus:", a % b)
Comparison of Python Operators
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Logical Operators in Python
Python Logical operators perform Logical AND, Logical OR and Logical NOT operations. It
is used to combine conditional statements.
The precedence of Logical Operators in Python is as follows:
1. Logical not
2. logical and
3. logical or
Example of Logical Operators in Python:
a = True
b = False
print(a and b)
print(a or b)
print(not a)
Assignment Operators in Python
a = 10
b = a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
Mcqs
1. Which of the following is a valid way to comment in Python?
// This is a comment
# This is a comment
<!-- This is a comment -->
/* This is a comment */
2. What is the result of the following expression in Python: 5 + 2 * 3
21
17
11
1
3. What will be the output of the following code snippet?
a=5
b=2
print(a // b)
2.5
2
2.0
2.00
4. What is the output of the following code?
num1 = "5"
num2 = 3
result = num1 * num2
print(result)
15
“555”
“333”
5. What is the output of the following code?
value = 2 + 3 * 4 / 2
print(value)
4.5
10.0
8.0
12.0
6. What is the output of the following code?
x = "5"
y = "2"
print(x + y)
7
52
10
3
7. Which of the following statements is true about Python variables?
Variables must be declared before they are used.
Variables can contain only letters.
Python variables are case-sensitive.
Python variables cannot be reassigned.
8. Which of the following is the correct way to take user input in Python?
input()
get_input()
user_input()
read_input()
9. Which of the following is the correct type conversion for converting a
floating-point number to an integer in Python?
int(float_num)
integer(float_num)
float_to_int(float_num)
convert_int(float_num)
Python Data Structures
Lists (Mutable, heterogeneous)[]
Python Lists are just like the arrays, declared in other languages which is an ordered
collection of data. It is very flexible as the items in a list do not need to be of the same type.
The implementation of Python List is similar to Vectors in C++ or ArrayList in JAVA. The
costly operation is inserting or deleting the element from the beginning of the List as all the
elements are needed to be shifted. Insertion and deletion at the end of the list can also
become costly in the case where the preallocated memory becomes full.
List = [1, 2, 3, "PYTHON", 2.3]
print(List)
List elements can be accessed by the assigned index. In python starting index of the list,
sequence is 0 and the ending index is (if N elements are there) N-1.
Basic List Operations
# Create a list
fruits = ["apple", "banana", "cherry"]
# Accessing elements
print("First fruit:", fruits[0])
# Adding elements
fruits.append("orange")
print("After adding orange:", fruits)
# Removing elements
fruits.remove("banana")
print("After removing banana:", fruits)
# Slicing a list
print("First two fruits:", fruits[:2])
Find the Largest Number in a List
numbers = [4, 7, 1, 9, 3]
largest = max(numbers)
print("The largest number is:", largest)
Sort a List in Ascending and Descending Order
numbers = [5, 2, 9, 1, 7]
# Sort in ascending order
numbers.sort()
print("Ascending order:", numbers)
# Sort in descending order
numbers.sort(reverse=True)
print("Descending order:", numbers)
Count the Occurrences of an Element
numbers = [1, 2, 3, 1, 2, 1, 4]
count_ones = numbers.count(1)
print("Occurrences of 1:", count_ones)
Tuples(ImMutable, heterogeneous)()
Python Tuple is a collection of Python objects much like a list but Tuples are immutable in
nature i.e. the elements in the tuple cannot be added or removed once created. Just like a
List, a Tuple can also contain elements of various types.
In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or
without the use of parentheses for grouping of the data sequence.
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one
element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a
tuple.
# Creating a Tuple with the use of Strings
Tuple = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple)
# Accessing element using indexing
print("First element of tuple")
print(Tuple[0])
Convert a Tuple to a List and Back
# Tuple to list
numbers = (10, 20, 30)
numbers_list = list(numbers)
print("List:", numbers_list)
# Modify the list
numbers_list.append(40)
# List to tuple
numbers = tuple(numbers_list)
print("Modified tuple:", numbers)
Check if an Element Exists in a Tuple
names = ("Alice", "Bob", "Charlie")
if "Bob" in names:
print("Bob is in the tuple")
else:
print("Bob is not in the tuple")
Unpacking a Tuple
# Tuple unpacking
person = ("John", 25, "Engineer")
name, age, profession = person
print("Name:", name)
print("Age:", age)
print("Profession:", profession)
Dictionary
Python dictionary is like hash tables in any other language with the time complexity of
O(1). It is an unordered collection of data values, used to store data values like a map,
which, unlike other Data Types that hold only a single value as an element, Dictionary holds
the key:value pair. Key-value is provided in the dictionary to make it more optimized.
Indexing of Python Dictionary is done with the help of keys. These are of any hashable type
i.e. an object whose can never change like strings, numbers, tuples, etc. We can create a
dictionary by using curly braces ({}) or dictionary comprehension.
# Create a dictionary
student = {"name": "Alice", "age": 20, "grade": "A"}
# Access a value
print("Name:", student["name"])
# Add a new key-value pair
student["major"] = "Computer Science"
print("Updated dictionary:", student)
# Update an existing value
student["grade"] = "A+"
print("After updating grade:", student)
# Remove a key-value pair
student.pop("age")
print("After removing age:", student)
Iterate Through a Dictionary
# Dictionary of fruits and their prices
fruits = {"apple": 100, "banana": 50, "cherry": 200}
# Iterate through keys and values
for fruit, price in fruits.items():
print(f"The price of {fruit} is {price} rupees")
Count the Frequency of Characters in a String
string = "hello world"
frequency = {}
for char in string:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
print("Character frequency:", frequency)
Merge Two Dictionaries
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
# Merge dictionaries
merged_dict = {**dict1, **dict2}
print("Merged dictionary:", merged_dict)
Set
Python Set is an unordered collection of data that is mutable and does not allow any
duplicate element. Sets are basically used to include membership testing and eliminating
duplicate entries. The data structure used in this is Hashing, a popular technique to perform
insertion, deletion, and traversal in O(1) on average.
# Create a set
colors = {"red", "blue", "green"}
# Add an element
colors.add("yellow")
print("After adding yellow:", colors)
# Remove an element
colors.remove("blue")
print("After removing blue:", colors)
# Check if an element exists
print("Is green in the set?", "green" in colors)
Union, Intersection, and Difference
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Union
print("Union:", set1 | set2)
# Intersection
print("Intersection:", set1 & set2)
# Difference
print("Difference:", set1 - set2)
Remove Duplicates from a List Using a Set
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print("Unique numbers:", unique_numbers)
Find Common Elements in Two Lists
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
# Convert lists to sets and find common elements
common = set(list1) & set(list2)
print("Common elements:", common)
Set Comprehension Example
# Create a set of squares for numbers from 1 to 5
squares = {x**2 for x in range(1, 6)}
print("Squares set:", squares)
Conditional statement in Python
In Python, If-Else is a fundamental conditional statement used for decision-making in
programming. If…Else statement allows to execution of specific blocks of code depending
on the condition is True or False.
if Statement
if statement is the most simple decision-making statement. If the condition evaluates to
True, the block of code inside the if statement is executed.
i = 10
# Checking if i is greater than 15
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
if….else Statement
if…else statement is a control statement that helps in decision-making based on specific
conditions. When the if condition is False. If the condition in the if statement is not true, the
else block will be executed.
i = 20
# Checking if i is greater than 0
if (i > 0):
print("i is positive")
else:
print("i is 0 or Negative")
Using Logical Operators with If..Else:
age = 25
experience = 10
# Using > & 'and' with IF..ELSE
if age > 23 and experience > 8:
print("Eligible.")
else:
print("Not eligible.")
Nested If Else Statement
Nested if…else statement occurs when if…else structure is placed inside another if or else
block. Nested If..else allows the execution of specific code blocks based on a series of
conditional checks.
i = 10
if (i == 10):
# First if statement
if (i < 15):
print("i is smaller than 15")
# Nested - if statement Will only be executed if
statement above it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
else:
print("i is not equal to 10")
Another Program
i = 25
# Checking if i is equal to 10
if (i == 10):
print("i is 10")
# Checking if i is equal to 15
elif (i == 15):
print("i is 15")
# Checking if i is equal to 20
elif (i == 20):
print("i is 20")
# If none of the above conditions are true
else:
print("i is not present")
1. Check if a Number is Positive, Negative, or Zero
num = int(input("Enter a number: "))
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
2. Check if a Number is Even or Odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
3. Find the Largest of Two Numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 > num2:
print(f"The larger number is {num1}.")
elif num1 < num2:
print(f"The larger number is {num2}.")
else:
print("Both numbers are equal.")
4. Check Whether a Year is a Leap Year
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
5. Grade Calculator
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade: A")
elif marks >= 80:
print("Grade: B")
elif marks >= 70:
print("Grade: C")
elif marks >= 60:
print("Grade: D")
else:
print("Grade: F")
Loops in Python – For, While and Nested Loops
Loops in Python are used to repeat actions efficiently. The main types are For loops
(counting through items) and While loops (based on conditions).
For Loop in Python
For loops are used for sequential traversal. For example: traversing a list or string or array
etc. In Python, there is “for in” loop which is similar to foreach loop in other languages.
for iterator_var in sequence:
statements(s)
n = 4
for i in range(0, n):
print(i)
Example with List, Tuple, String, and Dictionary Iteration Using for
Loops in Python
li = ["Python", "Programming", "1styear"]
for i in li:
print(i)
tup = ("Python", "Programming", "1styear")
for i in tup:
print(i)
s = "Programming"
for i in s:
print(i)
d = dict({'x':123, 'y':354})
for i in d:
print("%s %d" % (i, d[i]))
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i),
Using else Statement with for Loop in Python
list = ["Python", "Programming", "1stYear"]
for index in range(len(list)):
print(list[index])
else:
print("Inside Else Block")
The code iterates through the list and prints each element. After the loop ends it prints
“Inside Else Block” as the else block executes when the loop completes without a break.
1. Print Numbers from 1 to 10
for i in range(1, 11):
print(i)
2. Print the Sum of First N Natural Numbers
n = int(input("Enter a number: "))
sum_n = 0
for i in range(1, n + 1):
sum_n += i
print("Sum of first", n, "natural numbers is:", sum_n)
3. Print the Multiplication Table of a Given Number
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
4. Print All Even Numbers from 1 to N
n = int(input("Enter a number: "))
for i in range(2, n + 1, 2): # Start from 2, increment by 2
print(i)
5. Print Each Character of a String Separately
text = input("Enter a string: ")
for char in text:
print(char)
Nested Loops in Python
Python programming language allows to use one loop inside another loop which is called
nested loop. Following section shows few examples to illustrate the concept.
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
Code
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
While Loop in Python
while expression:
statement(s)
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello Programmers")
Another Program
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello Programmers")
else:
print("In Else Block")
Break:
● Terminates the entire loop immediately.
● Useful for exiting loops early when a condition is met.
● Prevents the execution of any remaining iterations.
● In loops with an else clause, the else part does not execute if break is used.
Continue:
● Skips the rest of the current loop iteration.
● Moves directly to the next iteration.
● Helps in skipping over unwanted elements or conditions without breaking
out of the loop entirely.
● Does not interfere with the loop-else construct (the else block executes if the
loop completes normally).
Functions
Python Functions is a block of statements that return the specific task. The idea is to put
some commonly or repeatedly done tasks together and make a function so that instead of
writing the same code again and again for different inputs, we can do the function calls to
reuse code contained in it over and over again.
Some Benefits of Using Functions
● Increase Code Readability
● Increase Code Reusability
Syntax
Types of Functions in Python
Below are the different types of functions in Python:
● Built-in library function: These are Standard functions in Python that are
available to use.
● User-defined function: We can create our own functions based on our
requirements.
Creating a Function in Python
We can define a function in Python, using the def keyword. We can add any type of
functionalities and properties to it as we require. By the following example, we can
understand how to write a function in Python. In this way we can create Python function
definition by using def keyword.
# A simple Python function
def fun():
print("Welcome to Programming")
Calling a Function in Python
After creating a function in Python we can call it by using the name of the functions Python
followed by parenthesis containing parameters of that particular function. Below is the
example for calling def function Python.
# A simple Python function
def fun():
print("Welcome to Programming")
# Driver code to call a function
fun()
Python Function with Parameters
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
Example Program
def add(num1: int, num2: int) -> int:
"""Add two numbers"""
num3 = num1 + num2
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Example Program
# A simple Python function to check whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)
Types of Python Function Arguments
● Default argument
● Keyword arguments (named arguments)
● Positional arguments
Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided in
the function call for that argument. The following example illustrates Default arguments to
write functions in Python.
# Python program to demonstrate default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Driver code (We call myFun() with only
# argument)
myFun(10)
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the caller
does not need to remember the order of parameters.
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname=’Python’, lastname=’Programming’)
student(lastname=’Programming’, firstname=’Python’)
Positional Arguments
We used the Position argument during the function call so that the first argument (or value)
is assigned to name and the second argument (or value) is assigned to age. By changing the
position, or if you forget the order of the positions, the values can be used in the wrong
places, as shown in the Case-2 example below, where 27 is assigned to the name and
Suraj is assigned to the age.
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
# You will get correct output because argument is given in
order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because argument is not in
order
print("\nCase-2:")
nameAge(27, "Suraj")
Python Scope
A variable is only available from inside the region it is created. This is called scope.
Local Scope
A variable created inside a function belongs to the local scope of that function, and can only
be used inside that function.
def myfunc():
x = 300
print(x)
myfunc()
Function Inside Function
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Global Scope
A variable created in the main body of the Python code is a global variable and belongs to
the global scope. Global variables are available from within any scope, global and local.
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Lamda Functions
A lambda function in Python is a small, anonymous function defined using the lambda
keyword. Unlike regular functions defined using def, lambda functions can have only one
expression.
Syntax of a Lambda Function:
lambda arguments: expression
● lambda is the keyword to define an anonymous function.
● arguments are input values, similar to parameters in a normal function.
● expression is the single operation that is evaluated and returned.
Characteristics of Lambda Functions:
1. Anonymous – They don’t have a name.
2. Single Expression – Can only contain one line of computation.
3. Can Have Multiple Arguments – But still evaluates a single expression.
4. Used for Short Functions – Useful where functions are needed temporarily.
Examples of Lambda Functions
1. Adding Two Numbers
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
2. Finding the Square of a Number
square = lambda x: x * x
print(square(6)) # Output: 36
3. Checking Even or Odd Number
even_or_odd = lambda x: "Even" if x % 2 == 0 else "Odd"
print(even_or_odd(9)) # Output: Odd
4. 4. Using Lambda to Find the Cube of Each Number in a List
numbers = [1, 2, 3, 4, 5]
cubed_numbers = list(map(lambda x: x ** 3, numbers))
print(cubed_numbers) # Output: [1, 8, 27, 64, 125]
Here map is used to apply lamda function in each element of a list even without using for
loop
5. Using Lambda with filter() to Get Even Numbers from a List
numbers = [10, 15, 20, 25, 30]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [10, 20, 30]
filter() selects elements that satisfy the condition in the lambda function.
Problems:
1. Function to Find Sum of Two Numbers
2. Function to Find Factorial of a Number
3. Function to Check if a Number is Even or Odd
4. Function to Find the Maximum of Three Numbers
5. Function to Reverse a String
6. Function to Check if a Number is Prime
7. Function to Count Digits in a Number
8. Function to Find the Sum of Digits of a Number
9. Function to Check if a String is Palindrome
Solution
# 1. Function to Find Sum of Two Numbers
def find_sum(a, b):
return a + b
# 2. Function to Find Factorial of a Number
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
# 3. Function to Check if a Number is Even or Odd
def is_even_or_odd(n):
if n % 2 == 0:
return "Even"
else:
return "Odd"
# 4. Function to Find the Maximum of Three Numbers
def max_of_three(a, b, c):
if a > b:
if a > c:
return a
else:
return c
else:
if b > c:
return b
else:
return c
# 5. Function to Reverse a String
def reverse_string(s):
rev = ""
for char in s:
rev = char + rev # Prepending characters to build the
reversed string
return rev
# 6. Function to Check if a Number is Prime
def is_prime(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
# 7. Function to Count Digits in a Number
def count_digits(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
# 8. Function to Find the Sum of Digits of a Number
def sum_of_digits(n):
total = 0
while n > 0:
total += n % 10
n //= 10
return total
# 9. Function to Check if a String is Palindrome
def is_palindrome(s):
rev = "" # Reverse string variable
for char in s:
rev = char + rev # Building the reversed string
return rev == s # Comparing original and reversed string
# Testing the functions
print(find_sum(10, 5)) # Output: 15
print(factorial(5)) # Output: 120
print(is_even_or_odd(7)) # Output: Odd
print(max_of_three(10, 20, 15)) # Output: 20
print(reverse_string("hello")) # Output: "olleh"
print(is_prime(7)) # Output: True
print(count_digits(12345)) # Output: 5
print(sum_of_digits(123)) # Output: 6
print(is_palindrome("madam")) # Output: True
Python Programms
1. Reverse a String Without Using Built-in Functions
2. Find the Intersection of Two Lists
3. Count Vowels and Consonants in a String
4. Find the Factorial of a Number Using Recursion
5. Check if a String is a Palindrome
Any 3
Strings in Python
A string in Python is a sequence of characters enclosed within single ('),
double ("), or triple (''' """) quotes. Strings are immutable, meaning
their contents cannot be changed once assigned
Length of a String
The len() function is used to find the number of characters in a string.
# Finding the length of a string
s = "Hello, World!"
print(len(s)) # Output: 13
String Concatenation (+ Operator)
Concatenation is the process of joining two or more strings using the +
operator.
# String concatenation
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2 # Adding a space between the words
print(result) # Output: Hello World
String Repetition (* Operator)
The * operator is used to repeat a string multiple times.
# String repetition
s = "Python "
print(s * 3) # Output: Python Python Python
Indexing
● Strings are indexed starting from 0 for the first character and -1 for
the last character.
● Positive indexing moves from left to right.
● Negative indexing moves from right to left.
s = "Python"
print(s[0]) # Output: P (First character)
print(s[-1]) # Output: n (Last character)
print(s[3]) # Output: h (Fourth character)
Slicing
Slicing is used to extract a portion of a string using [start:end:step]
notation:
● start: The starting index (included).
● end: The ending index (excluded).
● step: The step size (optional, default is 1).
s = "Programming"
print(s[0:5]) # Output: Progr (Characters from index 0 to 4)
print(s[:7]) # Output: Program (From start to index 6)
print(s[4:]) # Output: ramming (From index 4 to end)
print(s[::2]) # Output: Pormig (Every second character)
print(s[::-1]) # Output: gnimmargorP (Reversing a string)
Inbuilt Functions for Strings
upper() and lower()
Converts a string to uppercase or lowercase.
s = "Hello World"
print(s.upper()) # Output: HELLO WORLD
print(s.lower()) # Output: hello world
strip(), lstrip(), rstrip()
Removes whitespace (or specified characters) from the
string.
s = " Python "
print(s.strip()) # Output: "Python"
print(s.lstrip()) # Output: "Python "
print(s.rstrip()) # Output: " Python"
replace()
Replaces a substring with another string.
s = "Hello World"
print(s.replace("World", "Python")) # Output: Hello
Python
split() and join()
● split() divides a string into a list based on a
delimiter.
● join() joins elements of a list into a string.
s = "Python is fun"
words = s.split() # Splitting based on space
print(words) # Output: ['Python', 'is', 'fun']
new_s = "-".join(words)
print(new_s) # Output: Python-is-fun
find() and count()
● find() returns the index of the first occurrence of
a substring.
● count() returns the number of times a substring
appears.
s = "Programming in Python"
print(s.find("Python")) # Output: 15
print(s.count("n")) # Output: 3
File Handling: File input and output operations in Python Programming
File handling is an essential aspect of programming that allows users to store and retrieve
data permanently. In Python, file operations are performed using built-in functions such as
open(), read(), write(), and close().
1. Opening a File
Before performing any operation on a file, it must be opened using the open() function.
file_object = open("filename", mode)
2. Writing to a File
To write data into a file, use the write() or writelines() method.
# Open the file in write mode
file = open("sample.txt", "w")
# Writing data to the file
file.write("Hello, this is a sample file.\n")
file.write("Python file handling is easy!")
# Close the file
file.close()
If the file does not exist, Python creates it.
If the file exists, it overwrites the existing content.
3. Reading from a File
To read data from a file, use read(), readline(), or readlines().
Reading the Entire File
# Open the file in read mode
file = open("sample.txt", "r")
# Read entire file content
content = file.read()
# Print file content
print(content)
# Close the file
file.close()
Reading Line by Line
# Open the file in read mode
file = open("sample.txt", "r")
# Read first line
line1 = file.readline()
print("First line:", line1)
# Read second line
line2 = file.readline()
print("Second line:", line2)
# Close the file
file.close()
Reading All Lines into a List
# Open the file in read mode
file = open("sample.txt", "r")
# Read all lines into a list
lines = file.readlines()
# Print lines
for line in lines:
print(line.strip())
# Close the file
file.close()
4. Appending Data to a File
Appending means adding new content without deleting the existing content.
Appending Text to a File
# Open the file in append mode
file = open("sample.txt", "a")
# Append data
file.write("\nAppending new content!")
# Close the file
file.close()
Appending Multiple Lines
# Open the file in append mode
file = open("sample.txt", "a")
# List of new lines
new_lines = ["\nPython makes file handling simple.", "\nAppending
more data."]
# Append multiple lines
file.writelines(new_lines)
# Close the file
file.close()
5. Checking if a File Exists Before Reading
import os
filename = "sample.txt"
# Check if file exists
if os.path.exists(filename):
with open(filename, "r") as file:
print(file.read())
else:
print("File does not exist!")
6. Read and Write Mode ('r+')
with open("example.txt", "r+") as file:
content = file.read()
file.write("\nAdding content using r+ mode.")
# Read the updated file
with open("example.txt", "r") as file:
print(file.read())
r+ (Read and Write Mode)
● Opens an existing file for both reading and writing.
● Does not create a new file if the file does not exist.
● The file pointer starts at the beginning of the file.
● Does not truncate (erase) the file's contents.
● You can read, modify, and write within the file.
7. Write and Read Mode ('w+')
# Write and read mode (overwrites the file)
with open("example.txt", "w+") as file:
file.write("This is new content.")
file.seek(0) # Move cursor to the beginning
print(file.read())
w+ (Write and Read Mode)
● Opens a file for both writing and reading.
● Creates a new file if the file does not exist.
● Truncates (erases) the file if it already exists.
● The file pointer starts at the beginning of the file.
● You can read, modify, and write in the file, but the previous contents are lost.
8. Append and Read Mode ('a+')
# Append and read mode
with open("example.txt", "a+") as file:
file.write("\nAppending in a+ mode.")
file.seek(0) # Move cursor to the beginning
print(file.read())
Summary of When to Use Each Mode
● 'r' → Reading existing files.
● 'w' → Writing (overwrites existing content).
● 'a' → Appending content to an existing file.
● 'x' → Creating a new file (fails if it exists).
● 'r+' → Reading and writing (file must exist).
● 'w+' → Writing and reading (overwrites file).
● 'a+' → Appending and reading (creates if missing).
What is a Class?
A class is a blueprint for creating objects. It defines attributes (variables) and methods
(functions) that operate on those attributes.
What is an Object?
An object is an instance of a class. It holds real values for the attributes defined in the class.
2. Creating a Class and an Object
A class is created using the class keyword, and an object is created by calling the class.
class Car:
def __init__(self, brand, model): # Constructor
self.brand = brand
self.model = model
def display(self):
print(f"Car Brand: {self.brand}, Model: {self.model}")
# Creating an object
car1 = Car("Toyota", "Corolla")
car1.display()
3. Constructors in Python
A constructor is a special method used to initialize an object when it is created.
In Python, the constructor is defined using the __init__ method.
Types of Constructors
1. Non-Parameterized Constructor (Default Constructor)
2. Parameterized Constructor
3.1 Non-Parameterized Constructor
A constructor without parameters initializes an object with default values.
class Person:
def __init__(self): # No parameters
self.name = "John Doe"
self.age = 25
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
# Creating an object
p1 = Person()
p1.display()
3.2 Parameterized Constructor
A constructor with parameters allows passing values while creating an object.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Student Name: {self.name}, Age: {self.age}")
# Creating objects with parameters
s1 = Student("Alice", 20)
s2 = Student("Bob", 22)
s1.display()
s2.display()
4. Summary
● Class: A blueprint for objects.
● Object: An instance of a class.
● Constructor (__init__ method): Used to initialize objects.
● Types of Constructors:
○ Non-Parameterized: No parameters, uses default values.
○ Parameterized: Takes arguments to initialize attributes.
Inheritance in Python
Definition:
Inheritance is a feature in object-oriented programming that allows a new class
(called a child class) to reuse the code from an existing class (called a parent class).
It helps in:
● Code reusability
● Reducing redundancy
Easy maintenance
Types of Inheritance in Python:
● Single Inheritance
● Multiple Inheritance
● Multi-level Inheritance
● Hierarchical Inheritance
Hybrid Inheritance
class Animal:
def sound(self):
print("Animals make sound")
class Dog(Animal): # Dog inherits from Animal
def bark(self):
print("Dog barks")
d = Dog()
d.sound() # Inherited method
d.bark() # Dog's own method
Inbuilt Class Methods and Attributes
Function/Attribute Description
__init__() Constructor method
__str__() String representation
__dict__ Dictionary of object attributes
__class__ Returns class name
type() Tells the type of object
Example
class Student:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Student name is {self.name}"
s = Student("Ravi")
print(s) # Calls __str__()
print(s.__dict__) # Shows {'name': 'Ravi'}
print(s.__class__) # Shows class info
Multi-Level Inheritance
A class inherits from a class that itself inherits from another class.
✅ Example:
Grandfather → Father → Child
The child class indirectly inherits from the grandfather class.
Why use it?
To pass down common behavior through multiple generations of classes.
Example
class A:
def showA(self):
print("Class A")
class B(A):
def showB(self):
print("Class B")
class C(B):
def showC(self):
print("Class C")
obj = C()
obj.showA()
obj.showB()
obj.showC()
Multiple Inheritance
A class inherits from more than one parent class.
✅ Real-life Example:
A Child can inherit properties from both Father and Mother.
Advantage:
Gives flexibility and allows you to combine features from different classes.
Caution:
May lead to confusion when the same method is defined in multiple parent classes —
Python solves this using Method Resolution Order (MRO).
Example
class Father:
def skills(self):
print("Gardening, Cooking")
class Mother:
def hobbies(self):
print("Reading, Painting")
class Child(Father, Mother):
def ownSkill(self):
print("Coding")
c = Child()
c.skills()
c.hobbies()
c.ownSkill()
Method Overriding
When a child class redefines a method of the parent class.
This allows:
● Customizing behavior in child classes
Rewriting logic as needed
✅ Example:
The draw() method in a base class Shape might be overridden in a derived class like Circle
or Rectangle.
Example
class Parent:
def show(self):
print("This is Parent class")
class Child(Parent):
def show(self): # Overriding the method
print("This is Child class")
obj = Child()
obj.show() # Calls overridden method
Data Abstraction
Hiding complex implementation and showing only necessary details using abstract
methods. Python uses the abc module for abstraction.
In Python, abstraction is done using:
● Abstract classes
● Abstract methods
Python Syntax:
We use the abc module and @abstractmethod decorator.
Why use it?
● To force subclasses to implement required methods
● To create a blueprint of what a class should do
Example
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
class Bike(Vehicle):
def start(self):
print("Bike started")
b = Bike()
b.start()
Encapsulation
Encapsulation is the process of wrapping variables and methods into a single unit (class)
and restricting access to some parts of the object.
This is done using:
● Public members: accessible from anywhere
● Private members (prefix __): not directly accessible from outside the class
Why use it?
● Protects data from unauthorized access
● Increases security
Example
class Employee:
def __init__(self):
self.name = "Amit"
self.__salary = 50000 # private attribute
def show(self):
print("Name:", self.name)
print("Salary:", self.__salary)
e = Employee()
❌ Will give error
e.show()
# print(e.__salary)
Polymorphism
Polymorphism means "many forms". In Python, it refers to the ability of different classes to
define methods with the same name but different behavior.
Types:
1. Compile-Time Polymorphism (Not supported in Python like C++)
2. Run-Time Polymorphism (Supported using method overriding and duck typing)
✅ Real-life Example:
A function move() may work for a Car, Bike, and Airplane object, but each will define its
own way of moving.
Example
class Cat:
def sound(self):
print("Meow")
class Dog:
def sound(self):
print("Bark")
for animal in (Cat(), Dog()):
animal.sound() # Same method name, different class behavior
NumPy (Numerical Python) — Introduction
What is NumPy?
NumPy is a powerful library used for numerical computing. It allows us to work with arrays
and perform high-speed mathematical operations.
✅ Why use NumPy?
● Faster and more efficient than Python lists
● Supports multi-dimensional arrays
● Useful functions for statistics, linear algebra, and more
📌 Creating Arrays
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr)
📌Indexing Arrays
print(arr[0]) # Output: 1
print(arr[1:3]) # Output: [2 3]
📌 Using Arrays and Scalars
print(arr + 5) # Add 5 to every element
print(arr * 2) # Multiply each element by 2
📌 Array Transposition
mat = np.array([[1, 2], [3, 4]])
print(mat.T) # Transpose of the matrix
📌 Universal Array Functions
a = np.array([1, 4, 9])
print(np.sqrt(a)) # Square root
print(np.exp(a)) # Exponential
📌 Array Processing
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.add(a, b)) # [5 7 9]
print(np.dot(a, b)) # Dot product
📌 Array Input and Output
np.save('my_array.npy', arr) # Save
loaded_array = np.load('my_array.npy') # Load
print(loaded_array)
Pandas
What is Pandas?
Pandas is a data analysis library that makes it easy to work with structured data like tables.
✅ Why use Pandas?
● Handles large data sets
● Built-in support for CSV, Excel, SQL files
● Useful for data cleaning, transformation, and analysis
📌 Series in Pandas
A Series is like a column in Excel.
import pandas as pd
s = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
print(s)
📌 Index Objects
print(s.index) # Index(['a', 'b', 'c'], dtype='object')
📌 Reindex
s2 = s.reindex(['c', 'a', 'b', 'd'])
print(s2)
📌 Drop Entry
print(s.drop('b')) # Drops the entry with index 'b'
Plotting and Visualization using Matplotlib
What is Matplotlib?
It’s a plotting library to create charts, graphs, and visualizations.
import matplotlib.pyplot as plt
📊 Histogram
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
plt.hist(data)
plt.title("Histogram")
plt.show()
📊 Box Plot
data = [7, 15, 13, 22, 26, 9, 18]
plt.boxplot(data)
plt.title("Box Plot")
plt.show()
📊 Scatter Plot
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.scatter(x, y)
plt.title("Scatter Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()
📊 Bar Graph
labels = ['A', 'B', 'C']
values = [10, 20, 15]
plt.bar(labels, values)
plt.title("Bar Graph")
plt.show()
📊 Line Graph
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
plt.plot(x, y)
plt.title("Line Graph")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
THAT’S IT
ALL THE
BEST FOR
YOUR
EXAMS