simple calculator in python using if else

Here’s an example of How do you make a calculator using if else in Python, that can perform addition, subtraction, multiplication, and division:

# Define the calculator function
def calculator():
  # Get the operation and operands from the user
  operation = input('Enter the operation (+, -, *, /, %): ')
  operands = input('Enter the operands (separated by spaces): ').split()
  operands = [float(x) for x in operands]

  # Addition
  if operation == '+':
    # Initialize the result to 0
    result = 0
    # Iterate through the operands and add them to the result
    for operand in operands:
      result += operand
    return result
  # Subtraction
  elif operation == '-':
    # Initialize the result to the first operand
    result = operands[0]
    # Iterate through the remaining operands and subtract them from the result
    for operand in operands[1:]:
      result -= operand
    return result
  # Multiplication
  elif operation == '*':
    # Initialize the result to 1
    result = 1
    # Iterate through the operands and multiply them by the result
    for operand in operands:
      result *= operand
    return result
  # Division
  elif operation == '/':
    # Initialize the result to the first operand
    result = operands[0]
    # Iterate through the remaining operands and divide the result by them
    for operand in operands[1:]:
      result /= operand
    return result
  # Modulus
  elif operation == '%':
    # Initialize the result to the first operand
    result = operands[0]
    # Iterate through the remaining operands and calculate the modulus of the result
    for operand in operands[1:]:
      result %= operand
    return result
  # If the operation is not recognized, return an error message
  else:
    return 'Invalid operator'

# Test the calculator function
result = calculator()
print(result)

The above simple python calculator example code defines a function calculator that prompts the user for the operation and operands, and then performs the corresponding calculation. The result is returned and printed to the console.

To use the calculator, you would simply call the calculator function. It will prompt the user for the input, perform the calculation, and print the result.

The function can handle multiple operands for all of the supported operations (addition, subtraction, multiplication, division, and modulus). It also handles invalid input (e.g. division by zero) and unrecognized operations

Leave a Comment