0% found this document useful (0 votes)
8 views88 pages

Python Notes

The document provides an introduction to Python, covering its definition, features, and differences between Python 2 and Python 3. It includes instructions for setting up Python, writing and running basic programs, and various practice tasks and test questions related to input/output statements, variables, data types, and operators. Additionally, it offers examples of Python scripts for user interaction, data manipulation, and automation.

Uploaded by

ganesansitan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views88 pages

Python Notes

The document provides an introduction to Python, covering its definition, features, and differences between Python 2 and Python 3. It includes instructions for setting up Python, writing and running basic programs, and various practice tasks and test questions related to input/output statements, variables, data types, and operators. Additionally, it offers examples of Python scripts for user interaction, data manipulation, and automation.

Uploaded by

ganesansitan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CSK

1: Introduction to Python

1.1 What is Python?

Definition & Importance

Python is a high-level, interpreted, dynamically typed, and object-oriented


programming language. It is widely used in:

 Web Development (Flask, Django)


 Data Science & AI (Pandas, NumPy, TensorFlow)
 Automation & Scripting
 Game Development (Pygame)

Features of Python

 Easy to Learn – Simple and readable syntax


 Interpreted – Executes code line by line
 Dynamically Typed – No need to declare variable types
 Object-Oriented – Supports OOP principles
 Platform Independent – Runs on Windows, Mac, Linux
 Rich Library Support – NumPy, Pandas, TensorFlow, etc.

Python 2 vs Python 3

 Python 2 is obsolete, while Python 3 is the current standard.


 Syntax changes:
o Python 2: print "Hello"
o Python 3: print("Hello")

1
CSK

1.2 Setting Up Python

Installing Python & Pip

 Download from [Link].


 Pip is included for package management.

Using Different IDEs

 IDLE – Comes with Python


 VS Code – Lightweight and extensible
 PyCharm – Best for professional development
 Jupyter Notebook – Best for data science

1.3 First Python Program

Writing & Running Python Code

print("Hello, World!")

Run the script using:

python [Link]

Practice Programs

1. Write a Python script that prints "Welcome to Python Programming!".

print("Welcome to Python Programming!")

2
CSK

2. Create a Python script that prints the sum of two numbers.

num1 = 5
num2 = 10
sum_result = num1 + num2
print("Sum:", sum_result)

3. Print "Python is fun!" using different IDEs.

 Run this code in IDLE, VS Code, PyCharm, or Jupyter Notebook

print("Python is fun!")

4. Write a Python program that prints "Learning Python is easy" five


times.

for i in range(5):
print("Learning Python is easy")

5. Print the result of 5 + 10 using Python.

print("Result of 5 + 10:", 5 + 10)

6. Create a program that prints "Today's date" followed by the current


date.

import datetime
print("Today's date:", [Link]())

3
CSK

7. Print "I love Python" with each word on a new line.

print("I\nlove\nPython")

8. Create a Python script that takes user input and prints "Hello, [name]!".

name = input("Enter your name: ")


print(f"Hello, {name}!")

9. Write a script to print the version of Python installed on your system.

import sys
print("Python version:", [Link])

10. Run a Python command directly from the terminal.

Open the terminal and type:

python -c "print('Hello from terminal')"

Tasks

1. Automate a simple task

Write a Python program to greet a user based on the time of the day (Morning,
Afternoon, Evening).

import datetime

hour = [Link]().hour

if hour < 12:


4
CSK

print("Good Morning!")
elif hour < 18:
print("Good Afternoon!")
else:
print("Good Evening!")

2. Basic chatbot

Create a Python script that takes user input and replies with a predefined
message.

user_input = input("How are you today? ")


if "good" in user_input.lower():
print("That's great to hear!")
else:
print("Hope you have a better day!")

3. System check

Write a script to check whether Python is installed on the system and display the
version.

import sys
print("Python is installed. Version:", [Link])

4. Website opener

Write a script that opens a specified website using Python (webbrowser


module).

import webbrowser
[Link]("[Link]

5
CSK

5. System automation

Create a Python program that shuts down the computer using [Link]().

import os
confirm = input("Do you want to shut down the computer? (yes/no): ")
if [Link]() == "yes":
[Link]("shutdown /s /t 10") # For Windows

Test Questions

Multiple Choice Questions (MCQs)

1. Which of the following is NOT a feature of Python?


a) Interpreted
b) Statically Typed
c) Dynamically Typed
d) Platform Independent
2. Which Python version is currently recommended for development?
a) Python 2
b) Python 3
c) Both Python 2 and Python 3
d) None of the above
3. Which function is used to print output in Python?
a) echo()
b) printf()
c) print()
d) display()
4. Which statement is correct about Python variables?
a) Python variables require explicit declaration of data type

6
CSK

b) Python variables are case-sensitive


c) Python does not support variables
d) Variables must always start with a special character

Descriptive Questions

5. Explain the key differences between Python 2 and Python 3.


6. Write a Python script that prints the current date and time.
7. What are the advantages of using Python for programming?
8. Explain why Python is called an interpreted language.
9. How can you check the installed Python version using a script?

2: Input/Output Statements in Python

2.1 Input Statements

What is input()?

The input() function allows users to enter data at runtime. By default, input()
stores data as a string.

Taking User Input -Example 1: Basic Input

name = input("Enter your name: ")


print("Hello, " + name)

Note: The + operator is used for string concatenation.

7
CSK

Converting Input to Different Data Types

Since input() always returns a string, you must convert it if you need another
data type.

Example 2: Integer Input

age = int(input("Enter your age: ")) # Converts string input to an integer


print("Your age is:", age)

Example 3: Float Input

price = float(input("Enter the price of the item: ")) # Converts input to float
print("Price:", price)

Taking Multiple Inputs in a Single Line

Use the split() function to take multiple inputs.

Example 4: Multiple Inputs

x, y = input("Enter two numbers: ").split()


print("First number:", x)
print("Second number:", y)

Note: By default, split() separates values using spaces.

2.2 Output Statements in Python

Using print() to Display Output

Example 5: Basic Print Statement


8
CSK

print("Welcome to Python!")

Example 6: Printing Multiple Values

name = "Alice"
age = 25
print("Name:", name, "Age:", age)

Note: Multiple values can be printed using , in print().

String Formatting Techniques

Example 7: Using f-strings (Python 3.6+)

name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.")

Why use f-strings? They are faster and more readable than .format().

Example 8: Using .format()

print("My name is {} and I am {} years old.".format(name, age))

Example 9: Using % Formatting

print("My name is %s and I am %d years old." % (name, age))

Note: %s is used for strings, and %d is used for integers.

9
CSK

Printing Special Characters & Escape Sequences

Escape sequences allow special characters to be printed.

Example 10: Newline (\n) and Tab (\t)

print("Hello\nWorld!") # Prints on two lines


print("Name:\tAlice") # Adds a tab space

PRACTICE PROGRAMS

1. Take user input for name and age and display it.

name = input("Enter your name: ")


age = input("Enter your age: ")
print(f"Hello {name}, you are {age} years old!")

2. Accept two numbers and print their sum.

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
print("Sum:", num1 + num2)

3. Take a user’s full name as input and print it in reverse.

name = input("Enter your full name: ")


print("Reversed Name:", name[::-1])

4. Print a formatted sentence using f-strings.

city = input("Enter your city: ")


country = input("Enter your country: ")
print(f"You are from {city}, {country}.")
10
CSK

5. Accept three numbers and display their average.

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


print("Average:", (a + b + c) / 3)

6. Accept a string input and print it five times using a loop.

string = input("Enter a string: ")


for _ in range(5):
print(string)

7. Accept a user’s birth year and calculate their age.

birth_year = int(input("Enter your birth year: "))


current_year = 2025
print("Your age is:", current_year - birth_year)

8. Convert a string input to uppercase and lowercase.

text = input("Enter a string: ")


print("Uppercase:", [Link]())
print("Lowercase:", [Link]())

9. Accept a number and check if it is positive, negative, or zero.

num = int(input("Enter a number: "))


if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")

11
CSK

10. Print a welcome message with user details formatted properly.

name = input("Enter your name: ")


age = input("Enter your age: ")
print("Welcome, {}! You are {} years old.".format(name, age))

Tasks

1. Interactive Chatbot

Write a Python program that takes user input and responds with a greeting.

user_name = input("What's your name? ")


print(f"Hello {user_name}, how can I assist you today?")

2. Simple Data Entry System

Write a program that accepts name, age, city and saves it in a dictionary.

user_data = {}
user_data['name'] = input("Enter your name: ")
user_data['age'] = int(input("Enter your age: "))
user_data['city'] = input("Enter your city: ")

print("User Data:", user_data)

3. Temperature Converter

Convert Celsius to Fahrenheit and vice versa.

celsius = float(input("Enter temperature in Celsius: "))


fahrenheit = (celsius * 9/5) + 32

12
CSK

print(f"{celsius}°C is equal to {fahrenheit}°F")

4. Simple Password Protection

Ask for a password before allowing access.

password = "admin123"
user_input = input("Enter password: ")

if user_input == password:
print("Access Granted!")
else:
print("Access Denied!")

5. User Authentication System

Check username and password from stored data.

users = {"admin": "admin123", "user": "password"}


username = input("Enter username: ")
password = input("Enter password: ")

if username in users and users[username] == password:


print("Login Successful!")
else:
print("Invalid Credentials!")

13
CSK

Test Questions

Multiple Choice Questions (MCQs)

1. Which function is used to take user input?


a) scan()
b) input()
c) read()
d) enter()
2. Which method converts a string input to an integer?
a) int()
b) float()
c) str()
d) input()
3. Which operator is used for string concatenation?
a) +
b) -
c) *
d) &

Descriptive Questions

4. Explain the difference between print() and input().


5. Write a Python script that accepts a number and prints its square.
6. How does the split() function work in input()?
7. Write a program that takes user input for three numbers and prints their
sum.

14
CSK

3: Python Basics - Variables, Data Types & Operators

3.1 Variables & Data Types

What is a Variable?

A variable is a named storage location in memory that holds a value. In Python,


variables are dynamically typed, meaning they do not require explicit data type
declarations.

Declaring Variables

x = 10 # Integer
y = 3.14 # Float
z = "Python" # String
is_active = True # Boolean
data = None # NoneType

Note: Variable names are case-sensitive (Name and name are different).

Built-in Data Types in Python

Data Example Description


Type
int x = 10 Whole numbers
float y = 3.14 Decimal numbers
complex z = 2 + 3j Complex numbers
bool flag = True Boolean values (True, False)

15
CSK

str text = "Hi" Text data


list items = [1, 2, 3] Ordered, mutable collection
tuple coords = (1, 2) Ordered, immutable
collection
set colors = {"red", "blue"} Unordered, unique collection
dict user = {"name": "Alice", "age": Key-value pairs
25}

Type Conversion (Casting)

Python allows conversion between different data types using type casting
functions.

Example: Converting Types

a = "100"
b = int(a) # Convert string to integer
c = float(b) # Convert integer to float
d = str(c) # Convert float to string

print(type(a), type(b), type(c), type(d))

3.2 Operators in Python

Operators perform operations on variables and values.

16
CSK

Types of Operators in Python

Operator Type Operators Example


Arithmetic +, -, *, /, //, %, ** 5 + 3, 4 * 2
Relational >, <, >=, <=, ==, != x > y, a == b
Logical and, or, not x > 0 and x < 10
Assignment =, +=, -=, *=, /=, //= x += 5
Bitwise &, ` , ^, ~, <<, >>`
Membership in, not in "a" in "apple"
Identity is, is not x is y

Example: Using Arithmetic Operators

a = 10
b=3

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)

Example: Using Logical Operators

x=5
y = 10
17
CSK

print(x > 0 and y > 0) # True


print(x > 0 or y < 0) # True
print(not (x > y)) # True

PRACTICE PROGRAMS

1. Declare and print all data types in Python.

x = 10 # Integer
y = 3.14 # Float
z = "Python" # String
is_active = True # Boolean
data = None # NoneType
items = [1, 2, 3] # List
coords = (1, 2) # Tuple
colors = {"red", "blue"} # Set
user = {"name": "Alice", "age": 25} # Dictionary

print(type(x), type(y), type(z), type(is_active), type(data))


print(type(items), type(coords), type(colors), type(user))

2. Perform arithmetic operations on two numbers.

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))

print("Sum:", a + b)
print("Difference:", a - b)

18
CSK

print("Product:", a * b)
print("Quotient:", a / b)
print("Remainder:", a % b)

3. Swap two numbers without using a third variable.

a, b = 5, 10
a, b = b, a
print("After swapping: a =", a, "b =", b)

4. Convert an integer to float and vice versa.

num = 10
float_num = float(num)
int_num = int(float_num)

print("Float:", float_num, "Integer:", int_num)

5. Check if a number is even or odd.

num = int(input("Enter a number: "))


if num % 2 == 0:
print("Even number")
else:
print("Odd number")

6. Print the square and cube of a number.

19
CSK

num = int(input("Enter a number: "))


print("Square:", num ** 2)
print("Cube:", num ** 3)

7. Compare two numbers and find the maximum.

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


print("Maximum:", max(a, b))

8. Check if a given number is within a range.

num = int(input("Enter a number: "))


if 1 <= num <= 100:
print("Number is in range")
else:
print("Number is out of range")

9. Use identity operators to check object references.

x = [1, 2, 3]
y=x
print(x is y) # True

10. Perform logical operations and observe the results.

a, b = True, False
print(a and b) # False
print(a or b) # True

20
CSK

print(not a) # False

Tasks

1. Basic calculator using arithmetic operators.


2. Temperature converter (Celsius to Fahrenheit and vice versa).
3. Simple login system using input validation.
4. Check if a given year is a leap year.
5. Currency converter (USD to INR, EUR, etc.).

Test Questions

Multiple Choice Questions (MCQs)

1. Which of the following is a valid variable name in Python?


a) 1var
b) var_name
c) class
d) #variable
2. What is the result of 10 % 3?
a) 3
b) 1
c) 0
d) 10

21
CSK

4: Strings in Python

4.1 What is a String?

A string in Python is a sequence of characters enclosed in single ('), double


("), or triple quotes (''' or """).

string1 = 'Hello'
string2 = "Python"
string3 = '''Multiline
String'''

String Properties

 Immutable: Strings cannot be changed once created.


 Indexing: Each character in a string has an index (starting from 0).
 Slicing: Extracting a part of the string using : notation.

4.2 String Operations

Concatenation (+)

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # John Doe

Repetition (*)

text = "Python! "


print(text * 3) # Python! Python! Python!

22
CSK

Indexing and Slicing

s = "Python"
print(s[0]) # P
print(s[-1]) # n
print(s[1:4]) # yth
print(s[:3]) # Pyt
print(s[2:]) # thon

4.3 String Methods

Python provides many built-in string methods.

Method Description Example


upper() Converts to uppercase "hello".upper() → "HELLO"
lower() Converts to lowercase "HELLO".lower() → "hello"
title() Capitalizes first letter of each "hello world".title() → "Hello World"
word

strip() Removes whitespace from " hello ".strip() → "hello"


ends
replace() Replaces part of the string "hello".replace('h', 'y') → "yello"
split() Splits string into a list "a,b,c".split(',') → ['a', 'b', 'c']
join() Joins elements of a list into a " ".join(['Hello', 'Python']) → "Hello
string Python"

find() Finds a substring index "hello".find('e') → 1


count() Counts occurrences of a "banana".count('a') → 3
substring

23
CSK

4.4 Escape Characters

Escape characters allow inserting special characters inside strings.

Escape Character Description

\n New line

\t Tab

\' Single quote

\" Double quote

\\ Backslash

Example

print("Hello\nPython!") # Prints on two lines


print("I\'m learning Python.") # Prints: I'm learning Python.

PRACTICE PROGRAMS

1. Accept a string input and print its length.

text = input("Enter a string: ")


print("Length:", len(text))

2. Convert a given string to uppercase and lowercase.

text = input("Enter a string: ")


print("Uppercase:", [Link]())
print("Lowercase:", [Link]())
24
CSK

3. Accept a sentence and count the occurrences of a word.

sentence = input("Enter a sentence: ")


word = input("Enter a word to count: ")
print(f"The word '{word}' appears", [Link](word), "times.")

4. Reverse a string using slicing.

text = input("Enter a string: ")


print("Reversed String:", text[::-1])

5. Check if a string is a palindrome.

text = input("Enter a string: ").lower()


if text == text[::-1]:
print("Palindrome!")
else:
print("Not a palindrome.")

6. Extract the first and last word from a sentence.

sentence = input("Enter a sentence: ").split()


print("First word:", sentence[0])
print("Last word:", sentence[-1])

25
CSK

7. Replace all vowels in a string with *.

text = input("Enter a string: ")


vowels = "aeiouAEIOU"
for v in vowels:
text = [Link](v, '*')
print("Modified String:", text)

8. Find the first occurrence of a word in a string.

sentence = input("Enter a sentence: ")


word = input("Enter word to find: ")
index = [Link](word)
if index != -1:
print(f"'{word}' found at index {index}.")
else:
print(f"'{word}' not found.")

9. Count the number of words in a sentence.

sentence = input("Enter a sentence: ")


print("Word count:", len([Link]()))

10. Print a string multiple times using string multiplication.

text = input("Enter a string: ")


n = int(input("Enter number of times to repeat: "))
print(text * n)

26
CSK

Tasks

1. Extract domain from an email address

email = input("Enter your email: ")


domain = [Link]("@")[-1]
print("Domain:", domain)

2. Format a user’s full name properly

first = input("Enter first name: ").strip().capitalize()


last = input("Enter last name: ").strip().capitalize()
print("Formatted Name:", first, last)

3. Convert a comma-separated string to a list

csv_string = input("Enter comma-separated values: ")


csv_list = csv_string.split(",")
print("List:", csv_list)

4. Generate a random password

import random
import string

length = int(input("Enter password length: "))


password = ''.join([Link](string.ascii_letters + [Link], k=length))
print("Generated Password:", password)

27
CSK

5. Check if a sentence contains all letters of the alphabet (pangram)

import string

sentence = input("Enter a sentence: ").lower()


if set(string.ascii_lowercase).issubset(set(sentence)):
print("Pangram!")
else:
print("Not a pangram.")

Test Questions

Multiple Choice Questions (MCQs)

1. Which of the following is a correct way to declare a string?


a) str = 'Hello'
b) str = "Hello"
c) str = '''Hello'''
d) All of the above
2. What will print("Python"[2:5]) output?
a) tho
b) Pyt
c) tho
d) yth
3. Which function is used to split a string into a list?
a) split()
b) partition()
c) divide()
d) slice()

28
CSK

4. What is the output of print("Hello".upper())?


a) hello
b) HELLO
c) Hello
d) hELLO
5. Which method removes whitespace from both ends of a string?
a) trim()
b) strip()
c) remove()
d) rstrip()

5: Control Flow in Python

Control flow in Python refers to the order in which statements are executed.
Python provides:

1. Conditional Statements → (if, if-else, if-elif-else)


2. Loops → (for, while)
3. Loop Control Statements → (break, continue, pass)

5.1 Conditional Statements

Conditional statements allow Python to make decisions based on conditions.

1. if Statement

Executes a block of code if a condition is True.

Example

29
CSK

age = int(input("Enter your age: "))


if age >= 18:
print("You are eligible to vote.")

2. if-else Statement

Executes one block if the condition is True and another if False.

Example

num = int(input("Enter a number: "))


if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")

3. if-elif-else (Multiple Conditions)

Checks multiple conditions.

Example

marks = int(input("Enter your marks: "))


if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:

30
CSK

print("Grade: F")

4. Nested if Statements

if statements inside other if statements.

Example

age = int(input("Enter age: "))


if age >= 18:
print("You are an adult.")
if age >= 60:
print("You are also a senior citizen.")
else:
print("You are a minor.")

5.2 Loops in Python

Loops repeat a block of code multiple times.

1. for Loop

Iterates over a sequence (list, string, range, etc.).

Example

for i in range(1, 6):


print("Number:", i)

Note: range(1, 6) generates numbers 1, 2, 3, 4, 5 (excluding 6).

31
CSK

2. while Loop

Repeats as long as the condition is True.

Example

num = 1
while num <= 5:
print("Count:", num)
num += 1

5.3 Loop Control Statements

Statement Description

break Exits the loop immediately

continue Skips the current iteration and moves to the next one

pass Acts as a placeholder, does nothing

1. break Statement (Exit Loop)

for num in range(1, 10):


if num == 5:
break # Stops the loop when num == 5
print(num)

Output: 1 2 3 4

32
CSK

2. continue Statement (Skip Iteration)

for num in range(1, 6):


if num == 3:
continue # Skips when num == 3
print(num)

Output: 1 2 4 5

3. pass Statement (Placeholder)

for num in range(1, 6):


if num == 3:
pass # Does nothing, used as a placeholder
print(num)

Output: 1 2 3 4 5

PRACTICE PROGRAMS

1. Check if a number is positive, negative, or zero.

num = int(input("Enter a number: "))


if num > 0:
print("Positive Number")
elif num < 0:
print("Negative Number")
else:
print("Zero")

33
CSK

2. Find the largest of three numbers.

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


print("Largest Number:", max(a, b, c))

3. Print numbers from 1 to 10 using a for loop.

for i in range(1, 11):


print(i)

4. Print even numbers from 1 to 20 using a while loop.

num = 2
while num <= 20:
print(num)
num += 2

5. Find the sum of the first N natural numbers using a loop.

n = int(input("Enter N: "))
total = 0
for i in range(1, n + 1):
total += i
print("Sum:", total)

6. Reverse a number using a while loop.

34
CSK

num = int(input("Enter a number: "))


rev = 0
while num > 0:
digit = num % 10
rev = rev * 10 + digit
num //= 10
print("Reversed Number:", rev)

7. Print the multiplication table of a number.

num = int(input("Enter a number: "))


for i in range(1, 11):
print(f"{num} x {i} = {num * i}")

8. Count the number of digits in a number.

num = int(input("Enter a number: "))


count = 0
while num > 0:
num //= 10
count += 1
print("Number of digits:", count)

9. Check if a number is prime.

num = int(input("Enter a number: "))


is_prime = True

35
CSK

if num > 1:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
else:
is_prime = False

print("Prime" if is_prime else "Not Prime")

10. Print Fibonacci series up to N terms.

n = int(input("Enter N: "))
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b

Tasks

1. ATM Withdrawal System

Ask the user for an amount and check if they have sufficient balance.

2. Login System with Multiple Attempts

Allow users three attempts to enter the correct password.

3. Countdown Timer

Create a countdown from a user-specified number.


36
CSK

4. Simple Voting System

Ask users for age and allow voting only if age is 18 or above.

5. Factorial Calculation

Calculate the factorial of a number using a loop.

Test Questions

Multiple Choice Questions (MCQs)

1. Which loop is used when the number of iterations is unknown?


a) for loop
b) while loop
c) do-while loop
d) None of the above
2. What does break do in a loop?
a) Skips one iteration
b) Stops the loop immediately
c) Ignores the current condition
d) Repeats the loop twice
3. What is the output of range(1, 5)?
a) [1, 2, 3, 4]
b) [1, 2, 3, 4, 5]
c) [0, 1, 2, 3, 4]
d) [2, 3, 4]

37
CSK

6: Functions in Python

6.1 What is a Function?

A function is a block of reusable code that performs a specific task. Functions


help in:
✧ Code reusability

✧ Reducing redundancy

✧ Improving readability

6.2 Defining & Calling Functions

Syntax of a Function

def function_name(parameters):
# Function body
return value # Optional

Example: Function Without Parameters

def greet():
print("Hello, welcome to Python!")

greet()

Output:

Hello, welcome to Python!

38
CSK

Example: Function with Parameters

def add(a, b):


return a + b

result = add(5, 10)


print("Sum:", result)

Output:

Sum: 15

Example: Function with Default Parameters

def power(base, exponent=2): # Default exponent is 2


return base ** exponent

print(power(3)) # 3^2 = 9
print(power(3, 3)) # 3^3 = 27

Example: Function with Keyword Arguments

def display(name, age):


print(f"Name: {name}, Age: {age}")

display(age=25, name="Alice") # Order doesn't matter

39
CSK

6.3 Advanced Function Concepts

1. Variable-Length Arguments (*args)

*args allows passing multiple arguments.

def add_numbers(*numbers):
return sum(numbers)

print(add_numbers(2, 3, 5, 7)) # Output: 17

2. Keyword Variable-Length Arguments (**kwargs)

**kwargs allows passing multiple keyword arguments.

def person_info(**info):
for key, value in [Link]():
print(f"{key}: {value}")

person_info(name="John", age=30, city="New York")

3. Lambda (Anonymous) Functions

Lambda functions are one-line functions.

square = lambda x: x ** 2
print(square(4)) # Output: 16

40
CSK

4. map(), filter(), reduce() Functions

 map() applies a function to each element in a list.


 filter() filters elements based on a condition.
 reduce() reduces a list to a single value.

from functools import reduce

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

squared = list(map(lambda x: x ** 2, nums)) # Squares each number


evens = list(filter(lambda x: x % 2 == 0, nums)) # Keeps even numbers
sum_all = reduce(lambda x, y: x + y, nums) # Sum of all numbers

print("Squared:", squared)
print("Evens:", evens)
print("Sum:", sum_all)

Output:

Squared: [1, 4, 9, 16, 25]


Evens: [2, 4]
Sum: 15

5. Recursive Functions

A recursive function calls itself.

def factorial(n):
if n == 1:
return 1
41
CSK

return n * factorial(n - 1)

print(factorial(5)) # Output: 120

PRACTICE PROGRAMS

1. Write a function to find the factorial of a number.

def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)

print(factorial(5)) # Output: 120

2. Write a function to check if a number is even or odd.

def check_even_odd(n):
return "Even" if n % 2 == 0 else "Odd"

print(check_even_odd(7)) # Output: Odd

3. Write a function to find the largest of three numbers.

def find_max(a, b, c):


return max(a, b, c)

print(find_max(10, 25, 7)) # Output: 25

42
CSK

4. Write a function to reverse a string.

def reverse_string(s):
return s[::-1]

print(reverse_string("Python")) # Output: nohtyP

5. Write a function that returns the sum of all numbers in a list.

def sum_list(numbers):
return sum(numbers)

print(sum_list([1, 2, 3, 4, 5])) # Output: 15

6. Write a function that returns the square of each number in a list using
map().

def square_list(numbers):
return list(map(lambda x: x ** 2, numbers))

print(square_list([1, 2, 3, 4])) # Output: [1, 4, 9, 16]

7. Write a function to count vowels in a string.

def count_vowels(s):
return sum(1 for char in [Link]() if char in "aeiou")

print(count_vowels("Hello World")) # Output: 3

43
CSK

8. Write a function to check if a string is a palindrome.

def is_palindrome(s):
return s == s[::-1]

print(is_palindrome("madam")) # Output: True

9. Write a function to print the Fibonacci sequence up to n terms.

def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b

fibonacci(5) # Output: 0 1 1 2 3

10. Write a function to count occurrences of a word in a sentence.

def count_word(sentence, word):


return [Link]().split().count([Link]())

print(count_word("Python is fun and Python is powerful", "python")) # Output:


2

44
CSK

Tasks

1. Temperature Converter Function

Write a function that converts temperature between Celsius and Fahrenheit.

2. Basic Calculator using Functions

Create a calculator with add(), subtract(), multiply(), and divide().

3. Password Generator Function

Write a function to generate a random password with uppercase, lowercase,


digits, and symbols.

4. Email Validator

Write a function to check if an email is valid using regex.

5. File Extension Extractor

Write a function that extracts the file extension from a filename.

Test Questions

Multiple Choice Questions (MCQs)

1. Which keyword is used to define a function in Python?


a) func
b) define
c) def
d) lambda

45
CSK

2. What will print(len("Python")) output?


a) 5
b) 6
c) 7
d) Error
3. What does *args allow in a function?
a) Pass multiple values
b) Return multiple values
c) Pass keyword arguments
d) None of the above
4. Which function type has no name?
a) Recursive function
b) Lambda function
c) Nested function
d) Global function

7: Python Data Structures (Lists, Tuples, Sets, Dictionaries)

Python has four built-in data structures that help store and manage data:

1. Lists → Ordered, mutable collection ([ ])


2. Tuples → Ordered, immutable collection (( ))
3. Sets → Unordered, unique collection ({ })
4. Dictionaries → Key-value pairs ({key: value})

46
CSK

7.1 Lists in Python

A list is an ordered, mutable (modifiable) collection that can store multiple


data types.

Creating a List

numbers = [10, 20, 30, 40]


mixed_list = ["apple", 10, 3.14, True]
print(numbers) # Output: [10, 20, 30, 40]
print(mixed_list) # Output: ['apple', 10, 3.14, True]

Accessing List Elements

fruits = ["apple", "banana", "cherry"]


print(fruits[0]) # apple
print(fruits[-1]) # cherry

Modifying List Elements

fruits[1] = "orange"
print(fruits) # ['apple', 'orange', 'cherry']

List Methods

Method Description
append(x) Adds x to the end of the list
insert(i, x) Inserts x at index i
remove(x) Removes the first occurrence of x
pop(i) Removes the element at index i (default: last)
sort() Sorts the list in ascending order
reverse() Reverses the list order
count(x) Returns occurrences of x

47
CSK

Example: Using List Methods

nums = [4, 2, 8, 6]
[Link](10) # [4, 2, 8, 6, 10]
[Link]() # [2, 4, 6, 8, 10]
print(nums)

7.2 Tuples in Python

A tuple is an ordered, immutable collection (cannot be modified after


creation).

Creating a Tuple

my_tuple = (10, 20, 30, "apple")


print(my_tuple)

Accessing Elements

print(my_tuple[1]) # 20
print(my_tuple[-1]) # apple

Tuples are immutable:

my_tuple[1] = 50 # ❌ This will give an error

Tuple Methods

Method Description
count(x) Returns occurrences of x
index(x) Returns the index of x

48
CSK

Example: Tuple Methods

t = (1, 2, 3, 4, 2, 2)
print([Link](2)) # Output: 3
print([Link](3)) # Output: 2

7.3 Sets in Python

A set is an unordered, mutable collection that stores unique elements.

Creating a Set

my_set = {1, 2, 3, 4, 4, 5}
print(my_set) # {1, 2, 3, 4, 5} (removes duplicates)

Set Methods

Method Description

add(x) Adds x to the set

remove(x) Removes x from the set

union(set2) Returns a new set with elements from both sets

intersection(set2) Returns common elements

difference(set2) Returns elements in set1 but not in set2

Example: Using Set Methods

A = {1, 2, 3}
B = {3, 4, 5}

print([Link](B)) # {1, 2, 3, 4, 5}

49
CSK

print([Link](B)) # {3}
print([Link](B)) # {1, 2}

7.4 Dictionaries in Python

A dictionary stores key-value pairs.

Creating a Dictionary

student = {"name": "John", "age": 20, "marks": 90}


print(student["name"]) # John

Modifying a Dictionary

student["age"] = 21 # Update value


student["city"] = "New York" # Add new key-value
print(student)

Dictionary Methods

Method Description

keys() Returns all keys

values() Returns all values

items() Returns key-value pairs as tuples

pop(x) Removes key x

update(d2) Merges another dictionary d2

Example: Using Dictionary Methods

student = {"name": "Alice", "age": 22}

50
CSK

print([Link]()) # dict_keys(['name', 'age'])


print([Link]()) # dict_values(['Alice', 22])

PRACTICE PROGRAMS

1. Create a list and print its elements.

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)

2. Find the largest number in a list.

nums = [10, 20, 30, 40]


print("Largest:", max(nums))

3. Convert a list to a tuple.

nums = [1, 2, 3, 4]
num_tuple = tuple(nums)
print(num_tuple)

4. Merge two sets and remove duplicates.

A = {1, 2, 3}
B = {3, 4, 5}
print([Link](B))

5. Create a dictionary and print its keys and values.

student = {"name": "John", "age": 20}


for key, value in [Link]():

51
CSK

print(key, ":", value)

6. Count the occurrences of an element in a list.

nums = [1, 2, 2, 3, 3, 3]
print([Link](3)) # Output: 3

7. Find common elements between two sets.

A = {1, 2, 3}
B = {2, 3, 4}
print([Link](B)) # {2, 3}

8. Create a dictionary from user input.

name = input("Enter name: ")


age = input("Enter age: ")
student = {"name": name, "age": age}
print(student)

9. Remove duplicates from a list using a set.

nums = [1, 2, 2, 3, 3, 3]
unique_nums = list(set(nums))
print(unique_nums)

10. Check if a key exists in a dictionary.

student = {"name": "John", "age": 20}


if "age" in student:
print("Age exists")

52
CSK

Tasks

1. Sort a list of student names.


2. Find the most frequent number in a list.
3. Merge two dictionaries.
4. Count the occurrences of each word in a sentence.
5. Convert a list of tuples into a dictionary.

Test Questions

Multiple Choice Questions (MCQs)

1. Which data structure allows duplicate elements?


a) Tuple
b) Set
c) List
d) Dictionary
2. How do you access a value in a dictionary?
a) [Link]()
b) dict[key]
c) [Link]()
d) [Link]()

53
CSK

8: File Handling in Python

File handling allows Python to read, write, and modify files stored on a
computer. Python provides built-in functions like open(), read(), and write() to
work with files.

8.1 Opening and Closing Files

Syntax for Opening a File

file = open("[Link]", "mode")


Mode Description

'r' Read mode (default). Opens file for reading.

'w' Write mode. Overwrites existing file or creates a new one.

'a' Append mode. Adds new content to the end of the file.

'x' Exclusive creation. Fails if file exists.

'b' Binary mode. Used for non-text files (e.g., images).

Always close the file after use to free system resources!

[Link]()

54
CSK

Example: Opening and Closing a File

file = open("[Link]", "r") # Open file in read mode


content = [Link]()
print(content)
[Link]() # Always close the file!

8.2 Reading Files

Reading the Entire File

file = open("[Link]", "r")


print([Link]()) # Reads entire content
[Link]()

Reading Line by Line

file = open("[Link]", "r")


print([Link]()) # Reads one line
[Link]()

Reading All Lines as a List

file = open("[Link]", "r")


lines = [Link]() # Returns a list of all lines
print(lines)
[Link]()

55
CSK

8.3 Writing to Files

Writing to a File ('w' mode)

file = open("[Link]", "w")


[Link]("Hello, this is a test file.")
[Link]()

Warning: This will overwrite existing content!

Appending to a File ('a' mode)

file = open("[Link]", "a")


[Link]("\nNew line added!")
[Link]()

Appends content instead of overwriting.

8.4 Using with Statement (Best Practice)

The with statement automatically closes the file after reading/writing.

with open("[Link]", "r") as file:


content = [Link]()
print(content) # No need to manually close the file!

8.5 Working with CSV Files

Python provides the csv module for handling CSV files.

56
CSK

Reading a CSV File

import csv

with open("[Link]", "r") as file:


reader = [Link](file)
for row in reader:
print(row)

Writing to a CSV File

import csv

data = [["Name", "Age"], ["Alice", 25], ["Bob", 30]]

with open("[Link]", "w", newline="") as file:


writer = [Link](file)
[Link](data)

PRACTICE PROGRAMS

1. Write a Python program to read a file and print its content.

with open("[Link]", "r") as file:


print([Link]())

2. Count the number of lines in a text file.

with open("[Link]", "r") as file:

57
CSK

print("Number of lines:", len([Link]()))

3. Write a Python program to copy content from one file to another.

with open("[Link]", "r") as source, open("[Link]", "w") as dest:


[Link]([Link]())

4. Write a program to read only the first 10 characters from a file.

with open("[Link]", "r") as file:


print([Link](10)) # Reads first 10 characters

5. Append user input to a file.

text = input("Enter text to append: ")


with open("[Link]", "a") as file:
[Link]("\n" + text)

6. Write a Python program to remove blank lines from a file.

with open("[Link]", "r") as file:


lines = [Link]()

with open("[Link]", "w") as file:


for line in lines:
if [Link](): # Remove blank lines
[Link](line)

58
CSK

7. Write a program to check if a file exists before reading it.

import os

if [Link]("[Link]"):
with open("[Link]", "r") as file:
print([Link]())
else:
print("File not found!")

8. Count the number of words in a text file.

with open("[Link]", "r") as file:


words = [Link]().split()
print("Number of words:", len(words))

9. Write a program to reverse the content of a file.

with open("[Link]", "r") as file:


content = [Link]()

with open("[Link]", "w") as file:


[Link](content[::-1])

10. Extract unique words from a text file and store them in another file.

with open("[Link]", "r") as file:


words = set([Link]().split())

59
CSK

with open("unique_words.txt", "w") as file:


[Link]("\n".join(words))

Tasks

1. Create a log file system that stores logs of user actions.


2. Read a large dataset from a CSV file and process it.
3. Generate a report from a text file and save it as a new file.
4. Write a program that deletes a specific line from a file.
5. Encrypt and decrypt file content before saving.

Test Questions

Multiple Choice Questions (MCQs)

1. What is the default mode for opening a file in Python?


a) 'w'
b) 'r'
c) 'a'
d) 'x'
2. Which method reads the entire file content?
a) readline()
b) readlines()
c) read()
d) open()
3. What will happen if you try to write to a file opened in 'w' mode?
a) Append data to the existing content
b) Overwrite existing content

60
CSK

c) Raise an error if the file exists


d) Do nothing
4. Which statement is true about the with statement?
a) It is used only for writing files
b) It automatically closes the file after execution
c) It must be used with try-except
d) It is slower than open()
5. Which module is used for handling CSV files in Python?
a) json
b) csv
c) fileio
d) txtreader
6. How can you read a file without getting an error if it does not exist?
a) Use try-except
b) Use with open(file, "r")
c) Use [Link]()
d) Use print([Link]())
7. Which file mode should be used to append data without erasing the
content?
a) 'w'
b) 'a'
c) 'r'
d) 'x'
8. How can you check if a file exists before opening it?
a) [Link]("[Link]")
b) open("[Link]")
c) [Link]()
d) None of the above

61
CSK

9: Object-Oriented Programming (OOP) in Python

9.1 Uses, Applications, and Features of OOP

What is OOP?

Object-Oriented Programming (OOP) is a programming paradigm that


organizes code using objects and classes instead of functions and logic.

Features of OOP

1. Encapsulation → Data hiding using private/protected attributes.


2. Inheritance → Reusing attributes and methods in child classes.
3. Polymorphism → Same function name performing different tasks.
4. Abstraction → Hiding implementation details, exposing only relevant
functionalities.
5. Modularity → Organizing code into reusable and independent sections.

Applications of OOP in Python

✧ Game Development → Unity (C#) & Python Pygame.

✧ Web Development → Django and Flask (Object-based Models).

✧ Machine Learning → TensorFlow, Scikit-learn (Class-based models).


✧ GUI Applications → Tkinter, PyQt (UI elements as objects).

✧ Banking Systems → Securely handling customer accounts using


Encapsulation.

62
CSK

9.2 Classes & Objects in Python

✧ What is a Class?

A class is a blueprint for creating objects, defining attributes (variables) and


methods (functions).

✧ What is an Object?

An object is an instance of a class with its own values for attributes but shares
class methods.

Example: Defining a Class and Creating an Object

class Car:
def __init__(self, brand, model, year):
[Link] = brand # Attribute
[Link] = model
[Link] = year

def display_info(self):
print(f"Car: {[Link]} {[Link]} ({[Link]})")

# Creating Objects
car1 = Car("Toyota", "Corolla", 2020)
car2 = Car("Honda", "Civic", 2021)

car1.display_info()
car2.display_info()

63
CSK

Output:

Car: Toyota Corolla (2020)


Car: Honda Civic (2021)

9.3 Instance & Class Variables

Variable Type Definition Scope

Instance Defined inside __init__ and specific Different for each


Variable to each object object

Class Variable Shared among all objects of the class Same for all
objects

Example: Instance vs Class Variables

class Student:
school = "ABC High School" # Class variable

def __init__(self, name, age):


[Link] = name # Instance variable
[Link] = age

student1 = Student("John", 16)


student2 = Student("Alice", 17)

print([Link], [Link]) # John ABC High School


print([Link], [Link]) # Alice ABC High School

64
CSK

9.4 Inheritance in Python (Reusability of Code)

Inheritance allows a child class to reuse attributes and methods from a


parent class.

Type Description

Single Inheritance Child inherits from one parent class.

Multilevel Child inherits from parent, and another child inherits


Inheritance from that child.

Multiple Inheritance A class inherits from multiple parent classes.

Hierarchical Multiple child classes inherit from the same parent.


Inheritance

Hybrid Inheritance Combination of different inheritance types.

1. Single Inheritance

class Animal:
def sound(self):
print("Animals make sounds")

class Dog(Animal):
def bark(self):

65
CSK

print("Dog barks")

dog = Dog()
[Link]()
[Link]()

2. Multilevel Inheritance

class Grandparent:
def family_name(self):
print("Smith Family")

class Parent(Grandparent):
def parent_name(self):
print("John Smith")

class Child(Parent):
def child_name(self):
print("Mike Smith")

child = Child()
child.family_name()
child.parent_name()
child.child_name()

66
CSK

3. Multiple Inheritance

class Father:
def work(self):
print("Father is an engineer")

class Mother:
def care(self):
print("Mother is a teacher")

class Child(Father, Mother):


pass

child = Child()
[Link]()
[Link]()

9.5 Encapsulation in Python (Data Hiding)

Encapsulation prevents direct modification of object attributes using private


and protected access modifiers.

Access Modifier Syntax Access

Public [Link] Accessible anywhere

Protected self._var Accessible in class & subclasses

Private self.__var Accessible only inside the class

67
CSK

Example of Private Variables

class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable

def deposit(self, amount):


self.__balance += amount

def get_balance(self):
return self.__balance

account = BankAccount(1000)
[Link](500)
print(account.get_balance()) # 1500

Direct access to __balance will cause an error!

9.6 Polymorphism in Python

Polymorphism allows the same function name to perform different tasks


based on object types.

1. Method Overriding (Child class redefines parent method)

class Animal:
def make_sound(self):
print("Some generic animal sound")

class Dog(Animal):
68
CSK

def make_sound(self): # Overriding parent method


print("Bark!")

dog = Dog()
dog.make_sound()

2. Method Overloading (Using Default Arguments)

Python does not support method overloading directly, but we can achieve it
using default parameters.

class Math:
def add(self, a, b=0, c=0):
return a + b + c

m = Math()
print([Link](5)) # 5
print([Link](5, 10)) # 15
print([Link](5, 10, 15)) # 30

9.7 Abstraction in Python (Hiding Implementation Details)

Abstract classes cannot be instantiated and act as blueprints for other classes.

from abc import ABC, abstractmethod

class Animal(ABC):
@abstractmethod
def make_sound(self):

69
CSK

pass

class Dog(Animal):
def make_sound(self):
print("Dog barks!")

dog = Dog()
dog.make_sound()

PRACTICE PROGRAMS

1. Create a class Employee and initialize name, age, and salary.


2. Create a class Circle with methods to calculate area and circumference.
3. Implement single inheritance with Vehicle and Car.
4. Write a program demonstrating method overriding.
5. Create an abstract class Shape with Rectangle and Circle as subclasses.
6. Write a program that demonstrates encapsulation using private variables.
7. Write a program using multiple inheritance with Parent1, Parent2, and
Child.
8. Count the number of objects created from a class.
9. Write a program to demonstrate hybrid inheritance.
10. Create a class Book with title, author, and price. Implement a method to
display details.

Tasks

1. Library Management System using OOP.


2. Bank Account System with encapsulation.

70
CSK

3. School Management System using inheritance.


4. Hospital System using abstraction.
5. E-commerce Product System using polymorphism.

MCQs on OOP

1. What is an object in Python?


2. Which keyword is used to define a class?
3. Which OOP principle restricts access to attributes?
4. Which inheritance type has multiple parents?
5. Which access modifier makes a variable private?
6. What is the purpose of @abstractmethod?
7. How do you define a constructor?
8. What is method overloading?
9. What is the main advantage of encapsulation?
10. Which feature allows reusing code?

9: Exception Handling in Python

9.1 What is Exception Handling?

Exception handling in Python allows us to handle errors gracefully without


crashing the program.

71
CSK

✧ What is an Exception?

An exception is an error that occurs during program execution.

Exception Type Description

ZeroDivisionError Division by zero error

ValueError Invalid type conversion error

FileNotFoundError File does not exist

IndexError Accessing an invalid list index

KeyError Accessing an invalid dictionary key

9.2 Handling Exceptions using try-except

Use try-except to catch exceptions and prevent program crashes.

✧ Basic Syntax

try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception

Example: Handling Division by Zero

72
CSK

try:
x = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")

Output:

Error: Division by zero is not allowed.

Handling Multiple Exceptions

Use multiple except blocks to handle different errors.

try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input! Please enter a number.")

9.3 Using finally Block

The finally block executes no matter what, even if an exception occurs.

try:
file = open("[Link]", "r")
content = [Link]()
except FileNotFoundError:
print("File not found!")

73
CSK

finally:
print("Execution complete.") # This runs no matter what

9.4 Raising Custom Exceptions using raise

Use raise to manually trigger exceptions.

age = int(input("Enter your age: "))


if age < 18:
raise ValueError("Age must be 18 or above.")

1. Handle division by zero error.

try:
x = int(input("Enter a number: "))
print(10 / x)
except ZeroDivisionError:
print("Cannot divide by zero!")

2. Handle invalid input error (ValueError).

try:
num = int(input("Enter a number: "))
print("Valid number:", num)
except ValueError:
print("Invalid input! Please enter a number.")

74
CSK

3. Handle file not found error.

try:
file = open("[Link]", "r")
content = [Link]()
except FileNotFoundError:
print("File not found!")

4. Handle multiple exceptions (ZeroDivisionError & ValueError).

try:
x = int(input("Enter a number: "))
print(10 / x)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input! Enter a number.")

5. Use finally to close a file after reading.

try:
file = open("[Link]", "r")
print([Link]())
except FileNotFoundError:
print("File not found!")
finally:
print("Closing file...")

75
CSK

6. Use raise to manually trigger an exception.

age = int(input("Enter your age: "))


if age < 18:
raise ValueError("Age must be at least 18!")

7. Catch all exceptions using except Exception.

try:
x = 10 / int(input("Enter a number: "))
except Exception as e:
print("An error occurred:", e)

8. Check if a file exists before opening it.

import os
if [Link]("[Link]"):
with open("[Link]", "r") as file:
print([Link]())
else:
print("File does not exist.")

9. Handle KeyError in a dictionary.

try:
person = {"name": "Alice", "age": 25}
print(person["city"]) # Key does not exist
except KeyError:
print("Key not found in dictionary!")
76
CSK

10. Handle IndexError in a list.

try:
my_list = [1, 2, 3]
print(my_list[5]) # Out of range index
except IndexError:
print("Index out of range!")

Tasks

1. Create a login system that raises an error for incorrect credentials.


2. Read and process a CSV file while handling missing values.
3. Web scraping program that handles connection errors.
4. Data validation system that rejects incorrect user inputs.
5. Banking system that prevents overdrawing an account.

(MCQs)

1. What does the try-except block do?


a) Stops execution if an error occurs
b) Ignores errors completely
c) Catches and handles exceptions
d) None of the above

77
CSK

2. Which of the following exceptions occurs when a number is divided


by zero?
a) IndexError
b) ZeroDivisionError
c) ValueError
d) KeyError
3. What will finally do in a try-except-finally block?
a) Execute only if an exception occurs
b) Execute regardless of an exception
c) Only executes if except is skipped
d) None of the above
4. Which keyword is used to manually raise an exception?
a) error
b) throw
c) raise
d) exception
5. Which error occurs when trying to access a non-existent key in a
dictionary?
a) TypeError
b) KeyError
c) NameError
d) ValueError
6. What happens if an exception is not handled?
a) The program continues execution
b) The program crashes
c) The program ignores the error
d) Python fixes it automatically
7. Which function is used to get the error message of an exception?
a) print_exception()
78
CSK

b) [Link]()
c) str(e)
d) error_message()
8. Which type of exception is raised when accessing an index that does
not exist in a list?
a) KeyError
b) TypeError
c) IndexError
d) ValueError
9. How do you handle multiple exceptions in a single block?
a) Using multiple except blocks
b) Using a tuple in except
c) Using except Exception:
d) All of the above
10. Which statement is true about the with statement in file handling?
a) It closes the file automatically
b) It reads a file faster
c) It prevents exceptions
d) It works only in Python 3

10: Modules & Packages in Python

10.1 What is a Module?

A module is a Python file (.py) that contains functions, classes, or variables that
can be reused in other programs.

79
CSK

✧ Creating a Simple Module

Create a file [Link]:

# [Link]
def greet(name):
return f"Hello, {name}!"

Now, import and use it in another script:

import mymodule
print([Link]("Alice")) # Output: Hello, Alice!

10.2 Importing Modules in Python

Different Ways to Import a Module

Syntax Description
import module_name Imports the whole module
from module_name import Imports a specific function
function_name

import module_name as alias Assigns an alias to a module


from module_name import * Imports everything from the module (not
recommended)

Example: Different Import Methods

80
CSK

import math
print([Link](25)) # Output: 5.0

from math import sqrt


print(sqrt(36)) # Output: 6.0

import math as m
print([Link]) # Output: 3.141592653589793

10.3 Built-in Modules in Python

Python has several built-in modules, such as:

Module Usage
math Mathematical operations
random Generating random numbers
datetime Working with dates and times
os Interacting with the operating system
sys Accessing system-specific parameters

Example: Using the math Module

import math
print([Link](5)) # Output: 120
print([Link](2, 3)) # Output: 8.0

10.4 What is a Package?

A package is a collection of multiple modules organized in directories. A


package must contain an __init__.py file to be recognized by Python.
81
CSK

✧ Creating a Package Structure

mypackage/
│── __init__.py
│── [Link]
│── [Link]

✧ Using a Package in Python

from mypackage import module1


module1.function_name()

PRACTICE PROGRAMS

1. Create a module [Link] with basic math functions and import it.

# [Link]
def add(a, b):
return a + b

def subtract(a, b):


return a - b
import calculator
print([Link](5, 3)) # Output: 8

2. Create a module [Link] and import it.

82
CSK

# [Link]
def hello(name):
return f"Hello, {name}!"
from greetings import hello
print(hello("John")) # Output: Hello, John!

3. Use the random module to generate a random number.

import random
print([Link](1, 100)) # Output: Random number between 1-100

4. Use the datetime module to print the current date and time.

from datetime import datetime


print([Link]()) # Output: Current date and time

5. Create a package mypackage with multiple modules and use it.

# mypackage/[Link]
def greet():
return "Hello from module1!"
from mypackage import module1
print([Link]()) # Output: Hello from module1!

6. Use sys module to print command-line arguments.

import sys
print([Link]) # Prints command-line arguments

83
CSK

7. Create a module that calculates the area of a rectangle.

# [Link]
def rectangle(length, width):
return length * width
import area
print([Link](5, 10)) # Output: 50

8. Use the os module to list files in a directory.

import os
print([Link](".")) # Lists files in the current directory

9. Create a module that converts Celsius to Fahrenheit.

# [Link]
def to_fahrenheit(celsius):
return (celsius * 9/5) + 32
import temperature
print(temperature.to_fahrenheit(25)) # Output: 77.0

10. Use math module to calculate the square root of a number.

import math
print([Link](64)) # Output: 8.0

84
CSK

Tasks

1. Create a package ecommerce with modules for cart, checkout, and


payment.
2. Develop a module [Link] that fetches weather information using an
API.
3. Write a module [Link] that handles account transactions (deposit,
withdraw).
4. Build a package analytics with modules for statistics and
data_processing.
5. Create a file_manager.py module that handles file operations (read,
write, delete).

(MCQs)

1. What is a module in Python?


a) A file containing Python code
b) A function inside a class
c) A package of functions
d) A built-in library
2. Which statement correctly imports the math module?
a) import math()
b) import math
c) math import
d) import module math

85
CSK

3. Which of the following is a built-in module?


a) math
b) numpy
c) requests
d) custom_module
4. What is a package in Python?
a) A collection of modules inside a directory
b) A single Python file
c) A function library
d) A built-in module
5. What must a package contain to be recognized by Python?
a) __init__.py
b) [Link]
c) [Link]
d) [Link]
6. Which function is used to generate a random number?
a) [Link]()
b) [Link]()
c) [Link]()
d) [Link]()
7. How do you import a function from a module?
a) import [Link]
b) from module import function
c) from function import module
d) import function from module
8. What does the [Link]() function do?
a) Lists all modules
b) Lists all directories

86
CSK

c) Lists all files in a directory


d) Lists all installed packages
9. Which module is used to work with system arguments?
a) sys
b) os
c) subprocess
d) platform
10. Which of the following statements is true about modules?
a) Modules must be installed separately
b) Modules can only contain functions
c) Modules can be imported into other programs
d) Modules must contain a main() function

87

You might also like