Module-3 Python Important Questions
Module-3 Python Important Questions
The shelve module in Python is used for persistent storage of objects. Here's a simple code snippet demonstrating its use: \n```python\nimport shelve\ndata = {'name': 'Alice', 'age': 30, 'city': 'New York'}\nwith shelve.open('mydata') as db:\n db['info'] = data\n\n# Using pprint.pformat() to print formatted data\nfrom pprint import pformat\nformatted_data = pformat(data)\nprint(formatted_data)\n``` \nThis script saves a dictionary to a shelve file and then reads and formats it nicely with pprint.pformat() for readable output .
To sort a file's contents, read the lines into a list, sort it, and write to a new file. \nExample: \n```python\nwith open('input.txt', 'r') as infile:\n lines = infile.readlines()\nlines = [line.strip() for line in lines]\nlines.sort()\nwith open('sorted_output.txt', 'w') as outfile:\n for line in lines:\n outfile.write(line + '\n')\n``` \nThis code strips newlines, sorts entries, and writes sorted lines to 'sorted_output.txt' .
To count digit frequencies, convert the input number into a string, then iterate over each character \nwhile maintaining a dictionary to count occurrences. Here’s an example: \n```python\nnumber = input('Enter a multi-digit number: ')\nfrequency = {}\nfor digit in number:\n if digit.isdigit():\n frequency[digit] = frequency.get(digit, 0) + 1\nprint('Digit frequency:', frequency)\n``` \nThis code handles each digit separately and aggregates counts for a clear frequency distribution .
To count the number of lines in a file, you can open the file in read mode using the open() function, then iterate over each line in the file using a for loop, incrementing a counter for each line. Here's a simple implementation: \n```python\nwith open('filename.txt', 'r') as file:\n line_count = sum(1 for _ in file)\nprint('Total number of lines:', line_count)\n``` This code will output the total number of lines by counting each line iteration from the file .
The pyperclip module facilitates clipboard operations. By importing it, you can use pyperclip.copy(text) \nto copy a string 'text' to the clipboard, making it ready for pasting in another context. Subsequently, \nusing pyperclip.paste() retrieves the current clipboard content as a string. This module is handy \nfor automating copy-paste tasks across different programs or scripts .
Input validation ensures that user inputs are of the expected type and format, preventing \nerrors and potential security issues. It involves checking data types, using try-except blocks \nfro error handling, and ensuring inputs meet specific criteria before further processing. \nThis process protects against invalid or malicious data that might lead to program crashes \nor exploits .
The 'r' mode opens a file for reading; it raises an error if the file does not exist. Example: `open('file.txt', 'r')`. The 'w' mode opens a file for writing, creating the file if it doesn't exist, or truncating it if it does. Example: `open('file.txt', 'w')`. The 'a' mode opens a file for appending, creating the file if it doesn't exist. Example: `open('file.txt', 'a')`. Each mode serves a distinct purpose and affects how the data is accessed or modified .
The `split()` method divides a string into a list based on a separator, e.g., `'Hello world'.split()\nreturns ['Hello', 'world']`. The `endswith()` checks if a string ends with a specified suffix, \ne.g., `'test.py'.endswith('.py')` returns `True`. The `ljust()` method left-justifies a string, \npadding it with spaces, e.g., `'hello'.ljust(10)` results in `'hello '`. Each method \nserves a unique string manipulation task .
The `in` operator checks for substring presence within a string, while `not in` checks for absence. \nFor example, `if 'world' in 'Hello world':` verifies 'world' is part of 'Hello world'. Conversely, \n`if 'abc' not in 'Hello world':` confirms 'abc' is absent. These operators simplify searches \nand condition checks in strings by returning Boolean values directly .
To create a string without consonants, iterate through the input string and keep only the vowels. The program may look like this: \n```python\ninput_string = input('Enter a string: ')\nvowels = "aeiouAEIOU"\nnew_string = ''.join([char for char in input_string if char in vowels or not char.isalpha()])\nprint('String without consonants:', new_string)\n``` \nThis program constructs a new string by including only characters that are vowels or non-alphabetical, effectively removing the consonants .