Algorithms and Data Structures with PythonChapter 54
4. Enhancing User Experience
Section 4 of 8-~ 12 min read-Synced from Cuantum content
A basic calculator is functional now, but let's make it a bit more user-friendly:
- Error Handling: We should handle potential errors, such as when the user enters a non-numeric value.
- Result Formatting: Display the result in a more readable format.
Let's implement these:
# ... previous code ... if user_input in ('add', 'subtract', 'multiply', 'divide'): try: x = float(input("Enter first number: ")) y = float(input("Enter second number: ")) if user_input == 'add': print(f"{x} + {y} = {add(x, y)}") elif user_input == 'subtract': print(f"{x} - {y} = {subtract(x, y)}") elif user_input == 'multiply': print(f"{x} × {y} = {multiply(x, y)}") elif user_input == 'divide': print(f"{x} ÷ {y} = {divide(x, y)}") except ValueError: print("Please enter a valid number.") else: print("Invalid Input") # ... rest of the code ...We've wrapped our number input section with a try...except block to handle any ValueError exceptions. This ensures the program doesn't crash if a user accidentally (or intentionally) enters non-numeric values. We've also added formatted strings to display the result in a clearer manner.
With these enhancements, our basic calculator is now more resilient and user-friendly! As you work through this project, remember that it's not just about creating a tool that works; it's about creating a tool that provides a smooth experience for its users.