Python Practice Questions

Topic-based coding problems with sample test cases — build confidence step by step.

Exception Handling Practice

Handle runtime errors with try, except, else, finally and custom exceptions.

1
Catch Division by Zero
Easy
Write a program that divides two integers and catches ZeroDivisionError, printing 'Cannot divide by zero'.
First line: a. Second line: b.
Print the quotient, or the error message.
Sample Input 1
10
0
Sample Output 1
Cannot divide by zero
Sample Input 2
4
0
Sample Output 2
Cannot divide by zero
Sample Input 3
8
2
Sample Output 3
4.0
2
Catch ValueError on int()
Easy
Write a program that converts input to int and catches ValueError, printing 'Invalid number'.
A single line containing the input.
Print the integer, or 'Invalid number'.
Sample Input 1
abc
Sample Output 1
Invalid number
Sample Input 2
42
Sample Output 2
42
Sample Input 3
1.5
Sample Output 3
Invalid number
3
Try-Except with Multiple Values
Easy
Write a program that reads two numbers and prints their sum, catching any input error.
A single line containing two values.
Print the sum, or 'Invalid input'.
Sample Input 1
2 3
Sample Output 1
5
Sample Input 2
10 x
Sample Output 2
Invalid input
Sample Input 3
1 2 3
Sample Output 3
6
4
Simple try-except
Easy
Write a program that accesses an out-of-range list index and catches IndexError.
No input (list [1,2,3], index 5).
Print 'Index out of range'.
Sample Input 1

                      
Sample Output 1
Index out of range
Sample Input 2

                      
Sample Output 2
Index out of range
Sample Input 3

                      
Sample Output 3
Index out of range
5
Catch KeyError
Easy
Write a program that looks up a missing key in a dict and catches KeyError.
A single line containing a key to look up (dict = {'a':1,'b':2}).
Print the value, or 'Key not found'.
Sample Input 1
z
Sample Output 1
Key not found
Sample Input 2
a
Sample Output 2
1
Sample Input 3
b
Sample Output 3
2
6
Catch TypeError
Easy
Write a program that tries to add a string and an integer and catches TypeError.
No input.
Print 'Type error occurred'.
Sample Input 1

                      
Sample Output 1
Type error occurred
Sample Input 2

                      
Sample Output 2
Type error occurred
Sample Input 3

                      
Sample Output 3
Type error occurred
7
Try-Except-Finally
Easy
Write a program that tries to convert to int and always prints 'Done' in finally.
A single line containing the input.
Print the int or error, then 'Done'.
Sample Input 1
5
Sample Output 1
5
Done
Sample Input 2
abc
Sample Output 2
Invalid number
Done
Sample Input 3
7
Sample Output 3
7
Done
8
Catch Multiple Exceptions
Easy
Write a program that catches both ValueError and ZeroDivisionError.
First line: a. Second line: b.
Print the result, or the specific error message.
Sample Input 1
5
0
Sample Output 1
Cannot divide by zero
Sample Input 2
7
0
Sample Output 2
Cannot divide by zero
Sample Input 3
6
3
Sample Output 3
2.0
9
Exception with else Block
Easy
Write a program with try-except-else that prints 'No error' when the conversion succeeds.
A single line containing an integer string.
Print the integer, then 'No error'.
Sample Input 1
42
Sample Output 1
42
No error
Sample Input 2
abc
Sample Output 2
Invalid number
Sample Input 3
7
Sample Output 3
7
No error
10
Handle File Not Found
Easy
Write a program that tries to open 'missing.txt' and catches FileNotFoundError.
No input.
Print 'File not found'.
Sample Input 1

                      
Sample Output 1
File not found
Sample Input 2

                      
Sample Output 2
File not found
Sample Input 3

                      
Sample Output 3
File not found
1
Raising an Exception
Medium
Write a program that raises ValueError with message 'Negative not allowed' if input is negative.
A single line containing an integer.
Print the number, or the error message.
Sample Input 1
-5
Sample Output 1
Negative not allowed
Sample Input 2
10
Sample Output 2
10
Sample Input 3
-1
Sample Output 3
Negative not allowed
2
Custom Exception Class
Medium
Write a custom exception class NegativeError that inherits Exception, and raise it for negative input.
A single line containing an integer.
Print 'Custom error: Negative value', or the number.
Sample Input 1
-3
Sample Output 1
Custom error: Negative value
Sample Input 2
5
Sample Output 2
5
Sample Input 3
-1
Sample Output 3
Custom error: Negative value
3
Try-Except-Else-Finally
Medium
Write a program that divides two numbers and prints 'Success' in else and 'Cleanup done' in finally.
First line: a. Second line: b.
Print the quotient, 'Success', and 'Cleanup done'.
Sample Input 1
8
2
Sample Output 1
4.0
Success
Cleanup done
Sample Input 2
10
0
Sample Output 2
Cannot divide by zero
Cleanup done
Sample Input 3
9
3
Sample Output 3
3.0
Success
Cleanup done
4
Nested Try-Except
Medium
Write a program with an inner try that converts a value and an outer try that performs division.
First line: a. Second line: b.
Print the result or appropriate error message.
Sample Input 1
10
0
Sample Output 1
Cannot divide by zero
Sample Input 2
abc
2
Sample Output 2
Cannot divide by zero
Sample Input 3
10
5
Sample Output 3
2.0
5
Catch and Reraise
Medium
Write a program that catches ZeroDivisionError, prints 'Caught', then re-raises it.
First line: a. Second line: b (0).
Print 'Caught' and the re-raised error message.
Sample Input 1
5
0
Sample Output 1
Caught
Cannot divide by zero
Sample Input 2
5
0
Sample Output 2
Caught
Cannot divide by zero
Sample Input 3
10
2
Sample Output 3
Caught
5.0
6
Exception Hierarchy
Medium
Write a program that catches ArithmeticError (parent of ZeroDivisionError) for division by zero.
First line: a. Second line: b.
Print 'Arithmetic error caught'.
Sample Input 1
4
0
Sample Output 1
Arithmetic error caught
Sample Input 2
9
0
Sample Output 2
Arithmetic error caught
Sample Input 3
8
4
Sample Output 3
Arithmetic error caught
2.0
7
Index Error with Details
Medium
Write a program that accesses list index out of range and prints the valid index range instead.
No input (list [10,20,30], index 5).
Print 'Valid indices: 0 to 2'.
Sample Input 1

                      
Sample Output 1
Valid indices: 0 to 2
Sample Input 2

                      
Sample Output 2
Valid indices: 0 to 2
Sample Input 3

                      
Sample Output 3
Valid indices: 0 to 2
8
Attribute Error Handling
Medium
Write a program that accesses a non-existent attribute on an object and catches AttributeError.
No input (empty class with no attributes, access .missing).
Print 'Attribute not found'.
Sample Input 1

                      
Sample Output 1
Attribute not found
Sample Input 2

                      
Sample Output 2
Attribute not found
Sample Input 3

                      
Sample Output 3
Attribute not found
9
Chained Exceptions
Medium
Write a program that catches ValueError and re-raises it as RuntimeError with 'from e'.
A single line containing the input.
Print 'Converted to RuntimeError'.
Sample Input 1
abc
Sample Output 1
Converted to RuntimeError
Sample Input 2
5
Sample Output 2
Converted to RuntimeError
Sample Input 3
x
Sample Output 3
Converted to RuntimeError
10
Try-Except with Loop
Medium
Write a program that keeps asking for a valid integer until one is entered (simulate: use 2 attempts from input).
Two lines: first invalid value, then valid value.
Print the valid integer.
Sample Input 1
abc
42
Sample Output 1
42
Sample Input 2
x
10
Sample Output 2
10
Sample Input 3
a
b
5
Sample Output 3
5
1
Bank Withdrawal with Custom Errors
Hard
Write a class BankAccount with withdraw(amount) that raises custom errors for negative amount and insufficient balance.
First line: balance. Second line: withdrawal.
Print 'Withdrawn' or the specific error message.
Sample Input 1
100
150
Sample Output 1
Insufficient balance
Sample Input 2
500
100
Sample Output 2
Withdrawn
Sample Input 3
100
150
Sample Output 3
Insufficient balance
2
File Processing with Errors
Hard
Write a program that reads a filename from input and prints 'File opened' if it exists, catching FileNotFoundError and PermissionError.
A single line containing a filename.
Print the appropriate message.
Sample Input 1
missing.txt
Sample Output 1
File not found
Sample Input 2
data.txt
Sample Output 2
File not found
Sample Input 3
missing.csv
Sample Output 3
File not found
3
Custom Exception with Attributes
Hard
Write a custom exception InvalidAgeError that carries the age value, and raise it for age outside 0-150.
A single line containing the age.
Print 'Invalid age: [age]' or the age.
Sample Input 1
200
Sample Output 1
Invalid age: 200
Sample Input 2
25
Sample Output 2
25
Sample Input 3
-5
Sample Output 3
Invalid age: -5
4
Retry Logic with Exceptions
Hard
Write a program that attempts an operation up to 3 times, catching exceptions and printing the attempt number.
A single line containing a value that fails twice then succeeds.
Print attempt numbers and final success.
Sample Input 1
0
Sample Output 1
Attempt 1 failed
Attempt 2 failed
Success
Sample Input 2
0
0
1
Sample Output 2
Attempt 1 failed
Attempt 2 failed
Success
Sample Input 3
5
Sample Output 3
Success
5
Assertion for Validation
Hard
Write a program that uses assert to check that a number is positive, catching AssertionError.
A single line containing an integer.
Print the number, or 'Assertion failed'.
Sample Input 1
-1
Sample Output 1
Assertion failed
Sample Input 2
5
Sample Output 2
5
Sample Input 3
0
Sample Output 3
Assertion failed
6
Exception in OOP Methods
Hard
Write a class Calculator with divide(a, b) that raises ZeroDivisionError with a custom message.
First line: a. Second line: b.
Print the result, or the error message.
Sample Input 1
6
0
Sample Output 1
Cannot divide by zero
Sample Input 2
9
3
Sample Output 2
3.0
Sample Input 3
9
0
Sample Output 3
Cannot divide by zero
7
Multi-Layer Error Propagation
Hard
Write functions inner() that raises ValueError, and outer() that catches it and prints 'Handled in outer'.
No input.
Print 'Handled in outer'.
Sample Input 1

                      
Sample Output 1
Handled in outer
Sample Input 2

                      
Sample Output 2
Handled in outer
Sample Input 3

                      
Sample Output 3
Handled in outer
8
Cleanup with finally (Resource)
Hard
Write a program that simulates opening a resource, raises an exception, and closes the resource in finally.
A single line containing 1 to trigger the error, else 0.
Print 'Resource acquired', error message if triggered, and 'Resource released'.
Sample Input 1
1
Sample Output 1
Resource acquired
Error occurred
Resource released
Sample Input 2
0
Sample Output 2
Resource acquired
Resource released
Sample Input 3
1
Sample Output 3
Resource acquired
Error occurred
Resource released
9
User-Defined Error Hierarchy
Hard
Write base exception AppError and derived NetworkError and DataError. Raise NetworkError and catch AppError.
A single line containing 'network' or 'data'.
Print the caught error message.
Sample Input 1
network
Sample Output 1
Network error occurred
Sample Input 2
data
Sample Output 2
Data error occurred
Sample Input 3
network
Sample Output 3
Network error occurred
10
Convert Exception to Message
Hard
Write a program that reads two numbers, attempts division, and converts any exception to a friendly message using str(e).
First line: a. Second line: b.
Print the friendly error message or the quotient.
Sample Input 1
10
0
Sample Output 1
division by zero
Sample Input 2
5
2
Sample Output 2
2.5
Sample Input 3
5
0
Sample Output 3
division by zero