Example 1: simple python calculator
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
sum = float(num1) + float(num2)
sum2 = float(num1) - float(num2)
sum3 = float(num1) * float(num2)
sum4 = float(num1) / float(num2)
choice = input('Enter an operator, + = addition, - = subtraction, * = multiplication and / = division: ')
if choice == '+':
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
if choice == '-':
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum2))
if choice == '*':
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum3))
if choice == '/':
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum4))
Example 2: how to make a calculator using idle
def calculate():
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
else:
print('You have not typed a valid operator, please run the program again.')
again()
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('See you later.')
else:
again()
calculate()
Example 3: calculator in python
def mutiply (x):
return 5*x
o = mutiply(10)
print(o)
Example 4: how to create calculator in python
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
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'):
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))
break
else:
print("Invalid Input")