filmov
tv
Python Programming - Create a Simple Calculator Program - Updated 2021

Показать описание
In this video you will will learn how to create a simple calculator that can add, subtract, multiply or divide depending upon the input from the user. (See the source further down)
In the tutorial video, we ask the user to choose the desired operation. Options 1, 2, 3 and 4 are valid. Two numbers are taken and an if...elif...else branching is used to execute a particular section. User-defined functions add(), subtract(), multiply() and divide() evaluate respective operations.
==Source Code==
# This program make a simple calculator that can add, subtract, multiply, and
# divide using function
# Define function (adds two numbers)
def add(x, y):
return x + y
# define function subtracts two numbers
def subtract (x, y):
return x - y
# define function multiplies two numbers
def multiply(x, y):
return x * y
# define function (divides two numbers)
def divide (x, y):
return x / y
print("Select Operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4: ")
num1 = float(input("Enter First Number: "))
num2 = float(input("Enter Second Number: "))
if choice == '1':
print(num1, "+", num2,"=", add(num1,num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1,num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1,num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1,num2))
else:
print("Invalid Input")
==EndCode==
In the tutorial video, we ask the user to choose the desired operation. Options 1, 2, 3 and 4 are valid. Two numbers are taken and an if...elif...else branching is used to execute a particular section. User-defined functions add(), subtract(), multiply() and divide() evaluate respective operations.
==Source Code==
# This program make a simple calculator that can add, subtract, multiply, and
# divide using function
# Define function (adds two numbers)
def add(x, y):
return x + y
# define function subtracts two numbers
def subtract (x, y):
return x - y
# define function multiplies two numbers
def multiply(x, y):
return x * y
# define function (divides two numbers)
def divide (x, y):
return x / y
print("Select Operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4: ")
num1 = float(input("Enter First Number: "))
num2 = float(input("Enter Second Number: "))
if choice == '1':
print(num1, "+", num2,"=", add(num1,num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1,num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1,num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1,num2))
else:
print("Invalid Input")
==EndCode==
Комментарии