Python Basic Practice Programs
Python Basic Practice Programs
To include user-friendly error messages for invalid inputs in the script for calculating the cylinder's volume, implement a 'try-except' block for data validation: 'try: r = float(input("Enter radius of cylinder: ")) h = float(input("Enter height of cylinder: ")) if r <= 0 or h <= 0: raise ValueError("Dimensions must be positive numbers.") volume = 3.14 * r**2 * h print("Volume of cylinder:", volume) except ValueError as e: print(f"Error: {e}. Please enter valid positive numbers.")'. This approach ensures that users are guided clearly in case of errors.
Extend the script to handle data storage by implementing file I/O operations to save calculations. For instance, use a text file to append results: 'with open("calculations.txt", "a") as file: file.write(f"Rectangle Area: {area}\n")'. Introduce functionality to retrieve and display stored data: 'def retrieve_data(): with open("calculations.txt", "r") as file: print(file.read())'. This enhances the script's utility by enabling users to review past computations, supporting data persistence for audit and analysis purposes.
Implement error handling using 'try-except' blocks to capture invalid inputs and prevent runtime errors. For the circle's area calculation, wrap the input statement in a 'try' block, with corresponding 'except' for handling 'ValueError': 'try: r = float(input("Enter radius: ")) if r <= 0: raise ValueError("Radius must be positive.") area = 3.14 * r * r print("Area of circle:", area) except ValueError as e: print(f"Invalid input: {e}")'. This prevents crashes from invalid data and improves user feedback.
To extend the script to support input and output in meters, introduce a conversion option using conditional statements. Prompt users for their unit preference, then convert accordingly: 'unit = input("Convert from (1) Feet to Inches (2) Meters to Feet:") if unit == "1": feet = float(input("Enter distance in feet: ")) inches = feet * 12 print("Distance in inches:", inches) elif unit == "2": meters = float(input("Enter distance in meters: ")) feet = meters * 3.28084 print("Distance in feet:", feet)'. This version expands functionality by integrating multiple measurement systems.
To adapt the script for calculating the area of a rectangle to handle multiple rectangles, you can use a loop to repeatedly prompt the user for dimensions. For example, use a 'while' loop or 'for' loop based on user input to determine the number of rectangles: 'n = int(input("Enter number of rectangles: ")) for _ in range(n): l = int(input("Enter length: ")) b = int(input("Enter breadth: ")) area = l * b print("Area of rectangle:", area)'. This way, the program will iterate the specified number of times, processing each rectangle input.
Precision in calculating areas using Python can be greatly influenced by the data type used for inputs. Using 'int' limits calculations to whole numbers, which can reduce precision. Switching to 'float' for inputs allows for fractional numbers, enhancing accuracy: 'r = float(input("Enter radius: "))'. Additionally, using the 'math.pi' constant instead of '3.14' will improve precision for calculations involving pi. Hence, the script improvement would involve changing 'r' initialization to a 'float' and using 'math.pi' for pi representation: 'import math; area = math.pi * r**2'. This minimizes precision errors significantly.
Modularize the given scripts by defining functions for each task, enhancing code reusability and readability. Create distinct functions for 'input', 'calculation', and 'output'. For example, for rectangle area: 'def input_dimensions(): return int(input("Enter length:")), int(input("Enter breadth:")) def calculate_area(length, breadth): return length * breadth def output_area(area): print("Area:", area)'. The main call sequence then becomes: 'length, breadth = input_dimensions() area = calculate_area(length, breadth) output_area(area)'. This approach aids in maintenance and scalability.
To add input validation, use a 'try-except' block to catch input errors. Wrap the input code inside the 'try' block and raise a ValueError if the input is not a number: 'try: f = float(input("Enter temperature in Fahrenheit: ")) c = (f - 32) * 5 / 9 print("Temperature in Celsius:", c) except ValueError: print("Please enter a valid number")'. This ensures the program prompts with an error message for invalid inputs.
Improving the script to handle edge cases like negative marks or marks over 100 can significantly enhance its robustness and reliability in real-world applications. Implementing checks for input validity ensures that the user inputs lie within an acceptable range (e.g., 0 to 100), preventing illogical or erroneous outputs. This can be achieved using conditional statements: 'if not (0 <= n1 <= 100): raise ValueError("Marks should be between 0 and 100")'. This reduces erroneous data processing and fosters trust and reliability in the program's results.
Refactoring to use functions for common tasks like input and output enhances code maintainability and reduces redundancy. Functions such as 'get_user_input(prompt)' and 'display_result(value)' can be reused across different tasks, making the script cleaner and more organized. Additionally, it simplifies the debugging process and facilitates future updates by isolating changes needed to specific functions rather than multiple script sections. This approach ensures consistency in user interaction and output presentation, emphasizing best practices in efficient software development.