Python Exam Notes
Python Exam Notes
Inheritance allows a new class to inherit properties and methods from an existing class, which helps in minimizing redundancy and promoting code reusability. By defining common features in a base class, subclasses can extend or override these features to suit specific needs. This reduces the amount of code a programmer has to write and maintain, as changes in the parent class automatically propagate to child classes unless explicitly overridden. For example, a Car class inheriting from a Vehicle class can reuse attributes like 'brand' without redefining them .
Type casting and conversion can be crucial in scenarios that involve data input and user interaction, where data might be received as strings but need to be used as numeric types for computation. For example, converting a user-entered numeric value from a string to a float or int ensures that arithmetic operations can be performed correctly. Such conversion ensures data integrity and avoids runtime errors by maintaining consistency in data types throughout program execution .
Using *args in Python functions allows for the acceptance of an arbitrary number of positional arguments, providing flexibility in function calls, such as aggregating values or passing varying numbers of arguments to a function without explicitly defining each parameter. This facilitates use cases like summing an unknown quantity of numbers, for example, def add(*args): return sum(args). It allows developers to write generalized code that can handle diverse input scenarios, enhancing function versatility .
Global variables in Python can lead to programs that are hard to debug and maintain due to unintended side-effects across different parts of the code. They may be unintentionally modified from different scopes, complicating state management and increasing the potential for errors. Their usage can be minimized by using local variables within functions and classes, thereby encapsulating functionality and maintaining data within confined contexts. When necessary, global variables should be clearly documented and used with the global keyword within functions to avoid accidental shadowing .
Python handles errors using try-except blocks, which allow developers to catch exceptions and handle them gracefully without terminating the program. By using this mechanism, developers can specify what to do when an error occurs, like logging the error or retrying a block of code, thereby preventing crashes. This is important for robust program development because it enhances program stability and user experience, allowing the program to continue operations even when unexpected issues arise, such as handling a ZeroDivisionError during division .
Arithmetic operators in Python, such as + (addition), - (subtraction), * (multiplication), and / (division), are used to perform mathematical operations on numeric values. For example, they can be used in a calculation within a financial application. Logical operators, such as 'and', 'or', and 'not', are used to evaluate expressions based on boolean logic, determining the truth value of a condition. They are useful in control flow structures like 'if' statements to make decisions based on multiple conditions .
Encapsulation in Python is implemented through the definition of class and instance variables, along with access restrictions. Attributes can be defined as public, protected (with a single underscore), and private (with a double underscore), controlling the visibility outside the class. Encapsulation is fundamental in OOP because it restricts direct access to object data, ensuring data integrity and security while allowing controlled interaction through methods. This helps maintain the internal state of an object and allows changes without affecting external code that uses the class .
Positional arguments require that values be passed in the order defined by the function, which can lead to errors if not handled correctly . Keyword arguments specify the parameter name with the value, which enhances readability and avoids the order requirement. Default arguments allow a function to assume a default value for parameters if none are provided, providing flexibility and reducing the need to specify values frequently used . Together, these options provide flexibility in function calls, making them adaptable to different needs.
Python's comparison operators, such as ==, !=, >, <, >=, and <=, are essential in constructing conditional logic, allowing the evaluation of variable relationships to control program flow. They are commonly used in conditional statements like 'if' or loops to decide execution paths based on data conditions. Misusing these operators, such as using = instead of ==, can lead to logical errors, where the program does not behave as intended, and potentially introduce bugs that are difficult to trace in larger applications .
List comprehensions offer a more concise and readable way to create lists in Python. They allow for the integration of expressions and loops in a single line, which can make code shorter and easier to understand, such as creating a list of squares from a range of numbers . However, traditional for loops might still be preferable when complex logic needs to be applied, such as multiple nested conditions or complex data manipulation that would be cumbersome within a single line comprehension.