Python Programming Question Bank 2024
Python Programming Question Bank 2024
In Python, class inheritance allows a child class to inherit attributes and methods from a parent class, facilitating code reuse and extending functionality. A basic example is: 'class Parent: def speak(self): return "Hello" class Child(Parent): def act(self): return "I can act"'. Here, 'Child' inherits the 'speak' method from 'Parent'. Creating an instance of 'Child' can call both 'speak' and 'act': 'c = Child() c.speak() c.act()'. This demonstrates extending the parent class's capabilities with additional methods specific to the child class .
The 'datetime' module can be used to determine and print the current day's name with the following Python code: 'import datetime current_day = datetime.datetime.now().strftime("%A") print("Today is", current_day)'. This utilizes 'datetime.now()' to get the current date and time, and 'strftime' with the format code '%A' to extract the full weekday name .
The 'shutil' module in Python provides a collection of high-level operations on files and collections of files. 'shutil.copy()' is used to copy a single file from a source to a destination, preserving metadata. 'shutil.copytree()' extends this functionality by recursively copying an entire directory tree, including all files and subdirectories. 'copytree' is useful for robustly duplicating directory structures while 'copy' is suited for single, simple file operations .
Local variables in Python are defined within a function and can only be accessed within that function's scope, whereas global variables are declared outside any function and can be accessed by any code in the program. To refer to a global variable in a function, the 'global' keyword can be used: 'global var_name', which tells Python to use the global scope variable rather than creating a local one .
Exception handling in Python is done using try-except blocks. Code that might cause an exception is placed in the 'try' block, and the response to a potential exception is in the 'except' block. For example, handling a divide-by-zero error: 'try: result = 10/0 except ZeroDivisionError: print("Cannot divide by zero")'. This code attempts a division that will fail and catches the specific ZeroDivisionError, allowing the program to continue running without crashing .
You can implement a Fibonacci function in Python like this: 'def fibonacci(n): if n <= 0: return "N must be greater than 0" fib_sequence = [0, 1] for i in range(2, n): fib_sequence.append(fib_sequence[-1] + fib_sequence[-2]) return fib_sequence[:n]'. This function checks for valid input, initializes a list with the first two Fibonacci numbers, and iteratively calculates further numbers using their sum rule, returning the sequence up to N .
In Python, 'break' and 'continue' are loop control keywords used within loops to alter the loop's execution. 'break' immediately exits the loop, skipping any remaining iterations, while 'continue' skips the current iteration and proceeds to the next one. For example, in a 'for' loop iterating over a range, placing a 'break' when a certain condition is met will exit the loop entirely: 'for i in range(10): if i == 5: break'. Conversely, using 'continue' will just skip processing for the current iteration and continue with 'i+1': 'for i in range(10): if i == 5: continue'. This is often used to bypass certain data or conditions without terminating the entire loop .
In Python, variable names must start with a letter or underscore, cannot start with a number, and can contain alphanumeric characters and underscores. They are case-sensitive. Different types of variables can be demonstrated using examples: an integer 'x = 10', a float 'y = 10.5', and a string 'z = "Python"'. Variables can be reassigned and their types changed dynamically in Python .
The 'join' method in Python concatenates a list of strings with a specified separator: ' 'delimiter'.join(['This', 'is', 'Python'])' results in 'This is Python'. The 'split' method separates a string into a list based on a delimiter: 'string.split(' ')', applied to 'This is Python', results in ['This', 'is', 'Python']. These methods are often used for file processing and creating readable output from data sequences .
The primary difference between lists and tuples in Python is that lists are mutable while tuples are immutable. This means elements within a list can be altered, added, or removed, while a tuple's elements remain fixed after creation. Lists are preferred when modifications to the sequence are needed, such as appending new data, whereas tuples are used for fixed collections of items where immutability is beneficial, such as ensuring data integrity or using as keys in dictionaries .