Simple Calculator in Python Without Function
This guide explains how to create a simple calculator in Python without using functions. We'll cover basic examples and gradually add features like input validation.
Introduction
Python is a versatile programming language that can be used to create simple applications like calculators. In this guide, we'll create a basic calculator that performs addition, subtraction, multiplication, and division without using functions.
Python's simplicity makes it ideal for beginners learning programming concepts. By building a calculator, you'll understand basic input handling, arithmetic operations, and control flow.
Basic Calculator Example
Let's start with the simplest calculator that can add two numbers:
# Basic addition calculator
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 + num2
print(f"The sum is: {result}")
This code prompts the user to enter two numbers, converts them to floats, adds them together, and displays the result.
Calculator with Operations
We can extend this to handle different operations using if-elif-else statements:
# Calculator with multiple operations
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
result = num1 + num2
print(f"{num1} + {num2} = {result}")
elif choice == '2':
result = num1 - num2
print(f"{num1} - {num2} = {result}")
elif choice == '3':
result = num1 * num2
print(f"{num1} * {num2} = {result}")
elif choice == '4':
if num2 != 0:
result = num1 / num2
print(f"{num1} / {num2} = {result}")
else:
print("Error! Division by zero.")
else:
print("Invalid input")
This version allows the user to choose between four operations and handles division by zero.
Calculator with Validation
We can add input validation to ensure the user enters valid numbers:
# Calculator with input validation
while True:
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
break
except ValueError:
print("Please enter valid numbers!")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
while True:
choice = input("Enter choice (1/2/3/4): ")
if choice in ('1', '2', '3', '4'):
break
print("Please enter a valid choice (1/2/3/4)")
if choice == '1':
result = num1 + num2
print(f"{num1} + {num2} = {result}")
elif choice == '2':
result = num1 - num2
print(f"{num1} - {num2} = {result}")
elif choice == '3':
result = num1 * num2
print(f"{num1} * {num2} = {result}")
elif choice == '4':
if num2 != 0:
result = num1 / num2
print(f"{num1} / {num2} = {result}")
else:
print("Error! Division by zero.")
This version uses try-except blocks to handle invalid number inputs and a while loop to ensure the user selects a valid operation.
Conclusion
We've created a simple calculator in Python without using functions. This demonstrates basic Python concepts like input handling, arithmetic operations, and control flow. You can extend this further by adding more operations, implementing a loop to perform multiple calculations, or creating a graphical user interface.
Frequently Asked Questions
Can I create a calculator without using functions in Python?
Yes, you can create a calculator without using functions by using simple if-elif-else statements and loops directly in your main code.
How do I handle invalid number inputs in a calculator?
You can use try-except blocks to catch ValueError exceptions when converting user input to numbers.
What happens if I divide by zero in the calculator?
The calculator will display an error message since division by zero is mathematically undefined.
Can I add more operations to the calculator?
Yes, you can easily extend the calculator by adding more if-elif conditions for additional operations.
How can I make the calculator perform multiple calculations?
You can wrap the calculator code in a while loop and add a condition to exit the loop when the user is done.