0% found this document useful (0 votes)
6 views5 pages

Python

The document provides a comprehensive overview of various Python programming concepts, including identifiers, constructors, exception handling, and data types. It explains key features like operator precedence, recursion, and file handling, along with their practical applications. Additionally, it covers the differences between mutable and immutable types, selection statements, and the use of functions and methods in Python.
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)
6 views5 pages

Python

The document provides a comprehensive overview of various Python programming concepts, including identifiers, constructors, exception handling, and data types. It explains key features like operator precedence, recursion, and file handling, along with their practical applications. Additionally, it covers the differences between mutable and immutable types, selection statements, and the use of functions and methods in Python.
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

1. What is a Python identifier? 14. What is a constructor? 5. Explain break and continue statements.

A Python identifier is the name used to identify A constructor is a special method named The break statement is used to terminate a loop
variables, functions, classes, or objects in a __init__() that is automatically executed when immediately. The continue statement skips the
[Link] must begin with a letter (a–z or A–Z) an object is created. It is used to initialize the remaining statements in the current iteration
or an underscore _, cannot start with a digit, and data members of a class. and moves to the next iteration. Both are used
must not be a reserved keyword. 15. What is an exception? inside loops to control program flow.
2. Define constants and variables. An exception is a runtime error that occurs They help in improving logic clarity and
A variable is a named memory location whose during program execution. It disrupts the normal efficiency in looping structures.
value can change during program execution. flow of the program unless it is properly 6. Explain function parameters and
A constant is a value that remains fixed handled. arguments.
throughout the program, usually written using 16. Use of the with statement. Parameters are variables defined in a function
uppercase letters by convention. The with statement is used for resource definition. Arguments are the actual values
management. It ensures that resources like files passed to a function during a function call.
3. Difference between == and is. are properly opened and closed automatically. Python supports positional arguments, keyword
The == operator checks whether two objects 17. Meaning of __name__ == "__main__". arguments, and default arguments. This
have the same value, while the is operator This condition checks whether a Python file is flexibility allows functions to be reused
checks whether both variables refer to the being executed directly or imported as a efficiently.
same memory location. module. Code inside this block runs only when 7. Explain recursion with an example.
4. What is operator precedence? the file is executed directly. Recursion is a process in which a function calls
Operator precedence determines the order in 18. Define recursion. itself to solve a smaller version of the same
which different operators in an expression are Recursion is a programming technique where a problem. A recursive function must have a base
[Link] with higher precedence function calls itself to solve a problem. case to stop execution. For example, factorial of
are evaluated before operators with lower It usually consists of a base case and a a number can be calculated using recursion.
precedence. recursive case. Recursion simplifies complex problems but
19. What is a dictionary key? uses more memory due to function calls.
5. What is short-circuit evaluation? A dictionary key is a unique identifier used to 8. Explain modules and different import
Short-circuit evaluation means Python stops access values stored in a dictionary. statements.
evaluating a logical expression as soon as the Keys must be immutable data types such as A module is a file containing Python definitions
final result is known. For example, in an and integers, strings, or tuples. and statements. Modules help in code
operation, if the first condition is false, the 20. What is file append mode? reusability and better organization. Python
second condition is not evaluated. File append mode ("a") opens a file for writing supports different import methods such as
data at the end of the file. Existing content is not import module, from module import name, and
6. Define bitwise operators. erased, and new data is added after the last import module as alias. The __name__ variable
Bitwise operators perform operations directly line. helps identify whether a module is run directly
on the binary representation of integers. 1. Explain arithmetic operators and their or imported.
Common bitwise operators include AND (&), OR precedence in Python. 9. Explain ASCII and UTF-8 encoding.
(|), XOR (^), left shift (<<), and right shift (>>). Arithmetic operators in Python are used to ASCII is a character encoding standard that
perform mathematical calculations. The represents characters using 7 bits.
7. Purpose of the pass statement. common arithmetic operators are addition (+), It supports only English characters and
The pass statement is a null operation used subtraction (-), multiplication (*), division (/), symbols. UTF-8 is a variable-length encoding
when a statement is syntactically required but floor division (//), modulus (%), and that supports all Unicode characters. UTF-8 is
no action is needed. It is commonly used as a exponentiation (**). Operator precedence widely used because it is compatible with ASCII
placeholder in loops, functions, or class defines the order in which these operators are and supports multiple languages.
definitions. evaluated in an expression. For example, ** has 10. Explain string slicing and indexing.
the highest precedence, followed by *, /, //, %, Indexing is used to access individual characters
8. What is a lambda function? and then +, -. Parentheses can be used to of a string using positions. Slicing is used to
A lambda function is a small anonymous change the order of evaluation. extract a portion of a string using start and end
function defined using the lambda keyword. 2. Explain bitwise operators with suitable indices. Python supports both positive and
It can take any number of arguments but examples. negative indexing. String slicing helps in
contains only a single expression. Bitwise operators perform operations on efficient string manipulation.
numbers at the binary level. The main bitwise 11. Explain list vs tuple.
9. What is a docstring? operators are AND (&), OR (|), XOR (^), left shift A list is a mutable ordered collection of
A docstring is a special string literal used to (<<), and right shift (>>). For example, 5 & 3 elements. A tuple is an immutable ordered
describe the purpose and functionality of a performs bitwise AND on binary values 101 and collection of elements. Lists use square
module, class, or function. It is written using 011, resulting in 001. Bitwise operators are brackets, while tuples use parentheses.
triple quotes and helps in documentation. commonly used in low-level programming, Tuples are faster and safer when data should
masking, and performance optimization. not be modified.
10. Define mutability. 3. Explain and and or using short-circuit 12. Explain dictionary methods: get() and
Mutability refers to the ability of an object to evaluation. subscript operator.
change its value after creation. For example, The logical operators and and or are used to The subscript operator ([]) is used to access
lists are mutable, whereas tuples and strings combine conditions. Python uses short-circuit dictionary values using keys. If the key does not
are immutable. evaluation while evaluating these operators. exist, it raises a KeyError. The get() method
11. What is negative indexing? In an and expression, if the first condition is returns the value if the key exists, otherwise
Negative indexing allows accessing elements of false, the second condition is not evaluated. returns None or a default value. Hence, get() is
a sequence from the end. Index -1 refers to the In an or expression, if the first condition is true, safer for accessing dictionary values.
last element, -2 to the second last, and so on. the second condition is skipped. This improves 13. Explain object vs reference in Python.
12. What is None in Python? efficiency and avoids unnecessary evaluations. In Python, variables store references to objects,
None is a special constant in Python that 4. Explain if-elif-else ladder with an example. not the actual objects. Multiple variables can
represents the absence of a value. It is often The if-elif-else ladder is used to check multiple refer to the same object in memory. Changes
used to indicate null results or default return conditions sequentially. The if block is checked through one reference affect the same object.
values. first, followed by one or more elif blocks, and This explains Python’s memory-efficient object
13. Role of self in a class. finally an else block. Only one block is executed handling.
self refers to the current instance of a class. based on the condition that evaluates to true.
It is used to access instance variables and Example: grading system based on marks using
methods within the class definition. multiple conditions.
14. Explain __str__ and __repr__. 3. Explain bit masking with an example. 12. Explain constructor and instance
__str__ returns a readable string representation Bit masking is a technique used to manipulate attributes.
of an object. __repr__ returns an unambiguous specific bits of a binary number. It uses bitwise A constructor is a special method named
string mainly used for debugging. If __str__ is not operators such as AND (&), OR (|), and XOR (^). __init__() that runs when an object is created.
defined, Python uses __repr__. A mask is a binary value used to select Instance attributes are variables specific to
Both improve object readability and debugging. particular bits. For example, number & 1 is used each object. They are initialized inside the
15. Explain inheritance in Python. to check whether a number is even or odd. constructor using self. Constructors help set
Inheritance allows one class to acquire Bit masking is commonly used in low-level initial values for objects.
properties and methods of another class. programming and optimization tasks. 13. Explain method overloading using
The parent class is called the base class, and 4. Explain loops in Python with syntax and operators.
the child class is called the derived class. example. Python allows operator overloading using
Inheritance supports code reusability and Loops are used to execute a block of code special methods. Methods like __add__,
extensibility. Python supports single, multiple, repeatedly. Python supports while and for __sub__, and __mul__ define operator behavior.
and multilevel inheritance. loops. The while loop runs as long as a This allows objects to respond to operators.
16. Explain try and except blocks. condition is true. The for loop iterates over Operator overloading improves code readability.
The try block contains code that may cause an sequences like lists, strings, or ranges. 14. Explain inheritance and use of super().
exception. The except block handles the Loops reduce code repetition and improve Inheritance allows a child class to acquire
exception when it occurs. This prevents readability. break and continue help control properties of a parent class. The super()
abnormal program termination. Exception loop execution. function is used to access parent class
handling improves program reliability. 5. Explain functions and their return values. methods. It avoids code duplication.
17. Explain command-line arguments. A function is a reusable block of code that Inheritance supports extensibility and
Command-line arguments are values passed to performs a specific task. Functions are defined reusability.
a Python script during execution. They are using the def keyword. They may accept 15. Explain exception handling flow.
accessed using the [Link] list. [Link][0] parameters and return values using the return Exception handling manages runtime errors.
contains the script name. They are useful for statement. A function can return one or multiple The try block contains risky code. The except
dynamic input at runtime. values. If no return statement is used, the block handles exceptions. The else block runs if
18. Explain file opening modes. function returns None. Functions improve no exception occurs. The finally block executes
Python provides different file modes such as modularity and reduce redundancy. always.
read (r), write (w), append (a), and read-write 6. Explain lambda functions and closures. 16. Explain user-defined exceptions.
(r+). Each mode controls how the file is Lambda functions are small anonymous User-defined exceptions are custom exceptions
accessed. Choosing the correct mode prevents functions defined using the lambda keyword. created by programmers. They are defined by
data loss. File modes are used with the open() They can take multiple arguments but contain inheriting from the Exception class. They
function. only one expression. Closures occur when a improve error clarity and debugging. Custom
19. Explain static attributes. function remembers variables from its exceptions help handle specific application
Static attributes belong to the class rather than enclosing scope. Closures help retain state errors.
individual objects. They are shared among all without using global variables. They are 17. Explain file handling using with
instances of the class. Static attributes are commonly used in functional programming. statement.
defined inside the class but outside methods. File handling allows reading and writing data to
They are useful for maintaining common data. 7. Explain mutability and interning in Python. files. The with statement ensures files are
Mutability refers to whether an object can be automatically closed. It prevents memory leaks.
20. Explain the id() function. modified after creation. Lists and dictionaries It improves program safety and readability.
The id() function returns the unique identity of are mutable, while tuples and strings are 18. Explain recursion vs iteration.
an object. This identity represents the memory immutable. Interning is a memory optimization Recursion uses function calls to repeat tasks.
address during execution. It helps in technique where Python reuses immutable Iteration uses loops. Recursion is simpler for
understanding object references. id() is mainly objects. It helps reduce memory usage and complex problems. Iteration is more memory
used for debugging purposes. improves performance. Interning is commonly efficient. Both have their own advantages.
applied to small integers and strings. 19. Explain global vs local variables.
1. Explain Python data types with examples. 8. Explain list operations and slicing. Local variables are defined inside a function.
Python data types specify the type of data a Lists are ordered, mutable collections of Global variables are defined outside all
variable can store. Common built-in data types elements. Python supports operations like functions. Local variables have limited scope.
include int, float, complex, string, list, tuple, append, insert, remove, and pop. Slicing allows The global keyword allows modification of
set, and dictionary. Integers store whole extracting a subset of a list using start and end global variables inside functions.
numbers, while floats store decimal values. indices. Negative indexing is also supported. 20. Explain is vs == with memory concept.
Strings store text data and are enclosed in List slicing helps in efficient data manipulation. The == operator compares values of objects.
quotes. Lists are mutable collections, whereas 9. Explain sets and their applications. The is operator compares memory addresses.
tuples are immutable. Sets store unordered A set is an unordered collection of unique Two objects may have the same value but
unique values, and dictionaries store data as elements. Sets do not allow duplicate values. different memory locations. This distinction
key–value pairs. Python is dynamically typed, so They support mathematical operations like helps understand Python’s memory model.
data type declaration is not required. union, intersection, and difference. Sets are 21. Explain selection statements in Python.
2. Explain operator associativity and useful for removing duplicates and membership Selection statements are used to control the
precedence. testing. They improve performance for large flow of execution based on conditions.
Operator precedence determines the order in data collections. Python provides if, if-else, and if-elif-else
which operators are evaluated in an expression. 10. Explain dictionary structure and statements for decision making. The condition
Operators like ** have higher precedence than *, operations. inside the if statement is evaluated as either
/, and +. Operator associativity defines the A dictionary stores data in key–value pairs. true or false. If the condition is true, the
direction of evaluation when operators have the Keys must be unique and immutable. corresponding block of code is executed;
same precedence. For example, + and * follow Values can be of any data type. Common otherwise, control moves to the next condition.
left-to-right associativity, while ** follows right- operations include insertion, deletion, and These statements help programs make logical
to-left. Parentheses can be used to override updating values. Dictionaries provide fast data decisions, such as grading systems and menu-
precedence and associativity rules. These rules access and efficient lookups. driven programs. Selection statements improve
ensure correct evaluation of expressions. 11. Explain class and object with an example. program flexibility and readability.
A class is a blueprint for creating objects.
An object is an instance of a class. Classes
define attributes and methods. Objects
represent real-world entities. Object-oriented
programming improves modularity and
reusability.
22. Explain the range() function and its uses. 29. Explain the __init__ method with example. 1. Explain Python Operators in detail with
The range() function is used to generate a The __init__ method is a special constructor examples.
sequence of numbers. It can take one argument method in Python. It is automatically called Introduction
(stop), two arguments (start, stop), or three when an object of a class is created. This Operators in Python are special symbols or
arguments (start, stop, step). The sequence method is used to initialize instance variables. It keywords used to perform operations on
generated by range() is immutable and memory uses the self-keyword to refer to the current operands such as variables and constants. They
efficient. It is mainly used with for loops to object. Constructors help assign default or play a crucial role in performing calculations,
repeat operations a fixed number of times. initial values to objects. They improve object comparisons, and logical decisions in a
The range() function simplifies looping and consistency and reliability. program.
avoids manual counter updates. Classification of Operators
23. Explain string methods in Python. 30. Explain file read and write operations. 1. Arithmetic Operators
Python provides many built-in string methods to File read operations allow programs to retrieve Arithmetic operators are used for mathematical
manipulate text data. Common string methods data from files. The read mode (r) is used to read operations. They include addition (+),
include upper() and lower() for case conversion. file contents. File write operations store data subtraction (-), multiplication (*), division (/),
The strip() method removes unwanted spaces into files using write (w) or append (a) modes. floor division (//), modulus (%), and
from strings. The replace() method substitutes Python provides methods like read(), readline(), exponentiation (**). These operators follow a
characters or words, while split() divides strings and write(). Proper file handling prevents data specific precedence order during evaluation.
into lists. Since strings are immutable, these loss and ensures data persistence. Files are 2. Relational (Comparison) Operators
methods return new strings. String methods are widely used for permanent data storage. Relational operators compare two values and
widely used in text processing and data return a Boolean result (True or False).
cleaning. Difference between List, Tuple, and Examples include greater than (>), less than (<),
Dictionary in Python equal to (==), and not equal to (!=). They are
24. Explain regular expressions in Python. Python provides different built-in data commonly used in decision-making statements.
Regular expressions are patterns used to match structures to store and manage collections of 3. Logical Operators
and manipulate text. Python provides the re data. List, Tuple, and Dictionary are commonly Logical operators such as and, or, and not are
module for working with regular expressions. used, but they differ in structure, behavior, and used to combine multiple conditions. They
They are used to search, match, and replace usage. follow short-circuit evaluation, improving
patterns in strings. Regular expressions are List program efficiency.
commonly used for validation, such as checking A list is an ordered and mutable collection of 4. Assignment Operators
email IDs or phone numbers. They reduce elements. It allows duplicate values and Assignment operators are used to assign values
complex string operations into simple elements can be accessed using index to variables.
expressions. Regular expressions make text numbers. Lists are defined using square Examples include =, +=, -=, and *=. They reduce
processing more efficient and powerful. brackets [ ]. Because lists are mutable, code length and improve readability.
25. Explain ord() and chr() functions. elements can be added, removed, or modified 5. Bitwise Operators
The ord() function returns the Unicode (or ASCII) after creation. Lists are commonly used when Bitwise operators work at the binary level.
value of a character. For example, ord('A') the data needs to be changed frequently. They are mainly used in low-level programming
returns 65. The chr() function converts an Example: and optimization tasks.
integer value back to its corresponding my_list = [10, 20, 30] Example
character. For example, chr(65) returns 'A'. my_list[1] = 25 a = 10
These functions help in encoding, decoding, b=3
and character-level operations. They are useful Tuple print(a + b)
in cryptography and text analysis. A tuple is an ordered but immutable collection print(a > b and b != 0)
26. Explain packing and unpacking of tuples. of elements. Once a tuple is created, its values
Packing refers to grouping multiple values into a cannot be changed. Tuples are defined using 2. Explain Control Statements in Python.
single tuple. For example, t = 10, 20, 30 creates parentheses ( ). They allow duplicate values and Introduction
a packed tuple. Unpacking extracts tuple use indexing similar to lists. Tuples are faster Control statements determine the flow of
elements into separate variables. For example, than lists and are used when data should execution of a program. They allow programs to
a, b, c = t assigns values individually. remain constant. make decisions, repeat tasks, and manage
Tuple unpacking improves code readability and Example: execution paths.
reduces extra indexing. It is commonly used my_tuple = (10, 20, 30) Types of Control Statements
when functions return multiple values. 1. Selection Statements
Dictionary Selection statements execute different blocks
A dictionary is an unordered (insertion-ordered of code based on conditions. Python provides if,
27. Explain the datetime module in Python. in recent Python versions) and mutable if-else, and if-elif-else statements.
The datetime module is used to handle date and collection of data stored as key–value pairs. 2. Iteration Statements
time operations. It provides classes such as Keys must be unique and immutable, while Iteration statements allow repeated execution
date, time, and [Link] module supports values can be of any type. Dictionaries are of code. Python supports for loops for fixed
formatting, comparison, and arithmetic on defined using curly braces { }. They are used iterations and while loops for conditional
dates. It is useful in applications like attendance when data needs to be accessed using repetition.
systems and event scheduling. The datetime meaningful keys instead of index positions. 3. Loop Control Statements
module helps manage real-world time-based Example: Statements like break, continue, and pass
data efficiently. my_dict = {"name": "Amit", "age": 20} control loop execution. They help skip iterations
or terminate loops early.
28. Explain type conversion in Python. Example
Type conversion is the process of converting for i in range(1, 6):
one data type into another. Python supports if i == 4:
implicit type conversion, done automatically by break
the interpreter. Explicit type conversion is done print(i)
using functions like int(), float(), and str(). Advantages
Explicit conversion avoids type mismatch • Improves program flexibility
errors. Type conversion ensures correct
• Reduces code duplication
operations between different data types.
It plays an important role in user input handling. • Enhances logical clarity
3. Explain Functions in Python with types of 5. Explain Exception Handling in Python. Q1. Syntax Errors vs Runtime Exceptions
arguments. Introduction Syntax Errors
Introduction Exception handling is a mechanism to handle Syntax errors occur when a program violates the
A function is a reusable block of code designed runtime errors gracefully. It prevents sudden grammatical rules of the Python language.
to perform a specific [Link] help divide termination of programs. These errors are detected before execution,
large programs into smaller, manageable units. Exception Handling Blocks during the compilation or interpretation stage.
Types of Arguments • try – contains risky code Because of syntax errors, the Python interpreter
1. Positional Arguments – Passed in a stops immediately and the program does not
• except – handles exceptions
fixed order. run at all. Common causes of syntax errors
2. Keyword Arguments – Passed using • else – executes if no exception occurs include missing colons, incorrect indentation,
parameter names. • finally – executes always missing parentheses, and improper use of
3. Default Arguments – Have Example keywords. The interpreter clearly points to the
predefined values. try: line where the syntax error occurred, helping the
4. Variable-Length Arguments – x = int(input()) programmer correct it.
Accept multiple values using *args print(10/x) Example:
and **kwargs. except ValueError: if x > 5
Example print("Invalid input") print(x)
def display(name, age=20): except ZeroDivisionError: Runtime Exceptions
print(name, age) print("Division by zero") Runtime exceptions occur while the program is
finally: running, even when the syntax is correct.
display("Amit") print("End of program") These errors happen due to illegal operations
Advantages Advantages such as division by zero, accessing an invalid
• Promotes code reusability • Improves program robustness index, or converting incorrect data types.
If not handled properly, runtime exceptions
• Simplifies debugging • Helps in error diagnosis
cause abnormal termination of the program.
• Improves modular programming • Maintains program flow Examples of runtime exceptions include
Conclusion 6. Explain File Handling in Python with ZeroDivisionError, ValueError, IndexError, and
Functions make Python programs structured, modes. TypeError.
reusable, and easy to maintain. Introduction Example:
File handling allows data to be stored x = 10 / 0
4. Explain Object-Oriented Programming permanently on secondary storage. Comparison
(OOP) concepts in Python. Python provides built-in support for file Syntax errors prevent program execution
Introduction operations. entirely, while runtime exceptions occur during
Object-Oriented Programming is a programming File Modes execution. Syntax errors must be corrected
paradigm that uses objects and classes to • r – Read existing file before running the program, whereas runtime
design applications.
• w – Write (overwrites file) exceptions can be handled using exception
Python fully supports OOP concepts. handling mechanisms.
Core OOP Concepts • a – Append data
1. Class and Object • r+ – Read and write Q2. Traceback, try, except, else, finally, raise
A class is a blueprint, while an object is an File Handling Steps Traceback
instance of a class. 1. Open the file A traceback is a detailed error report displayed
2. Encapsulation 2. Perform operations when an exception occurs. It shows the
Encapsulation binds data and methods into a 3. Close the file sequence of function calls and the exact line
single unit and protects data from unauthorized Example number where the error happened. Tracebacks
access. with open("[Link]", "a") as f: help in debugging and identifying the root cause
3. Inheritance [Link]("Python File Handling\n") of errors.
Inheritance allows one class to acquire 7. Explain Inheritance and Method Resolution try Block
properties and methods of another class, Order (MRO). The try block contains code that may raise an
reducing redundancy. Introduction exception. Python executes this block first.
4. Polymorphism Inheritance enables a class to reuse properties except Block
Polymorphism allows the same method name of another class. Python supports multiple The except block catches and handles
to perform different tasks based on context. inheritance. exceptions raised in the try block.
Example Method Resolution Order (MRO) It prevents the program from crashing and
class Person: MRO defines the order in which methods are allows graceful error handling.
def show(self): searched. Python uses C3 linearization to else Block
print("Person") resolve ambiguity. The else block executes only if no exception
Example occurs in the try block. It is useful for code that
class Student(Person): class A: pass, class B(A): pass, class C(B): pass should run only when execution is successful.
pass 8. Explain Python Memory Model (Object and finally Block
s = Student() Reference). The finally block executes always, regardless of
[Link]() Introduction whether an exception occurs or not. It is mainly
Python uses a reference-based memory model. used for cleanup tasks such as closing files or
Variables do not store values directly but store releasing resources.
references to objects. raise Statement
Explanation The raise statement is used to explicitly
• Multiple variables can reference the generate an exception. It is useful for enforcing
same object program rules or handling invalid inputs.
• Mutable objects can change via any Example:
reference try:
• Immutable objects cannot be x = int(input())
modified if x < 0:
Example raise ValueError("Negative number not
x = [1, 2] allowed")
except ValueError as e:
y=x
[Link](3) print(e)
print(x) finally:
print("Program ended")
Q5. File Opening Modes (read/write/append),
Q3. Matching except clause, except with with Statement
multiple exceptions, finally with return File Opening Modes
Matching except Clause Python provides several file opening modes to
When an exception occurs, Python checks the control file operations.
except blocks sequentially from top to bottom. • Read mode (r): Opens a file for
The first matching except block is executed, and reading. The file must exist.
the rest are skipped. Therefore, specific
• Write mode (w): Opens a file for
exceptions should always be written before
writing. Existing content is
general exceptions.
overwritten.
except with Multiple Exceptions
Python allows handling multiple exceptions in a • Append mode (a): Opens a file for
single except block by specifying them as a writing at the end without deleting
[Link] reduces code duplication and existing content.
simplifies error handling. • Read and write mode (r+): Allows
Example: both reading and writing.
try: Example:
x = int("abc") f = open("[Link]", "a")
except (ValueError, TypeError): [Link]("Python File Handling\n")
print("Handled multiple exceptions") [Link]()
finally with return with Statement
Even if a return statement is present in the try or The with statement is used for efficient resource
except block, the finally block is executed management.
before the function returns. This ensures that It automatically closes the file after completing
cleanup operations are always performed. the block of code.
Example: Even if an exception occurs, the file is safely
def test(): closed.
try: Example:
return 10 with open("[Link]", "r") as f:
finally: print([Link]())
print("Finally executed") Advantages
test() • Cleaner code
Q4. Built-in exceptions, user-defined
• Automatic file closure
exception classes, exceptions with
arguments, command-line arguments • Prevents memory leaks
Built-in Exceptions
Built-in exceptions are predefined error classes
provided by Python. They handle common
runtime errors such as division by zero, invalid
data types, and index errors. Examples include
ZeroDivisionError, ValueError, IndexError,
TypeError, and KeyError.
User-Defined Exception Classes
Python allows programmers to define their own
exception classes by inheriting from the
Exception class. User-defined exceptions
improve program readability and help handle
application-specific errors.
Example:
class InvalidAgeError(Exception):
pass
Exceptions with Arguments
Exceptions can carry additional information
through arguments. These messages help
describe the exact nature of the error.
raise ValueError("Invalid input provided")
Command-Line Arguments
Command-line arguments allow users to pass
values to a program at runtime. They are stored
in the [Link] list from the sys module.
This feature makes programs flexible and
reusable.

You might also like