My 100-Day Python Journey - Day 10: Mastering Functions, Recursion, and a Calculator Project
Introduction
Greetings, fellow code enthusiasts! Day 10 of my 100-day Python adventure has been nothing short of exhilarating. Today, I've taken a deep dive into the world of functions, explored the intricacies of multiple return values, delved into docstrings, dissected the nuances between print and return, and ventured into the fascinating realm of flags and recursion. Stick around as I recount my challenges, discoveries, and cap it all off with a mini-project that beautifully showcases my evolving Python skills.
Functions with Outputs
Functions, the building blocks of any Python program, have become my trusty companions. Today's focus was on functions with outputs, made possible by the mighty return
keyword. Let's start with a simple example that converts any string into title case:
def title_case(input_string):
"""
This function takes an input string and returns it in title case.
"""
return input_string.title()
result = title_case("hello, world!")
print(result) # Output: "Hello, World!"
In this example, the title_case
function accepts an input_string
, applies the title()
method to it, and returns the result in title case.
But wait, there's more! I've also concocted two additional functions: one to calculate the area of a rectangle and another to find the square of a number. These functions, too, make use of the return
statement to deliver their results.
def calculate_rectangle_area(length, width):
"""
This function calculates the area of a rectangle.
"""
return length * width
def square(number):
"""
This function computes the square of a number.
"""
return number ** 2
Multiple Return Values
Python offers the fantastic ability to return multiple values from a single function. Think of it as receiving multiple gifts at once! Feast your eyes on this example:
def calculate_circle_properties(radius):
"""
This function calculates both the circumference and area of a circle.
"""
circumference = 2 * 3.14159 * radius
area = 3.14159 * radius * radius
return circumference, area
circle_circumference, circle_area = calculate_circle_properties(5)
print("Circumference:", circle_circumference)
print("Area:", circle_area)
In the calculate_circle_properties
function, I'm returning both the circumference and area of a circle as a tuple. When calling the function, I unpack these values into separate variables for easy access.
Docstrings
In the world of programming, clear documentation is akin to a treasure map. Python supports docstrings, which are like instruction manuals for your functions. Here's how to add them:
def greet(name):
"""
This function takes a name and returns a personalized greeting message.
"""
return f"Hello, {name}!"
help(greet) # This will display the docstring.
Docstrings provide vital information about a function's purpose, parameters, and usage, making your code more understandable and maintainable.
Print vs. Return
While both print
and return
can display information, they serve different purposes. Allow me to illustrate with these two code snippets:
def print_message(message):
"""
This function prints the provided message.
"""
print(message)
def return_message(message):
"""
This function returns the provided message.
"""
return message
print_message("Hello") # This prints "Hello"
result = return_message("World") # This assigns "World" to the variable result
print_message
does exactly as its name suggests โ it prints the message. In contrast, return_message
returns the message, allowing you to store or manipulate the result.
Flags and Recursions
Flags are like traffic signals in programming; they help control the flow of your code. Recursion, on the other hand, is akin to a function calling itself, a concept that might seem mind-boggling but proves invaluable in solving complex problems by breaking them down into simpler subproblems. Let me showcase a classic example:
def factorial(n):
"""
This recursive function calculates the factorial of a number.
"""
if n == 1:
return 1
else:
return n * factorial(n - 1)
In this factorial
function, recursion works its magic. It repeatedly calls itself, each time with a smaller n
, until it reaches the base case (n == 1
) and then works its way back up, multiplying the results along the way. This recursive approach is both elegant and powerful.
Project: Crafting a Simple Calculator
As the cherry on top of Day 10, I undertook a mini-project โ crafting a basic calculator.
The below Python code defines a simple calculator program that can perform basic arithmetic operations like addition, subtraction, multiplication, and division. It takes user input for numbers and the operation symbol, calculates the result, and offers the option to continue with the result or start a new calculation. The program uses functions, dictionaries, loops, and clear screen functionality.
from replit import clear
from art import logo
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
def calculator():
print(logo)
num1 = float(input("What's the first number?: "))
for symbol in operations:
print(symbol)
should_continue = True
while should_continue:
operation_symbol = input("Pick an operation: ")
num2 = float(input("What's the next number?: "))
calculation_function = operations[operation_symbol]
answer = calculation_function(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")
if input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ") == 'y':
num1 = answer
else:
should_continue = False
clear()
calculator()
calculator()
# I used replit to run the code
Conclusion
Day 10 has been a remarkable journey filled with insights into functions, docstrings, flags, and the enchanting world of recursion. I've not only expanded my Python repertoire but also culminated the day with a practical calculator project. Stay tuned for more exhilarating adventures on my 100-day Python journey as we continue to unravel the fascinating world of programming. Until next time, happy coding! ๐