1.
Explain Various Types of Errors with Examples
Introduction
An error is a mistake in a program that causes the program to produce incorrect results or stop
execution. Errors are common during program development and must be identified and corrected.
In Python, errors are mainly classified into three types:
1. Syntax Errors
2. Runtime Errors
3. Logical Errors
1. Syntax Error
Definition
A Syntax Error occurs when the rules (syntax) of Python are violated. The program cannot run until the
error is corrected.
Example
if 5 > 2
print("Hello")
Error
SyntaxError: invalid syntax
Explanation
The colon (:) is missing after the if statement, so Python generates a syntax error.
2. Runtime Error
Definition
A Runtime Error occurs while the program is executing. The program starts running but stops when an
invalid operation occurs.
Example
a = 10
b=0
print(a / b)
Error
ZeroDivisionError: division by zero
Explanation
The program tries to divide a number by zero, which is not allowed.
3. Logical Error
Definition
A Logical Error occurs when the program runs successfully but produces an incorrect output due to
wrong logic.
Example
a = 10
b = 20
print("Sum =", a - b)
Output
Sum = -10
Explanation
The programmer wanted to find the sum but used the subtraction operator (-) instead of addition (+). The
program runs without error but gives the wrong result.
Summary of Errors
Error Type Description
Syntax Error Violates Python grammar rules
Runtime Error Occurs during program execution
Logical Error Produces incorrect output due to wrong logic
Advantages of Error Handling
1. Helps identify mistakes in programs.
2. Improves program reliability.
3. Makes debugging easier.
4. Prevents program failure.
Conclusion
Errors are mistakes that affect program execution. The three main types of errors in Python are Syntax
Errors, Runtime Errors, and Logical Errors. Understanding these errors helps programmers develop
correct and efficient programs.
2. Define Exception. Explain Different Exception Handling Techniques in Python
Introduction
In Python programming, errors may occur during program execution. These errors are called exceptions.
Python provides a mechanism called exception handling to handle these errors and prevent program
termination.
Definition of Exception
An exception is an unwanted or unexpected event that occurs during program execution which disrupts the
normal flow of the program.
Need for Exception Handling
• To prevent program crash.
• To handle runtime errors smoothly.
• To improve program reliability.
• To provide user-friendly error messages.
Exception Handling Techniques in Python
Python uses try-except blocks and related keywords to handle exceptions.
1. try and except block
Definition
The try block contains the code that may cause an error.
The except block handles the error if it occurs.
Syntax
try:
# risky code
except:
# handling code
Example
try:
a = 10
b=0
print(a / b)
except:
print("Cannot divide by zero")
Output
Cannot divide by zero
2. try with specific except
Definition
We can handle specific exceptions separately.
Example
try:
a = int("hello")
except ValueError:
print("Invalid value")
3. try with multiple except blocks
Definition
We can use multiple except blocks to handle different types of exceptions.
Example
try:
a = 10 / 0
b = int("abc")
except ZeroDivisionError:
print("Division error")
except ValueError:
print("Value error")
4. try-except-else block
Definition
The else block runs only if no exception occurs.
Example
try:
a = 10
b=5
print(a / b)
except:
print("Error")
else:
print("No error occurred")
5. try-except-finally block
Definition
The finally block always executes whether an exception occurs or not.
Example
try:
a = 10 / 2
except:
print("Error")
finally:
print("Program completed")
Summary Table
Block Purpose
try Code that may cause error
except Handles error
else Runs if no error
finally Always executes
Conclusion
Exception handling in Python is used to handle runtime errors and prevent program crashes. It uses blocks
like try, except, else, and finally to manage errors efficiently and improve program stability.
3. Can we write try with multiple except statements? Justify your answer with examples.
Introduction
In Python, exceptions may occur due to different types of errors. To handle them properly, Python allows the
use of multiple except blocks with a single try block. This helps in handling different errors separately and
makes the program more efficient and clear.
Answer
Yes, we can write multiple except statements with a single try block in Python.
Each except block handles a specific type of exception.
Syntax
try:
# risky code
except ExceptionType1:
# handling code
except ExceptionType2:
# handling code
Example Program
try:
a = int(input("Enter number: "))
b = int(input("Enter number: "))
print("Result =", a / b)
except ZeroDivisionError:
print("Error: Cannot divide by zero")
except ValueError:
print("Error: Invalid input (enter numbers only)")
Output Cases
Case 1:
Input: 10, 0
Output: Error: Cannot divide by zero
Case 2:
Input: hello
Output: Error: Invalid input (enter numbers only)
Explanation
• If the user enters 0 as denominator, ZeroDivisionError occurs.
• If the user enters non-numeric value, ValueError occurs.
• Each error is handled separately using different except blocks.
• Only the matching exception block executes.
Advantages of Multiple Except Blocks
1. Handles different errors separately.
2. Makes code more clear and readable.
3. Improves program reliability.
4. Helps in debugging easily.
5. Prevents program from crashing.
Conclusion
Yes, Python allows multiple except blocks with a single try block. This feature is very useful to handle
different types of exceptions in a structured way and improves program stability and clarity.
4. Explain Different Built-in Exceptions in Python with Examples
Introduction
In Python, an exception is an error that occurs during program execution. Python provides many built-in
exceptions to handle common errors. These exceptions help programmers easily identify and fix problems in
the program.
Built-in Exceptions in Python
1. ZeroDivisionError
Definition
Occurs when a number is divided by zero.
Example
a = 10
b=0
print(a / b)
Output
ZeroDivisionError: division by zero
2. ValueError
Definition
Occurs when a function receives an argument of correct type but invalid value.
Example
num = int("abc")
Output
ValueError: invalid literal for int()
3. TypeError
Definition
Occurs when an operation is performed on incompatible data types.
Example
a = 10
b = "5"
print(a + b)
Output
TypeError: unsupported operand type(s)
4. IndexError
Definition
Occurs when we try to access an invalid index in a list or tuple.
Example
a = [1, 2, 3]
print(a[5])
Output
IndexError: list index out of range
5. KeyError
Definition
Occurs when a dictionary key is not found.
Example
d = {"name": "Ammu"}
print(d["age"])
Output
KeyError: 'age'
6. NameError
Definition
Occurs when a variable is not defined.
Example
print(x)
Output
NameError: name 'x' is not defined
7. FileNotFoundError
Definition
Occurs when we try to open a file that does not exist.
Example
open("[Link]", "r")
Output
FileNotFoundError: No such file or directory
Summary Table
Exception Cause
ZeroDivisionError Division by zero
ValueError Invalid value
TypeError Wrong data type operation
IndexError Invalid index
KeyError Missing dictionary key
NameError Variable not defined
FileNotFoundError File does not exist
Conclusion
Python provides many built-in exceptions to handle different types of errors during program execution. These
exceptions help in identifying errors clearly and improve program reliability and debugging.
5. How to Create and Raise User Defined Exceptions with Examples
Introduction
In Python, we can create our own exceptions in addition to built-in exceptions. These are called user-defined
exceptions. They are used when built-in exceptions are not suitable for a specific situation.
Definition
A user-defined exception is an exception created by the programmer using a custom class. It is used to
define and handle application-specific errors.
Need of User Defined Exceptions
• To handle specific program rules.
• To make error messages more meaningful.
• To improve program clarity.
• To control program flow based on conditions.
Steps to Create User Defined Exception
Step 1: Create a custom exception class
We create a class that inherits from the built-in Exception class.
Step 2: Raise the exception using raise keyword
We use raise to trigger the exception when a condition is not satisfied.
Syntax
class ErrorName(Exception):
pass
raise ErrorName("Error message")
Example Program
Example: Age Validation
class InvalidAgeError(Exception):
pass
age = int(input("Enter age: "))
if age < 18:
raise InvalidAgeError("You are not eligible to vote")
else:
print("You are eligible to vote")
Output
Case 1:
Input: 16
Output: InvalidAgeError: You are not eligible to vote
Case 2:
Input: 20
Output: You are eligible to vote
Explanation
• A custom exception InvalidAgeError is created.
• If age is less than 18, the exception is raised using raise.
• Otherwise, normal output is displayed.
• This helps enforce rules in the program.
Advantages of User Defined Exceptions
1. Makes error handling specific and meaningful.
2. Improves readability of code.
3. Helps in enforcing business rules.
4. Makes debugging easier.
5. Gives better control over program flow.
Conclusion
User-defined exceptions allow programmers to create custom error types according to application needs.
They are created using a class and raised using the raise keyword, making programs more meaningful and
controlled.
6. Explain Different Clean-up Activities with Suitable Examples
Introduction
In Python, after handling exceptions, it is important to perform some clean-up activities. These are actions
that ensure proper completion of a program, such as closing files, releasing resources, or freeing memory.
Python provides the finally block for clean-up activities.
Definition
Clean-up activities are the tasks performed at the end of program execution to release system resources
properly, whether an exception occurs or not.
These are mainly done using the finally block in exception handling.
Why Clean-up Activities are Needed
• To close opened files properly.
• To release memory and resources.
• To avoid data corruption.
• To ensure smooth program termination.
finally Block
Definition
The finally block is always executed whether an exception occurs or not. It is mainly used for clean-up
activities.
Syntax
try:
# risky code
except:
# handling code
finally:
# cleanup code
Example 1: Basic Clean-up Example
try:
print("Program started")
a = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Cleanup done")
Output
Program started
Cannot divide by zero
Cleanup done
Explanation
Even though an error occurs, the finally block executes.
Example 2: File Handling Clean-up
try:
f = open("[Link]", "w")
[Link]("Hello Python")
except:
print("Error occurred")
finally:
[Link]()
print("File closed successfully")
Explanation
• File is opened and written.
• Even if error occurs, file is still closed in finally block.
Types of Clean-up Activities
1. Closing Files
Ensures no data loss and releases file resources.
2. Releasing Memory
Clears unused resources.
3. Closing Database Connections
Ensures proper database handling.
4. Network Resource Release
Closes network connections safely.
Advantages of Clean-up Activities
1. Prevents resource leakage.
2. Ensures proper program termination.
3. Improves system performance.
4. Maintains data safety.
5. Increases program reliability.
Conclusion
Clean-up activities in Python are performed using the finally block, which executes whether an exception
occurs or not. It is mainly used to release resources like files, memory, and database connections, ensuring
smooth program execution.
7. Explain how to create a GUI application in Python with examples
Introduction
GUI (Graphical User Interface) is a type of interface that allows users to interact with a program using visual
elements like buttons, labels, text boxes, etc. In Python, GUI applications are created using the built-in library
called Tkinter.
Definition
A GUI application is a program that uses graphical components such as windows, buttons, and text fields to
interact with the user instead of using command-line input.
Tkinter in Python
• Tkinter is the standard GUI library in Python.
• It is used to create windows and widgets.
• It is simple and easy to use.
Steps to Create a GUI Application
Step 1: Import Tkinter module
import tkinter as tk
Step 2: Create main window
window = [Link]()
Step 3: Set window title and size
[Link]("My First GUI")
[Link]("300x200")
Step 4: Add widgets (Label, Button, etc.)
Step 5: Run the application loop
[Link]()
Example: Simple GUI Application
import tkinter as tk
window = [Link]()
[Link]("Simple GUI")
[Link]("300x200")
label = [Link](window, text="Welcome to Python GUI")
[Link]()
button = [Link](window, text="Click Me")
[Link]()
[Link]()
Output
A window will open showing:
• A label: Welcome to Python GUI
• A button: Click Me
Common GUI Components (Widgets)
1. Label
Used to display text.
[Link](window, text="Hello")
2. Button
Used to perform actions.
[Link](window, text="Click")
3. Entry
Used to take input from user.
[Link](window)
Example with Input and Button
import tkinter as tk
def show():
name = [Link]()
print("Hello", name)
window = [Link]()
[Link]("Input Example")
entry = [Link](window)
[Link]()
button = [Link](window, text="Submit", command=show)
[Link]()
[Link]()
Explanation
• User enters name in Entry box.
• When button is clicked, function show() runs.
• It prints greeting message.
Advantages of GUI Applications
1. Easy to use for users.
2. Interactive and user-friendly.
3. No need to remember commands.
4. Suitable for real-world applications.
Conclusion
GUI applications in Python are created using the Tkinter library. It allows developers to create windows,
buttons, labels, and input fields easily. GUI makes programs more interactive and user-friendly compared to
command-line programs.
8. Explain Different Widgets Used in GUI Based Applications with Examples
Introduction
In Python, GUI (Graphical User Interface) applications are created using the Tkinter module. In GUI, the user
interacts through different components called widgets such as buttons, labels, text boxes, etc.
Widgets are the building blocks of a GUI application.
Definition
A widget is a graphical element in a GUI application that is used to display information or take input from the
user.
Common Widgets in Tkinter
1. Label Widget
Definition
A Label is used to display text or messages on the window.
Example
import tkinter as tk
window = [Link]()
label = [Link](window, text="Welcome to Python GUI")
[Link]()
[Link]()
2. Button Widget
Definition
A Button is used to perform an action when clicked.
Example
import tkinter as tk
def click():
print("Button Clicked")
window = [Link]()
button = [Link](window, text="Click Me", command=click)
[Link]()
[Link]()
3. Entry Widget
Definition
An Entry widget is used to take single-line input from the user.
Example
import tkinter as tk
window = [Link]()
entry = [Link](window)
[Link]()
[Link]()
4. Text Widget
Definition
A Text widget is used to take multi-line input from the user.
Example
import tkinter as tk
window = [Link]()
text = [Link](window)
[Link]()
[Link]()
5. Checkbutton Widget
Definition
A Checkbutton is used to select multiple options.
Example
import tkinter as tk
window = [Link]()
check = [Link](window, text="Accept Terms")
[Link]()
[Link]()
6. Radiobutton Widget
Definition
A Radiobutton is used to select only one option from multiple choices.
Example
import tkinter as tk
window = [Link]()
var = [Link]()
r1 = [Link](window, text="Male", variable=var, value="Male")
r2 = [Link](window, text="Female", variable=var, value="Female")
[Link]()
[Link]()
[Link]()
7. Listbox Widget
Definition
A Listbox is used to display a list of items from which a user can select.
Example
import tkinter as tk
window = [Link]()
listbox = [Link](window)
[Link](1, "Python")
[Link](2, "Java")
[Link](3, "C++")
[Link]()
[Link]()
Summary of Widgets
Widget Purpose
Label Display text
Widget Purpose
Button Perform action
Entry Single-line input
Text Multi-line input
Checkbutton Multiple selection
Radiobutton Single selection
Listbox List selection
Advantages of Widgets
1. Makes GUI interactive.
2. Easy user input and output.
3. Improves user experience.
4. Used in real-world applications.
Conclusion
Widgets are the basic elements of GUI applications in Python. Using Tkinter widgets like Label, Button, Entry,
Text, Checkbutton, Radiobutton, and Listbox, we can create interactive and user-friendly applications.
9. Differences Between Terminal-Based and GUI-Based Programming
Introduction
In programming, applications can be developed in different ways based on how users interact with them. The
two main types are Terminal-Based (Command Line Interface - CLI) and GUI-Based (Graphical User
Interface) applications.
1. Terminal-Based Programming
Definition
Terminal-based programming is a type of program where the user interacts with the system using text
commands in a terminal or command prompt.
Example
• Python programs run in IDLE or command prompt.
• Input is given using keyboard commands.
Example Program
name = input("Enter name: ")
print("Hello", name)
2. GUI-Based Programming
Definition
GUI-based programming uses graphical components like buttons, text boxes, windows, and menus for
user interaction.
Example
• Applications like calculator apps, mobile apps, and windows applications.
Example (Tkinter GUI)
import tkinter as tk
window = [Link]()
label = [Link](window, text="Hello GUI")
[Link]()
[Link]()
Differences Between Terminal-Based and GUI-Based Programming
Feature Terminal-Based Programming GUI-Based Programming
Interface Text-based Graphical (windows, buttons)
User Interaction Commands via keyboard Mouse and keyboard
Ease of Use Less user-friendly More user-friendly
Learning Requires command knowledge Easy to use
Speed Faster for experts Slightly slower
Example Python terminal, CMD Windows apps, mobile apps
Advantages of Terminal-Based Programming
1. Simple and fast for developers.
2. Uses less memory.
3. Easy for coding and debugging.
Advantages of GUI-Based Programming
1. User-friendly and attractive.
2. No need to remember commands.
3. Suitable for real-world applications.
4. Easy for beginners.
Conclusion
Terminal-based programming uses text commands, while GUI-based programming uses graphical
components. GUI applications are more user-friendly, whereas terminal-based programs are faster and
simpler for developers.