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

12 Marks Python PDF

The document explains conditional statements (if, if-else, if-elif-else, nested if) and iteration statements (while, for, break, continue, pass) in Python, providing syntax and example programs for each. It also covers string operations, fruitful functions, and various list operations including creation, accessing, modifying, and deleting elements, along with the concepts of aliasing and cloning in lists. Each section includes code snippets and explanations to illustrate the concepts effectively.

Uploaded by

asmalar0997
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)
3 views48 pages

12 Marks Python PDF

The document explains conditional statements (if, if-else, if-elif-else, nested if) and iteration statements (while, for, break, continue, pass) in Python, providing syntax and example programs for each. It also covers string operations, fruitful functions, and various list operations including creation, accessing, modifying, and deleting elements, along with the concepts of aliasing and cloning in lists. Each section includes code snippets and explanations to illustrate the concepts effectively.

Uploaded by

asmalar0997
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

12 marks-unit 3

[Link] about the conditional statements (if, if-else, if-elif else, nested if)
in python with flow chart, Syntax and example program

Python Conditions and If statements

Python supports the usual logical conditions from mathematics:

• Equals: a == b

• Not Equals: a != [Link]

• Less than: a < b

• Less than or equal to: a <= b

• Greater than: a > b

• Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if


statements" and loops.

An "if statement" is written by using the if keyword.

Example

If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if
statement to test whether b is greater than a. As a is 33, and b is 200, we
know that 200 is greater than 33, and so we print to screen that "b is greater
than a".

The Elif Keyword


The elif keyword is Python's way of saying "if the previous conditions were not
true, then try this condition".

The elif keyword allows you to check multiple expressions for True and
execute a block of code as soon as one of the conditions evaluates to True.

ExampleGet your own Python Server

a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

In this example a is equal to b, so the first condition is not true, but


the elif condition is true, so we print to screen that "a and b are equal".

The Else Keyword

The else keyword catches anything which isn't caught by the preceding
conditions.

The else statement is executed when the if condition (and any elif conditions)
evaluate to False.

Example

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to
screen that "a is greater than b".

Nested If Statements

You can have if statements inside if statements. This is


called nested if statements.

Example

x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

In this example, the inner if statement only runs if the outer condition (x > 10)
is true.

[Link] about the iteration statements(while, for, break, continue, pass) in


python with flow chart, Syntax and example program

Iteration Statements in Python

Iteration statements are used to execute a block of code repeatedly based on


a condition or sequence. Python provides the following iteration statements:

• while

• for

• break

• continue

• pass
1. While Loop

Definition

A while loop repeatedly executes a block of code as long as the condition is


true.

Syntax

while condition:
statement(s)

Flowchart

Start

Check Condition
↓ ↓
True False
↓ ↓
Execute End

Go back to condition

Example Program

i=1
while i <= 5:
print(i)
i += 1

Output:

12345

2. For Loop

Definition

A for loop is used to iterate over a sequence (list, tuple, string, range, etc.).

Syntax
for variable in sequence:
statement(s)

Flowchart

Start

Initialize sequence

Get next item

Is item available?
↓ ↓
Yes No
↓ ↓
Execute End

Repeat

Example Program

for i in range(1, 6):


print(i)

Output:

12345

3. Break Statement

Definition

break is used to terminate the loop immediately, even if the condition is true.

Syntax

for/while:
if condition:
break

Flowchart
Loop Start

Check condition
↓ ↓
True False
↓ ↓
Break Continue loop

End

Example Program

for i in range(1, 6):


if i == 3:
break
print(i)

Output:

12

4. Continue Statement

Definition

continue skips the current iteration and moves to the next iteration.

Syntax

for/while:
if condition:
continue

Flowchart

Loop Start

Check condition
↓ ↓
True False
↓ ↓
Skip Execute
↓ ↓
Next iteration

Example Program

for i in range(1, 6):


if i == 3:
continue
print(i)

Output:

1245

5. Pass Statement

Definition

pass is a null statement. It does nothing but acts as a placeholder.

Syntax

for/while:
pass

Flowchart

Loop Start

Execute pass

Do nothing

Next iteration / End

Example Program

for i in range(5):
pass
print("Loop completed")
Output:

Loop completed

[Link] about the string operations (methods) with Example programs.

Introduction

A string is a sequence of characters enclosed in quotes (' ', " "). Python
provides many built-in string methods to perform operations like modifying,
searching, and formatting strings.

1. Changing Case Methods

Methods

• upper() – Converts to uppercase

• lower() – Converts to lowercase

• title() – Converts first letter of each word to uppercase

• capitalize() – Capitalizes first character

Example

text = "hello world"

print([Link]())
print([Link]())
print([Link]())
print([Link]())

Output:

HELLO WORLD
hello world
Hello World
Hello world
2. Searching Methods

Methods

• find() – Returns index of first occurrence

• index() – Same as find but gives error if not found

• count() – Counts occurrences

Example

text = "python programming"

print([Link]("pro"))
print([Link]("thon"))
print([Link]("m"))

Output:

7
2
2

3. Checking Methods

Methods

• isalnum() – Checks alphanumeric

• isalpha() – Checks only alphabets

• isdigit() – Checks digits

• islower() / isupper()

Example

text = "Python123"

print([Link]())
print([Link]())
print([Link]())
Output:

True
False
False

4. Replace and Modify Methods

Methods

• replace(old, new) – Replaces substring

• strip() – Removes spaces from both ends

• lstrip() / rstrip()

Example

text = " hello python "

print([Link]())
print([Link]("python", "world"))

Output:

hello python
hello world

5. Splitting and Joining

Methods

• split() – Splits string into list

• join() – Joins list into string

Example

text = "apple,banana,grape"

data = [Link](",")
print(data)
new_text = "-".join(data)
print(new_text)

Output:

['apple', 'banana', 'grape']


apple-banana-grape

6. String Length and Membership

Operations

• len() – Returns length

• in / not in – Membership operators

Example

text = "python"

print(len(text))
print("py" in text)
print("z" not in text)

Output:

6
True
True

7. Formatting Strings

Methods

• format()

• f-strings (modern method)

Example

name = "Sujith"
age = 20
print("My name is {} and age is {}".format(name, age))
print(f"My name is {name} and age is {age}")

Output:

My name is Sujith and age is 20


My name is Sujith and age is 20

4.

Fruitful Functions in Python

Definition

A fruitful function is a function that returns a value after performing some


computation.
It uses the return statement to send the result back to the caller.

Unlike non-fruitful functions (which only print output), fruitful functions


produce a result that can be stored and reused.

Syntax of Fruitful Function

def function_name(parameters):
statements
return value

Flow of Execution (Concept)

Start

Call Function

Execute statements

Return value

Back to caller

End

Key Features

• Uses return statement

• Can return single or multiple values

• Stops execution after return

• Returned value can be stored in a variable

Example 1: Simple Addition Function

def add(a, b):


return a + b

result = add(5, 3)
print("Sum:", result)

Output:

Sum: 8

Example 2: Function Returning Multiple Values

def calculate(a, b):


return a + b, a * b

sum_val, product = calculate(4, 2)

print("Sum:", sum_val)
print("Product:", product)

Output:

Sum: 6
Product: 8

Example 3: Finding Maximum Number


def find_max(a, b):
if a > b:
return a
else:
return b

print("Maximum:", find_max(10, 20))

Output:

Maximum: 20

Example 4: Checking Even or Odd

def is_even(n):
return n % 2 == 0

print(is_even(4))
print(is_even(7))

Output:

True
False

Unit-4
1..Write code snippets in Python to perform the following

(i)Creating the list

(ii)Accessing elements in the list

(iii)Modifying elements in the list

(iv)Deleting the elements in the list

List Operations in Python

Introduction
A list in Python is a mutable data structure used to store multiple elements in
a single variable. Lists are ordered and allow duplicate values.

(i) Creating a List

Explanation

Lists can be created using square brackets [] or the list() constructor.

Code Snippets

# Creating a list with elements


list1 = [10, 20, 30, 40, 50]
print("List1:", list1)

# Creating an empty list


list2 = []
print("Empty List:", list2)

# Creating list using list() function


list3 = list((1, 2, 3))
print("List3:", list3)

(ii) Accessing Elements in a List

Explanation

Elements in a list are accessed using index values.

• Index starts from 0

• Negative indexing is also allowed

Code Snippets

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

# Access using positive index


print("First element:", numbers[0])
print("Third element:", numbers[2])
# Access using negative index
print("Last element:", numbers[-1])

# Access using slicing


print("Sublist:", numbers[1:4])

(iii) Modifying Elements in a List

Explanation

Lists are mutable, so elements can be changed after creation.

Code Snippets

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

# Modify single element


numbers[1] = 25
print("After modification:", numbers)

# Modify multiple elements using slicing


numbers[2:4] = [35, 45]
print("After slicing modification:", numbers)

(iv) Deleting Elements in a List

Explanation

Elements can be removed using del, remove(), or pop().

Code Snippets

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

# Delete using del


del numbers[1]
print("After del:", numbers)

# Remove element by value


[Link](30)
print("After remove:", numbers)

# Remove element using pop()


[Link]()
print("After pop:", numbers)

# Clear all elements


[Link]()
print("After clear:", numbers)

2.. List the various methods for accessing elements in a Python list and also
explain how index-based
access works with an example. Additionally, what are slicing techniques,
and how do they allow you to
retrieve a sublist? Describe how both methods are used to access data from
a list.

Accessing Elements in a Python List

Introduction

A list is an ordered collection of elements. Accessing elements means


retrieving values stored in the list using different techniques such as indexing
and slicing.

Methods for Accessing Elements in a List

1. Index-Based Access

• Uses index position to access elements

• Index starts from 0 (left to right)

• Negative indexing starts from -1 (right to left)

Syntax

list[index]
Example

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

print(numbers[0]) # First element


print(numbers[2]) # Third element
print(numbers[-1]) # Last element

Output

10
30
50

How Index-Based Access Works

• Python assigns an index to each element

• Example:

Index: 0 1 2 3 4
List: 10 20 30 40 50

• numbers[0] → 10

• numbers[-1] → 50

This allows direct and fast access (O(1)) to elements.

2. Slicing Technique

Definition

Slicing is used to retrieve a sublist (portion of a list).

Syntax

list[start : end : step]

• start → starting index (inclusive)

• end → ending index (exclusive)

• step → increment value


Examples

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

print(numbers[1:4]) # Elements from index 1 to 3


print(numbers[:3]) # From beginning to index 2
print(numbers[2:]) # From index 2 to end
print(numbers[::2]) # Every second element

Output

[20, 30, 40]


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

How Slicing Works

Example:

Index: 0 1 2 3 4
List: 10 20 30 40 50

• numbers[1:4] → elements from index 1 to 3

• Output → [20, 30, 40]

End index is not included

3.. Compare and contrast the difference between aliasing and cloninglists.
Illustrate with the suitable examples.

Aliasing vs Cloning in Python Lists

Introduction
In Python, lists can be assigned or copied in different ways.
Two important concepts are aliasing and cloning, which determine how
memory is shared or duplicated.

1. Aliasing

Definition

Aliasing occurs when two or more variables refer to the same list object in
memory.

Key Point

No new list is created; only a new reference is made.

Example Program

list1 = [10, 20, 30]


list2 = list1 # Aliasing

list2[0] = 100

print("List1:", list1)
print("List2:", list2)

Output

List1: [100, 20, 30]


List2: [100, 20, 30]

Explanation

• list1 and list2 point to the same memory location

• Any change in one list affects the other

Diagram (Concept)

list1 ──► [10, 20, 30] ◄── list2

2. Cloning

Definition
Cloning creates a new copy of the list with a different memory location.

Key Point

Changes in one list do not affect the other.

Methods of Cloning

• [Link]()

• Slicing [:]

• list()

Example Program

list1 = [10, 20, 30]


list2 = [Link]() # Cloning

list2[0] = 100

print("List1:", list1)
print("List2:", list2)

Output

List1: [10, 20, 30]


List2: [100, 20, 30]

Another Cloning Example (Slicing)

list1 = [1, 2, 3]
list2 = list1[:]

[Link](4)

print(list1)
print(list2)

Diagram (Concept)
list1 ──► [10, 20, 30]

list2 ──► [10, 20, 30]

Difference Between Aliasing and Cloning

Feature Aliasing Cloning

Memory Same memory location Different memory location

Object creation No new object New object created

Effect of changes Affects both lists Independent

Syntax list2 = list1 [Link](), [:]

Safety Risky (unintended changes) Safe

Advantages & Use Cases

Aliasing

• Saves memory

• Faster (no copying overhead)

• Used when shared data is needed

Cloning

• Prevents accidental modification

• Useful in data processing

• Ensures data integrity

4..Illustrate the ways of crerating the Tuple and the Tuple assignment with
suitable programs.
Tuples in Python

Introduction

A tuple is an ordered and immutable collection of elements in Python.


Tuples are similar to lists but cannot be modified after creation.

Ways of Creating Tuples

1. Using Parentheses ()

t1 = (10, 20, 30)


print(t1)

2. Without Parentheses (Tuple Packing)

t2 = 1, 2, 3
print(t2)

Python automatically packs values into a tuple.

3. Using tuple() Constructor

t3 = tuple([4, 5, 6])
print(t3)

4. Creating a Single Element Tuple

t4 = (10,) # comma is important


print(t4)

Without comma, it is treated as an integer.

5. Creating Empty Tuple

t5 = ()
print(t5)

Tuple Assignment (Packing and Unpacking)

1. Tuple Packing

• Assigning multiple values to a single tuple


t = (10, 20, 30)
print(t)

2. Tuple Unpacking

• Assigning tuple elements to individual variables

t = (10, 20, 30)

a, b, c = t

print(a)
print(b)
print(c)

Output:

10
20
30

3. Multiple Assignment (Without Tuple Keyword)

a, b, c = 1, 2, 3
print(a, b, c)

4. Swapping Variables Using Tuple

a=5
b = 10

a, b = b, a

print("a =", a)
print("b =", b)

5. Using * Operator (Extended Unpacking)

t = (1, 2, 3, 4, 5)

a, *b, c = t
print(a) # first element
print(b) # middle elements as list
print(c) # last element

5..Analyze the difference in memory efficiency between tuples and lists.


How does the immutability of tuples affect their use in Python?

Memory Efficiency and Immutability: Tuples vs Lists in Python

Introduction

Python provides two important data structures:

• List → Mutable (can be changed)

• Tuple → Immutable (cannot be changed)

This difference directly affects memory usage, performance, and usage


scenarios

1. Memory Efficiency Difference

Lists

• Lists are mutable, so Python allocates extra memory to allow


modifications (add/remove elements).

• They store additional information like size and capacity.

• Hence, lists consume more memory.

Tuples

• Tuples are immutable, so Python does not allocate extra memory.

• Stored in a fixed, compact structure.

• Hence, tuples consume less memory than lists.

Example Program (Memory Check)


import sys

list1 = [1, 2, 3, 4, 5]
tuple1 = (1, 2, 3, 4, 5)

print("List size:", [Link](list1))


print("Tuple size:", [Link](tuple1))

Output will show that tuple size < list size

2. Effect of Immutability of Tuples

Immutability Means

• Elements cannot be changed, added, or removed

• Once created, tuple data is fixed

Impact on Usage

(i) Faster Execution

• No need to handle changes → faster than lists

(ii) Safe Data Storage

• Prevents accidental modification

• Useful for constant data

(iii) Can Be Used as Dictionary Keys

d = {(1, 2): "value"} # valid

Lists cannot be used as keys because they are mutable.

(iv) Better Memory Optimization

• Ideal when data does not change

(v) Suitable for Fixed Records

Example:
student = ("Sujith", 20, "CSE")

3. Comparison Table

Feature List Tuple

Mutability Mutable Immutable

Memory Usage More Less

Speed Slower Faster

Modification Allowed Not allowed

Use Case Dynamic data Fixed data

6.. Set1 = {1, 2, 3, 4}


set2 = {3, 4, 5, 6}
Create a python program using above string for the given operations
(i)Add and remove elements from a set.
(ii)Find the intersection of two sets.
(iii)Compare two sets and find out if they are disjoint.
(iv) Find the difference between two sets.
(v) Generate a power set (all possible subsets) of a given set.
(vi)Return a shallow copy of the set.
Develop a python program that allows the user to interactively add new
books to the
dictionary and search for books by title and also uses a while loop to
continuously prompt
the user for actions until they choose to exit the program.

Set Operations in Python

Given Sets

set1 = {1, 2, 3, 4}

set2 = {3, 4, 5, 6}
(i) Add and Remove Elements

[Link](7) # Add element

[Link](2) # Remove element

print("After add/remove:", set1)

(ii) Intersection of Two Sets

intersection = [Link](set2)

print("Intersection:", intersection)

(iii) Check if Sets are Disjoint

print("Are disjoint?", [Link](set2))

(iv) Difference Between Sets

print("Difference (set1 - set2):", [Link](set2))

print("Difference (set2 - set1):", [Link](set1))

(v) Power Set (All Possible Subsets)

def power_set(s):

s = list(s)

result = [[]]

for elem in s:

result += [x + [elem] for x in result]

return result
print("Power set:", power_set(set1))

(vi) Shallow Copy of Set

copy_set = [Link]()

print("Shallow copy:", copy_set)

Interactive Book Dictionary Program

Description

• Add new books (title & author)

• Search books by title

• Runs continuously using while loop until user exits

Program

books = {}

while True:

print("\n1. Add Book")

print("2. Search Book")

print("3. Display All Books")

print("4. Exit")

choice = input("Enter your choice: ")

if choice == '1':

title = input("Enter book title: ")

author = input("Enter author name: ")


books[title] = author

print("Book added successfully!")

elif choice == '2':

title = input("Enter book title to search: ")

if title in books:

print("Author:", books[title])

else:

print("Book not found!")

elif choice == '3':

print("Books in library:")

for title, author in [Link]():

print(title, ":", author)

elif choice == '4':

print("Exiting program...")

break

else:

print("Invalid choice! Try again.")

.
Unit-5
1. Define module and explain the concept in a more detailed way.

Module in Python

Definition

A module in Python is a file containing Python code (functions, variables, and


classes) that can be imported and reused in other programs.

In simple terms, a module is a .py file used to organize and reuse code.

Concept of Modules (Detailed Explanation)

As programs grow larger, writing all code in a single file becomes difficult to
manage.
Modules help in dividing a program into smaller, logical parts, making
development easier.

Why Use Modules?

1. Code Reusability

• Write once, use many times

• Reduces duplication

2. Modularity

• Large programs are divided into smaller files

• Each module performs a specific task

3. Easy Maintenance

• Bugs can be fixed easily in one module

• Improves readability
4. Namespace Separation

• Each module has its own namespace

• Avoids variable/function name conflicts

Types of Modules

1. Built-in Modules

Predefined modules provided by Python.

Example

import math
print([Link](25))

2. User-Defined Modules

Modules created by the programmer.

Creating and Using a Module

Step 1: Create a Module ([Link])

def add(a, b):


return a + b

def greet(name):
return "Hello " + name

Step 2: Use the Module in Another Program

import mymodule

print([Link](10, 5))
print([Link]("Sujith"))

Ways to Import Modules

1. Import Entire Module


import math
print([Link])

2. Import Specific Functions

from math import sqrt


print(sqrt(36))

3. Import with Alias

import math as m
print([Link](49))

4. Import All Members

from math import *


print(sqrt(64))

Working of a Module

• When a module is imported:

o Python executes the module once

o All its functions and variables become available

Use of __name__ Variable

if __name__ == "__main__":
print("Executed directly")

Helps to check whether the file is:

• Run directly

• Imported as a module

Advantages of Modules

• Improves program structure

• Enhances code reuse

• Makes debugging easier


• Supports team development

2. Describe the different file operations available in Python. Explain how


files are opened, read from, written to, and closed. Provide examples to
illustrate each file operation.

File Operations in Python

Introduction

File handling in Python allows us to store data permanently in files instead of


temporary memory. Python provides built-in functions to create, open, read,
write, and close files.

1. Opening a File

Syntax

file = open("filename", "mode")

Common Modes

Mode Description

r Read (default)

w Write (overwrites file)

a Append (adds data)

x Create new file

b Binary mode

Example

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

2. Reading from a File


Methods

• read() → Reads entire file

• readline() → Reads one line

• readlines() → Reads all lines as list

Example

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

content = [Link]()
print(content)

[Link]()

Reading Line by Line

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

print([Link]())
print([Link]())

[Link]()

3. Writing to a File

Explanation

• w mode creates or overwrites a file

• write() is used to insert content

Example

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

[Link]("Hello Python\n")
[Link]("File handling example")

[Link]()
4. Appending to a File

Explanation

• a mode adds data to the end of the file

Example

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

[Link]("\nThis is appended text")

[Link](

5. Closing a File

Explanation

• close() releases system resources

• Important to avoid memory leaks

Example

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


# Perform operations
[Link](

6. Using with Statement (Best Practice)

Explanation

Automatically closes the file after use

Example

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


content = [Link]()
print(content)

7. Complete Example Program


# Writing to file
with open("[Link]", "w") as file:
[Link]("Hello World\n")

# Appending data
with open("[Link]", "a") as file:
[Link]("Appending new line\n")

# Reading data
with open("[Link]", "r") as file:
print([Link]())

3.. List and explain the various types of errors and exceptions in
[Link] between syntax errors and runtime [Link]
examples for any three common exceptions.

Errors and Exceptions in Python

Introduction

Errors and exceptions are problems that occur during the execution of a
program. They can interrupt the normal flow of the program.

Types of Errors in Python

1. Syntax Errors (Compile-Time Errors)

Definition

Errors that occur due to violation of Python syntax rules.

Characteristics

• Detected before execution

• Prevent the program from running

Example
if True
print("Hello")

Missing colon (:) causes a syntax error.

2. Runtime Errors (Exceptions)

Definition

Errors that occur during program execution.

Characteristics

• Program starts but crashes when error occurs

• Called exceptions

3. Logical Errors

Definition

Errors where the program runs but produces incorrect output.

Example

a = 10
b=5
print(a - b) # Intended addition but subtraction use

Common Exceptions in Python

1. ZeroDivisionError

Occurs when dividing by zero.

a = 10
b=0
print(a / b)

2. IndexError

Occurs when accessing invalid index in a list.


lst = [1, 2, 3]
print(lst[5])

3. ValueError

Occurs when invalid value is passed.

num = int("abc"

4. TypeError (Optional Extra)

Occurs when operations are applied to incompatible types.

print(5 + "hello")

Difference Between Syntax Errors and Runtime Exceptions

Feature Syntax Error Runtime Exception

Occurs When Before execution During execution

Cause Wrong syntax Invalid operation

Detection By Python interpreter While running

Execution Program won’t start Program crashes midway

Example Missing : Division by zero

Exception Handling (Brief)

Python uses try-except to handle exceptions.

try:
a = int(input("Enter number: "))
print(10 / a)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input")
4.. Differentiate between a Python module and a Python [Link]
their structure and usage with the help of suitable code [Link]
how modules and packages are imported and organized in Python.

Difference Between Python Module and Package

Introduction

In Python, both modules and packages are used to organize code.

• A module is a single file

• A package is a collection of modules

1. Python Module

Definition

A module is a single Python file (.py) containing functions, variables, or


classes.

Structure of a Module

[Link]

Example ([Link])

def add(a, b):


return a + b

def greet(name):
return "Hello " + name

Using a Module

import mymodule

print([Link](2, 3))
print([Link]("Sujith"))

2. Python Package
Definition

A package is a directory (folder) that contains multiple modules and a special


file __init__.py.

Structure of a Package

mypackage/
__init__.py
[Link]
[Link]

Example

[Link]

def add(a, b):


return a + b

[Link]

def sub(a, b):


return a - b

Using a Package

from mypackage import module1

print([Link](5, 3))

3. Key Differences

Feature Module Package

Definition Single file Collection of modules

Structure .py file Folder with __init__.py

Size Small Large


Feature Module Package

Usage Simple programs Large projects

Example [Link] numpy

4. Importing Modules and Packages

Importing Module

import math
print([Link](16))

Importing Specific Function

from math import sqrt


print(sqrt(25))

Importing from Package

from mypackage.module1 import add


print(add(10, 5))

Using Alias

import math as m
print([Link])

5. Organization of Modules and Packages

• Modules are stored as files

• Packages are stored as directories

• Helps in:

o Code organization

o Avoiding name conflicts

o Managing large applications


6. Advantages

Modules

• Simple and reusable

• Easy to maintain

Packages

• Better organization for large projects

• Supports hierarchical structure

5.. Describe how command-line arguments work in [Link] how the


sys module is used to retrieve
these arguments. Illustrate with a sample Python program that accepts
command-line [Link]
how arguments are accessed and processed in the script.

Command-Line Arguments in Python

Introduction

Command-line arguments are values passed to a Python program when it is


executed from the command line. These arguments allow users to provide
input without using input() during runtime.

How Command-Line Arguments Work

• Arguments are entered after the script name

• They are passed as strings

• Python stores them in a list called [Link]

Syntax (Command Line)

python [Link] arg1 arg2 arg3

Using the sys Module


Definition

The sys module provides access to system-specific parameters and functions,


including command-line arguments.

Accessing Arguments

import sys

print([Link])

Explanation

• [Link] is a list

• [Link][0] → script name

• [Link][1] → first argument

• [Link][2] → second argument

Example Program 1: Display Arguments

import sys

print("Script name:", [Link][0])


print("Arguments:", [Link][1:])

Execution

python [Link] hello 10

Output

Script name: [Link]


Arguments: ['hello', '10']

Example Program 2: Addition of Two Numbers

import sys
a = int([Link][1])
b = int([Link][2])

print("Sum:", a + b)

Execution

python [Link] 5 3

Output

Sum: 8

How Arguments Are Processed

1. Import sys module

2. Access arguments using [Link]

3. Convert arguments if needed (e.g., int())

4. Perform required operations

Important Points

• All arguments are strings by default

• Must convert to appropriate type (int, float)

• Length can be checked using:

len([Link])

Handling Errors

import sys

if len([Link]) != 3:
print("Usage: python [Link] num1 num2")
else:
a = int([Link][1])
b = int([Link][2])
print("Sum:", a + b)
6.. Discuss about packages in detail. Write the steps to create a package.

Introduction

A package in Python is a way of organizing related modules into a directory


(folder).
It helps in managing large programs by grouping similar functionalities
together.

In simple terms:
Package = Folder of Modules

Definition

A package is a collection of Python modules stored in a directory that


contains a special file called __init__.py.

Structure of a Package

mypackage/
__init__.py
[Link]
[Link]
subpackage/
__init__.py
[Link]

__init__.py indicates that the folder is a package (can be empty).

Features of Packages

• Organizes large code into hierarchical structure

• Promotes modularity and reusability

• Avoids name conflicts

• Makes code easy to maintain

Types of Packages
1. Built-in Packages

• Predefined packages in Python


Example: numpy, pandas

2. User-Defined Packages

• Created by programmers for specific applications

Creating a Package (Step-by-Step)

Step 1: Create a Directory

Create a folder named mypackage

Step 2: Add __init__.py File

# can be empty or contain initialization code

Step 3: Create Modules

[Link]

def add(a, b):


return a + b

[Link]

def sub(a, b):


return a - b

Step 4: Use the Package

from mypackage import module1

print([Link](5, 3))

Importing from Packages

1. Import Entire Module

import mypackage.module1
print([Link](2, 3))
2. Import Specific Function

from mypackage.module1 import add


print(add(10, 5))

3. Import with Alias

import mypackage.module1 as m
print([Link](4, 6))

4. Import from Subpackage

from [Link] import module3

Use of __init__.py

• Initializes the package

• Can define variables or functions

• Controls what is imported using __all__

Advantages of Packages

• Better code organization

• Supports large projects

• Improves readability

• Enables code reuse

You might also like