Okay, let's translate the concepts you've learned into a tangible application. Building a simple command-line tool is an excellent way to see how variables, control flow, functions, and error handling work together. We'll construct a basic calculator that performs addition, subtraction, multiplication, and division based on user input.
This project will directly use:
input()
: To get numbers and the desired operation from the user.float
) suitable for calculations.+
, -
, *
, /
) to perform the calculations.if
/elif
/else
): To determine which operation to perform based on the user's choice.while
): To allow the user to perform multiple calculations without restarting the script.try
/except
): To manage potential issues like non-numeric input or division by zero, preventing the program from crashing.Our command-line calculator should:
To keep the code organized and readable, we can break it down into functions:
get_number(prompt)
: A function that takes a prompt message, asks the user for input, and keeps asking until a valid number (float
) is entered. It handles ValueError
if the input isn't a number.get_operation()
: A function that prompts the user for an operation (+, -, *, /) and keeps asking until a valid one is entered.calculate(num1, num2, operation)
: A function that takes two numbers and the operation string, performs the calculation, and returns the result. It handles ZeroDivisionError
.main()
: The main function that orchestrates the application flow, calling the other functions and managing the primary loop.Let's look at snippets illustrating some important parts.
We need to ensure the user enters a valid number. A while
loop combined with try-except
is suitable for this.
def get_number(prompt):
"""Prompts the user for a number and handles invalid input."""
while True:
try:
user_input = input(prompt)
number = float(user_input) # Attempt conversion to float
return number
except ValueError:
print("Invalid input. Please enter a number.")
# Example usage within the main loop:
# first_number = get_number("Enter the first number: ")
# second_number = get_number("Enter the second number: ")
This get_number
function encapsulates the logic for repeatedly asking for input until a valid floating-point number is entered. It catches the ValueError
that float()
raises if the conversion fails.
The calculation logic uses if/elif/else
to select the operation. Crucially, division requires a check for ZeroDivisionError
.
def calculate(num1, num2, operation):
"""Performs the calculation based on the operation."""
if operation == '+':
return num1 + num2
elif operation == '-':
return num1 - num2
elif operation == '*':
return num1 * num2
elif operation == '/':
if num2 == 0:
print("Error: Cannot divide by zero.")
return None # Indicate failure
else:
return num1 / num2
else:
# This case should ideally be prevented by get_operation()
print("Error: Invalid operation.")
return None
# Example usage within the main loop:
# result = calculate(first_number, second_number, chosen_operation)
# if result is not None:
# print(f"The result is: {result}")
Here, we explicitly check if the operation is division (/
) and if the divisor (num2
) is zero before attempting the division. If it is, we print an error and return None
. The calling code should check if result
is None
before printing it.
The main part of the script will use a while True
loop that continues until the user explicitly asks to quit.
def main():
print("Welcome to the Simple Command-Line Calculator!")
while True:
# --- Get inputs using functions like get_number() and get_operation() ---
num1 = get_number("Enter the first number: ")
num2 = get_number("Enter the second number: ")
op = get_operation() # Assume get_operation handles validation
# --- Perform calculation ---
result = calculate(num1, num2, op)
# --- Display result ---
if result is not None:
print(f"Result: {num1} {op} {num2} = {result}")
# --- Ask to continue ---
again = input("Perform another calculation? (yes/no): ").lower()
if again != 'yes':
break # Exit the while loop
print("Thank you for using the calculator. Goodbye!")
# --- Call the main function to start the application ---
# if __name__ == "__main__": # Good practice, explained later
# main()
# For now, just calling main() is fine for a simple script:
# main()
This structure ties everything together. It calls the input and calculation functions, prints the output, and controls the flow based on the user's choice to continue or quit.
Save the complete code as a Python file (e.g., calculator.py
). Open your terminal or command prompt, navigate to the directory where you saved the file, and run it using:
python calculator.py
You should see the welcome message and prompts to enter numbers and operations.
Here’s how a session might look:
Welcome to the Simple Command-Line Calculator!
Enter the first number: 10
Enter the second number: 5
Enter operation (+, -, *, /): +
Result: 10.0 + 5.0 = 15.0
Perform another calculation? (yes/no): yes
Enter the first number: 20
Enter the second number: 0
Enter operation (+, -, *, /): /
Error: Cannot divide by zero.
Perform another calculation? (yes/no): yes
Enter the first number: apple
Invalid input. Please enter a number.
Enter the first number: 7
Enter the second number: 3
Enter operation (+, -, *, /): *
Result: 7.0 * 3.0 = 21.0
Perform another calculation? (yes/no): no
Thank you for using the calculator. Goodbye!
This simple calculator project demonstrates how different Python features you've learned combine to create a functional program. It effectively uses functions for organization, loops for repetition, conditionals for decisions, and error handling for robustness. You can expand this project by adding more operations (like exponentiation), improving the interface, or even adding features like calculation history.
© 2025 ApX Machine Learning