Building a Calculator with Functions in Python

Day 11/30 🔹 Problem: Build a calculator using functions 🔹 What I focused on today: Breaking a problem into small reusable functions and controlling flow using a menu 🔹 My Thinking Process: Create separate functions for each operation (add, subtract, multiply, divide) Show a menu to the user Take user choice Call the corresponding function 👉 Functions + menu = clean and organized program 🔹 Inputs I used: Two numbers Operation choice 🔹 Code: def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a * b def divide(a, b): if b == 0: return "Cannot divide by zero" return a / b print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") choice = input("Enter your choice: ") num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == "1": print("Result:", add(num1, num2)) elif choice == "2": print("Result:", subtract(num1, num2)) elif choice == "3": print("Result:", multiply(num1, num2)) elif choice == "4": print("Result:", divide(num1, num2)) else: print("Invalid choice") 🔹 Example: Choice = 1, Numbers = 10 and 5 Output → 15 🔹 Key Takeaway: Using functions makes code modular, reusable, and easier to manage, especially when multiple operations are involved #Day11 #Python #30DaysOfCode #LearningInPublic #DataAnalytics #ProblemSolving

To view or add a comment, sign in

Explore content categories