-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
82: Practice Exercise: Building a Calculator with Functions
You've learned how to write functions, but the real magic happens when you stop thinking about them as isolated snippets of code and start thinking about them as building blocks for a tool. To get a feel for this, we're going to build a basic calculator. It sounds simple, but it's the perfect way to practice delegating logic to specific functions so your main program doesn't become a tangled mess.
Defining the core math operations
I always start by writing the "engine" before the "dashboard." In this case, the engine is just a set of functions that do one thing and do it well. I'm going to define four basic functions. Notice how I'm keeping these lean—no input prompts inside these functions, just raw calculations. This makes them reusable elsewhere if we ever decided to turn this into a GUI app or a web service.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error: Division by zero!"
return x / y
Connecting user input to the logic
Now we need a way to let the user decide which operation to run. I could use a massive if/elif block inside a main function, which is exactly what I'll do here. I like to keep the "orchestration" logic separate from the "calculation" logic. It keeps the code readable.
def calculator():
print("Select operation: +, -, *, /")
choice = input("Enter choice: ")
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
if choice == '+':
print("Result:", add(num1, num2))
elif choice == '-':
print("Result:", subtract(num1, num2))
elif choice == '*':
print("Result:", multiply(num1, num2))
elif choice == '/':
print("Result:", divide(num1, num2))
else:
print("Invalid input")
The "string concatenation" trap
I just ran the code above and realized I made a classic mistake. If I enter 10 and 5 and choose addition, the program prints 105 instead of 15. Why? Because input() always returns a string. Python is doing string concatenation instead of mathematical addition.
I need to cast those inputs to floats before passing them into my functions. I'll fix this by wrapping the input() calls. I'm using float() instead of int() because a calculator that can't handle decimals isn't much of a calculator.
# Fixed version of the input section
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
Adding a loop for a better experience
Right now, the program runs once and then dies. That's annoying for the user. I'll wrap the whole thing in a while loop and add a "quit" option. This transforms it from a script into a legitimate little application.
def calculator():
while True:
print("\nSelect operation: +, -, *, / (or 'q' to quit)")
choice = input("Enter choice: ")
if choice.lower() == 'q':
print("Closing calculator. Goodbye!")
break
if choice in ('+', '-', '*', '/'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '+':
print("Result:", add(num1, num2))
elif choice == '-':
print("Result:", subtract(num1, num2))
elif choice == '*':
print("Result:", multiply(num1, num2))
elif choice == '/':
print("Result:", divide(num1, num2))
except ValueError:
print("Invalid input! Please enter numeric values.")
else:
print("Invalid operator selected.")
calculator()
I added a try/except block there because users love to type "banana" when you ask for a number. This prevents the whole program from crashing just because of one typo.
📋 Practical Task
Exercise: Adding an Exponent Function to the Calculator
Your task is to extend the calculator we just built. Currently, it only handles the four basic operations. I want you to add the ability to calculate exponents (raising one number to the power of another).
- Create a new function called
power(x, y)that returns x raised to the power of y. - Update the
calculator()function's menu to include the**operator. - Update the
if/eliflogic to call your newpowerfunction when**is selected. - Test it by calculating 2 to the power of 3 (which should return 8.0).
There are no comments for now.