Python Functions and File Handling Examples
Python Functions and File Handling Examples
To reverse the contents of a file character-by-character with each character separated by a comma, open the target file for reading, read its contents into a string, then create a new string where each character is separated by a comma. Use the ''.join() method to insert commas between characters, and apply the reversed() function to reverse the resulting iteration of the string. Finally, write back the processed string into the file or another output file . For example, for the input 'Hello!', the output would be 'H,e,l,l,o,!,!' .
To construct a Python function named ComputeAverage that calculates the average of a list of numbers, define the function to take a list as an input. Use a try-except block to handle the case where the list is empty: in the try block, compute the average if the list is non-empty; in the except block, catch the ZeroDivisionError to return 0 when the list is empty . A simple implementation can look like: def ComputeAverage(numbers): try: return sum(numbers) / len(numbers) except ZeroDivisionError: return 0 .
To implement a function perfect_square in Python that identifies perfect squares, define a function that takes a number as input and calculates its square root. If the square of the integer value of this root equals the original number, return the number; otherwise, return -1. For example, perfect_square(1) should return 1, while perfect_square(2) should return -1 because 2 is not a perfect square . The function checks the condition using integer arithmetic to verify the square property.
To sort numbers from a file into separate files based on parity in Python, first read the numbers from the file Input.Txt. Use a loop to iterate through each number and apply a conditional statement to check if the number is odd or even. If the number is odd, write it to ODD.TXT; if even, write it to EVEN.TXT . This involves opening Input.Txt in read mode and the other two files in write mode to store the respective outputs .
Unpacking tuples in Python involves assigning the elements of a tuple to variables using a single assignment statement, e.g., tuple_values = (1, 2, 3); a, b, c = tuple_values . Handling mutable sequences can involve changing elements within a list by index, such as my_list = [1, 2, 3]; my_list[0] = 9, changing the list to [9, 2, 3]. String concatenation can be done using the '+' operator, e.g., str1 = 'Hello'; str2 = 'World'; result = str1 + ' ' + str2 results in 'Hello World' .