0% found this document useful (0 votes)
2 views39 pages

Programming With Python

Uploaded by

kranthinakka99
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)
2 views39 pages

Programming With Python

Uploaded by

kranthinakka99
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

Programming with Python – 10 Marks Answers

UNIT – 3

1(a) Define Function. Explain Function Creation and Function Calling in Python with
Example Program

Definition of Function

A function is a block of organized and reusable code that performs a specific task. Functions
help in reducing code repetition, improving readability, and making programs modular.

Advantages of Functions

1. Reduces code duplication.

2. Improves readability.

3. Makes debugging easier.

4. Enables code reusability.

5. Simplifies maintenance.

Function Creation in Python

Functions are created using the def keyword.

Syntax

def function_name(parameters):

statement1

statement2

return value

Function Calling

After creating a function, it can be called by using its name followed by parentheses.

Example Program

# Function definition

def add(a, b):


result = a + b

return result

# Function calling

x = 10

y = 20

sum = add(x, y)

print("Sum =", sum)

Output

Sum = 30

Explanation

1. def add(a, b): creates a function named add.

2. The function accepts two arguments.

3. The function calculates the sum.

4. return sends the result back.

5. add(x, y) calls the function.

Conclusion

Functions are essential in Python programming because they divide large programs into
smaller manageable parts.

1(b) Explain Local and Global Variables with Suitable Examples

Local Variables

Variables declared inside a function are called local variables. They can be accessed only
inside that function.

Example

def display():

x = 10
print("Local variable:", x)

display()

Output

Local variable: 10

Global Variables

Variables declared outside all functions are called global variables. They can be accessed
throughout the program.

Example

x = 100

def show():

print("Global variable:", x)

show()

print(x)

Output

Global variable: 100

100

Difference Between Local and Global Variables

Local Variable Global Variable

Declared inside function Declared outside function

Accessible only inside function Accessible throughout program

Temporary lifetime Exists throughout program execution

Conclusion

Local variables improve security while global variables help share data among functions.

2(a) Explain Different Function Arguments with Suitable Examples


Python supports different types of arguments.

1. Positional Arguments

Arguments passed according to position.

def student(name, age):

print(name, age)

student("Ravi", 20)

2. Keyword Arguments

Arguments passed using parameter names.

def student(name, age):

print(name, age)

student(age=20, name="Ravi")

3. Default Arguments

Parameters assigned with default values.

def greet(name="Guest"):

print("Hello", name)

greet()

greet("Sai")

4. Variable Length Arguments

Allows passing multiple arguments.

def total(*numbers):

print(sum(numbers))
total(1,2,3,4)

Advantages

1. Flexibility in function calling.

2. Easier code reuse.

3. Simplifies handling inputs.

Conclusion

Different arguments provide flexibility in Python functions.

2(b) Python Function to Check Common Member in Two Lists

Program

def common_data(list1, list2):

for x in list1:

for y in list2:

if x == y:

return True

return False

list1 = [1, 2, 3, 4]

list2 = [5, 6, 3, 8]

print(common_data(list1, list2))

Output

True

Explanation

1. Nested loops compare elements.

2. If any common element exists, function returns True.


3. Otherwise returns False.

Conclusion

The program demonstrates list comparison using functions.

3(a) Explain Anonymous Functions with Examples

Definition

Anonymous functions are functions without names. They are created using the lambda
keyword.

Syntax

lambda arguments : expression

Example 1

square = lambda x: x*x

print(square(5))

Output

25

Example 2

add = lambda a, b: a+b

print(add(10, 20))

Output

30

Advantages

1. Short and simple.

2. Used for temporary functions.

3. Useful with filter(), map(), reduce().

Conclusion

Lambda functions simplify small operations in Python.

3(b) Explain Keywords: import, from, as


1. import

Used to import an entire module.

import math

print([Link](25))

2. from

Imports specific functions from a module.

from math import sqrt

print(sqrt(16))

3. as

Used to provide an alias name.

import math as m

print([Link](5))

Advantages

1. Reuse existing code.

2. Reduces program complexity.

3. Improves readability.

Conclusion

These keywords help in using modules efficiently.

4(a) List and Explain Standard Modules in Python

Standard Modules

Python provides many built-in modules.

1. math Module

Provides mathematical functions.

import math

print([Link](64))

2. random Module

Generates random numbers.


import random

print([Link](1,10))

3. datetime Module

Handles date and time.

import datetime

print([Link]())

4. os Module

Performs operating system operations.

import os

print([Link]())

Conclusion

Standard modules simplify programming by providing ready-made functions.

4(b) Differentiate Top-Down and Bottom-Up Approaches

Top-Down Approach Bottom-Up Approach

Starts from main problem Starts from smaller modules

Problem divided into subproblems Small modules combined

Uses stepwise refinement Uses integration

Easier for planning Easier for reusable modules

Example of Top-Down

Developing a banking system by first designing overall system and then modules.

Example of Bottom-Up

Creating small modules like login, deposit, withdrawal and integrating them.

Conclusion

Both approaches are useful in software development.

5(a) Explain Advantages of Packages and Procedure to Create Package


Definition

A package is a collection of Python modules.

Advantages

1. Organizes modules.

2. Avoids name conflicts.

3. Improves reusability.

4. Simplifies maintenance.

Procedure to Create Package

1. Create folder.

2. Add __init__.py file.

3. Create modules inside package.

4. Import package.

Example

# [Link]

def add(a,b):

return a+b

from package.module1 import add

print(add(2,3))

Conclusion

Packages help manage large Python projects efficiently.

5(b) Define Recursion and Explain Recursive Functions

Definition

Recursion is a process where a function calls itself repeatedly.

Example – Factorial

def factorial(n):
if n == 1:

return 1

else:

return n * factorial(n-1)

print(factorial(5))

Output

120

Advantages

1. Simplifies complex problems.

2. Useful in tree and graph traversal.

3. Reduces code length.

Disadvantages

1. Uses more memory.

2. Slower execution.

Conclusion

Recursive functions are useful for solving repetitive problems.

UNIT – 4

1(a) Define Inheritance and Explain Types of Inheritance with Examples

Definition

Inheritance is an object-oriented concept in which one class acquires properties and


methods of another class.

Advantages

1. Code reusability.

2. Easy maintenance.

3. Supports hierarchical classification.


Types of Inheritance

1. Single Inheritance

class Parent:

def show(self):

print("Parent class")

class Child(Parent):

pass

obj = Child()

[Link]()

2. Multiple Inheritance

class A:

def display1(self):

print("Class A")

class B:

def display2(self):

print("Class B")

class C(A,B):

pass

3. Multilevel Inheritance

class A:

pass

class B(A):

pass
class C(B):

pass

4. Hierarchical Inheritance

One parent class inherited by many child classes.

Conclusion

Inheritance improves code reusability and modularity.

1(b) Demonstrate Polymorphism Using Python Program

Definition

Polymorphism means one function behaving differently in different situations.

Example

class Bird:

def sound(self):

print("Bird sound")

class Parrot(Bird):

def sound(self):

print("Parrot speaks")

class Crow(Bird):

def sound(self):

print("Crow caws")

p = Parrot()

c = Crow()

[Link]()
[Link]()

Output

Parrot speaks

Crow caws

Conclusion

Polymorphism increases flexibility in programming.

2(a) Demonstrate Operator Overloading with Example Program

Definition

Operator overloading allows operators to work differently for user-defined objects.

Example

class Number:

def __init__(self, value):

[Link] = value

def __add__(self, other):

return [Link] + [Link]

n1 = Number(10)

n2 = Number(20)

print(n1 + n2)

Output

30

Conclusion

Operator overloading improves readability and flexibility.

2(b) Demonstrate File Operations with Suitable Python Program


File Operations

1. Create file

2. Write data

3. Read data

4. Append data

5. Close file

Program

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

[Link]("Hello Python")

[Link]()

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

print([Link]())

[Link]()

Output

Hello Python

Conclusion

File handling is used for permanent data storage.

3(a) Demonstrate Design with Classes Using Case Study

Case Study – Student Management System

Program

class Student:

def __init__(self, name, marks):

[Link] = name

[Link] = marks

def display(self):
print("Name:", [Link])

print("Marks:", [Link])

s1 = Student("Sai", 95)

[Link]()

Output

Name: Sai

Marks: 95

Explanation

1. Class defines blueprint.

2. Object stores student data.

3. Method displays information.

Conclusion

Classes help model real-world entities.

3(b) Explain write() and writelines() with Examples

write()

The write() function writes a single string into a file.

Example

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

[Link]("Hello Python")

[Link]()

writelines()

The writelines() function writes multiple strings into a file.

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

lines = ["Python\n", "Java\n", "C\n"]

[Link](lines)

[Link]()

Difference Between write() and writelines()

write() writelines()

Writes single string Writes multiple strings

Accepts string Accepts list of strings

Conclusion

Both methods are used for writing data into files efficiently.

4(a) Demonstrate Log File Writing in Python Program

Introduction

Logging is used to record events, errors, and execution details in programs.

Python provides the logging module for log file management.

Example Program

import logging

[Link](
filename='[Link]',
level=[Link]
)

[Link]("Program Started")
[Link]("Warning Message")
[Link]("Error Occurred")
Explanation

• basicConfig() configures logging.

• filename specifies log file.

• INFO, WARNING, ERROR are logging levels.

Advantages

1. Helps debugging

2. Maintains execution history

3. Tracks runtime errors

Conclusion

Logging is important for software maintenance and error tracking.

4(b) Develop a Program to Read Config Files in Python

Introduction

Configuration files store application settings separately from program code.

Python uses configparser module to read configuration files.

Program

import configparser

config = [Link]()

[Link]('[Link]')

print(config['DEFAULT']['Name'])

Config File
[DEFAULT]
Name = Python Programming

Output

Python Programming

Advantages

1. Easy configuration management

2. Separates settings from code

3. Simplifies maintenance

Conclusion

Config files improve flexibility and maintainability of applications.

5(a) Demonstrate read(), readline(), and readlines()

Introduction

Python provides different functions to read file contents.

1. read()

Reads complete file content.

Example

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

print([Link]())

[Link]()

2. readline()

Reads one line at a time.


Example

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

print([Link]())

[Link]()

3. readlines()

Reads all lines into a list.

Example

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

print([Link]())

[Link]()

Advantages

1. Easy file reading

2. Supports line-by-line processing

3. Useful for text processing

Conclusion

These functions help in efficient file reading operations.

5(b) Explain self, Constructor, Class Variable and Instance Variable

self

self refers to the current object of a class.

Constructor

A constructor is a special method automatically called when an object is created.


Syntax

def __init__(self):

Class Variable

A variable shared among all objects.

Instance Variable

A variable unique to each object.

Example Program

class Student:

college = "ABC College"

def __init__(self, name):


[Link] = name

s1 = Student("Sai")
s2 = Student("Ravi")

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

Output

ABC College
Sai

Explanation

• college is class variable.

• name is instance variable.

• self accesses object variables.

Conclusion
These concepts are fundamental for object-oriented programming.

6(a) List and Explain Object-Oriented Concepts

Introduction

Object-Oriented Programming organizes programs using objects and classes.

Main OOP Concepts

1. Class

Blueprint for creating objects.

2. Object

Instance of a class.

3. Encapsulation

Binding data and methods together.

4. Abstraction

Hiding implementation details.

5. Inheritance

Acquiring properties from another class.

6. Polymorphism

One interface with many forms.

Advantages of OOP

1. Reusability

2. Security

3. Easy maintenance

4. Modularity

Conclusion

OOP concepts improve software quality and simplify program development.


6(b) Different Modes of Opening File in Python and open() Function

File Opening Modes

Mode Meaning

r Read

w Write

a Append

x Create

rb Read Binary

wb Write Binary

open() Function

Used to open files in Python.

Syntax

open(filename, mode)

Example

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

print([Link]())

[Link]()

Explanation

• filename → file name

• mode → operation mode

Conclusion

The open() function is essential for performing file operations in Python.


7(a) Python Program to Create Student Class

Program

class Student:

def __init__(self, name, branch, grade):


[Link] = name
[Link] = branch
[Link] = grade

def display(self):
print("Name:", [Link])
print("Branch:", [Link])
print("Grade:", [Link])

s = Student("Sai", "CSE", "A")

[Link]()

Output

Name: Sai
Branch: CSE
Grade: A

Explanation

• Constructor initializes data.

• Object stores student details.

• display() method prints information.

Conclusion

Classes help organize related data and functions effectively.

7(b) Method Overriding and Method Overloading Concepts

Method Overriding
Child class changes parent class method behavior.

Program

class Parent:
def show(self):
print("Parent Method")

class Child(Parent):
def show(self):
print("Child Method")

obj = Child()

[Link]()

Output

Child Method

Method Overloading

Same method works with different parameters.

Program

class Demo:

def add(self, a, b, c=0):


print(a+b+c)

obj = Demo()

[Link](10,20)
[Link](10,20,30)

Output

30
60

Conclusion
Method overriding modifies inherited behavior, while method overloading increases
flexibility in method usage.

UNIT – 5 (10 Marks Answers)

1(a) List and Explain Any Four Built-in Error Types in Python

Introduction

Errors are problems that occur during program execution. Python provides many built-in
error types to identify different runtime problems.

Errors help programmers debug and correct programs easily.

1. ZeroDivisionError

Occurs when a number is divided by zero.

Example

a = 10
b=0

print(a/b)

Output

ZeroDivisionError: division by zero

2. NameError

Occurs when a variable is used without definition.

Example

print(x)

Output

NameError: name 'x' is not defined

3. TypeError

Occurs when incompatible data types are used together.


Example

a = 10
b = "Python"

print(a + b)

Output

TypeError

4. IndexError

Occurs when invalid index is used in list or tuple.

Example

list1 = [10,20,30]

print(list1[5])

Output

IndexError: list index out of range

Advantages of Built-in Errors

1. Helps debugging

2. Identifies runtime problems

3. Improves program reliability

4. Simplifies error handling

Conclusion

Built-in error types help programmers detect and fix problems efficiently during program
execution.

1(b) Compare Terminal-Based and GUI-Based Programs

Introduction

Programs can be classified into:


1. Terminal-based programs

2. GUI-based programs

Both are used for user interaction.

Terminal-Based Programs

These programs use text commands through command prompt or terminal.

Features

1. Text interface

2. Keyboard input only

3. Faster execution

4. Less memory usage

Example

name = input("Enter name: ")

print("Welcome", name)

GUI-Based Programs

GUI stands for Graphical User Interface.


These programs use windows, buttons, menus, and graphics.

Features

1. User-friendly interface

2. Uses mouse and keyboard

3. Attractive appearance

4. Easy interaction

Example

from tkinter import *

root = Tk()

label = Label(root, text="Welcome")


[Link]()

[Link]()

Difference Between Terminal and GUI Programs

Terminal-Based GUI-Based
Text interface Graphical interface
Keyboard input Mouse and keyboard
Less attractive More attractive
Faster execution More memory usage
Hard for beginners Easy for beginners

Conclusion

GUI programs provide better user interaction, while terminal programs are simpler and
faster.

2(a) Define Exceptions and Explain Exception Handling in Python

Introduction

An exception is an error that occurs during program execution and interrupts normal flow.

Python provides exception handling to manage errors without terminating the program.

Exception Handling

Python uses:

• try

• except

• else

• finally

blocks for handling exceptions.


Syntax

try:
statements

except Exception:
statements

Example Program

try:
a = 10
b=0

print(a/b)

except ZeroDivisionError:
print("Cannot divide by zero")

Output

Cannot divide by zero

Explanation

• try block contains risky code.

• If exception occurs, control moves to except.

• Program execution continues normally.

Advantages of Exception Handling

1. Prevents abnormal termination

2. Improves program reliability

3. Simplifies debugging

4. Handles runtime errors gracefully


Conclusion

Exception handling helps develop secure and reliable Python programs.

2(b) Develop a Python Program to Handle Division by Zero Exception

Program

try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))

result = a / b

print("Result =", result)

except ZeroDivisionError:
print("Division by zero is not allowed")

Sample Output 1

Enter numerator: 10
Enter denominator: 2

Result = 5.0

Sample Output 2

Enter numerator: 10
Enter denominator: 0

Division by zero is not allowed

Explanation

• User inputs two numbers.

• Division operation may generate exception.

• except block handles error safely.


Conclusion

The program demonstrates safe handling of division by zero exception.

3(a) Demonstrate GUI-Based Program Coding with Example

Introduction

Python provides the tkinter module for creating GUI applications.

GUI applications use:

• Windows

• Buttons

• Labels

• Text boxes

for user interaction.

Example Program

from tkinter import *

root = Tk()

[Link]("GUI Program")

label = Label(root, text="Welcome to Python GUI")

[Link]()

button = Button(root, text="Exit", command=[Link])

[Link]()

[Link]()

Explanation

• Tk() creates main window.


• Label() displays text.

• Button() creates button.

• mainloop() runs application.

Advantages of GUI Programs

1. User friendly

2. Attractive interface

3. Easy interaction

4. Better user experience

Conclusion

GUI programming helps create interactive applications in Python.

3(b) How to Create, Raise and Handle User Defined Exceptions in Python

Introduction

Python allows programmers to create their own exceptions called user-defined exceptions.

These exceptions are created using classes derived from Exception.

Program

class AgeError(Exception):
pass

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

try:
if age < 18:
raise AgeError

print("Eligible for voting")

except AgeError:
print("Age is below 18")
Sample Output 1

Enter age: 20

Eligible for voting

Sample Output 2

Enter age: 15

Age is below 18

Explanation

• AgeError is user-defined exception.

• raise keyword generates exception.

• except handles exception.

Advantages

1. Customized error handling

2. Improves readability

3. Useful in large applications

Conclusion

User-defined exceptions improve program control and reliability.

4(a) List and Explain Clean-Up Actions with Examples

Introduction

Cleanup actions are operations executed regardless of whether exception occurs or not.

Python uses finally block for cleanup actions.


Need for Cleanup Actions

1. Closing files

2. Releasing resources

3. Closing database connections

4. Preventing memory leaks

Example Program

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

print([Link]())

except FileNotFoundError:
print("File not found")

finally:
print("File operation completed")

Explanation

• finally block executes always.

• It runs even if exception occurs.

Advantages

1. Ensures proper resource release

2. Improves reliability

3. Prevents resource leakage

Conclusion

Cleanup actions are important for safe and efficient program execution.

4(b) Program to Implement Single Try Block with Multiple Except Blocks
Introduction

Python supports multiple except blocks to handle different exceptions separately.

Program

try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

result = a / b

print("Result =", result)

except ZeroDivisionError:
print("Cannot divide by zero")

except ValueError:
print("Invalid input")

except:
print("Some other error occurred")

Sample Output 1

Enter first number: 10


Enter second number: 2

Result = 5.0

Sample Output 2

Enter first number: 10


Enter second number: 0

Cannot divide by zero

Sample Output 3
Enter first number: abc

Invalid input

Explanation

• Different exceptions are handled separately.

• Improves clarity and debugging.

Advantages

1. Better error handling

2. Easy debugging

3. Improves program reliability

Conclusion

Multiple except blocks make programs robust and fault tolerant.

5(a) Is it Possible to Implement Multiple Exception Blocks in Python Exception Handling?

Introduction

Yes, Python supports multiple exception blocks.

Each exception block handles a specific type of error separately.

Syntax

try:
statements

except Exception1:
statements

except Exception2:
statements
Example Program

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

result = 10 / num

print(result)

except ZeroDivisionError:
print("Cannot divide by zero")

except ValueError:
print("Invalid input")

Sample Output 1

Enter number: 2

5.0

Sample Output 2

Enter number: 0

Cannot divide by zero

Sample Output 3

Enter number: abc

Invalid input

Advantages

1. Separate handling for each error

2. Easier debugging

3. Better reliability
4. Improves readability

Conclusion

Multiple exception blocks improve error handling and program stability.

5(b) Explain the Purpose of else and finally Blocks in Exception Handling

Introduction

Python provides else and finally blocks along with try and except.

These blocks improve program control and cleanup.

else Block

• Executes only when no exception occurs.

• Used for code that should run after successful execution.

finally Block

• Executes always.

• Used for cleanup actions.

Program

try:
a = 10
b=2

result = a / b

except ZeroDivisionError:
print("Division by zero error")

else:
print("Division Successful")
print("Result =", result)
finally:
print("Program Completed")

Output

Division Successful
Result = 5.0
Program Completed

Explanation

• else runs because no exception occurred.

• finally executes in all situations.

Advantages

1. Better program structure

2. Proper resource cleanup

3. Improved readability

4. Reliable execution

Conclusion

The else and finally blocks improve exception handling and ensure proper program
execution.

You might also like