How to Build a Simple Calculator in Python - Step by Step 1

preview_player
Показать описание
This is a very interesting tutorial on how to build a simple calculator in Python

# ******* HOW TO BUILD A SIMPLE CALCULATOR IN PYTHON STEP BY STEP *****************
# 1. ADD
# 2. SUBTRACT
# 3. MULTIPLY
# 4. DIVIDE

print("Select an operation to perform: ")
print("1. ADD")
print("2. SUBTRACT")
print("3. MULTIPLY")
print("4. DIVIDE")

I use PyCharm, get it here

Рекомендации по теме
Комментарии
Автор

i was supposed to do exactly this for my homework and didn't understand it in my 4 hour class but i totally got it in a 15 minute video, thank you!!

sophyabud
Автор

Just wanna share my comments:

You can declare the numbers so you’ll have reusable function:

def get_nums():
x = float(input('Enter 1st number: '))
y = float(input('Enter 2nd number: '))
return x, y

and simply assign it to your operations function like this:

def sum(x, y):
return x + y

inside your loop you can do this instead:

x, y = get_nums()

so you don’t have to repeat it…

if operation == '1':
result = sum(x, y)

you can use fstring instead to make it simplified.
print(f'The Sum of {x} and {y} is {result}')


also put error handling on your division operation:

if y is equal to zero, you can print cannot divide by zero.

Overall, it' s really nice. Thanks for sharing your knowledge.

mohisa
Автор

Thank you for this. I didn't know how to go about this but you just simplified it in 15 mins. Thank you so much

ogochukwuonwujekwe
Автор

A diffrent Calculator:
num1 = input("Insert a number: ")
variable = input("Insert a variable(+, -, *, /): ")
num2 = input("Insert a number: ")

add = float(num1) + float(num2)
subtract = float(num1) - float(num2)
multiply = float(num1) * float(num2)
divide = float(num1) / float(num2)

if variable == "+":
print (add)

elif variable == "-":
print(subtract)

elif variable == "*":
print(multiply)

elif variable == "/":
print(divide)

else:
print("Error: Invalid input")

plancton
Автор

im brand new to python and after some videos i made my own calculator and this is like the exact same thing i made myself nice

Aquafina
Автор

This was such an amazing tutorial. Wonderful to follow and easy to understand! Keep up the great work.

friendlyperson
Автор

Simple and fast! Thank you for the lazy ones:
print("Select an operation to perforn: ")
print("1. ADD")
print("2. SUBTRACT")
print("3. MULTIPLY")
print("4. DIVIDE")

operation = input()

if operation == "1":
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
print("The sum is " + str(int(num1) + int(num2)))

elif operation == "2":
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
print("The difference is " + str(int(num1) - int(num2)))

elif operation == "3":
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
print("The product is " + str(int(num1 * int(num2))))

elif operation == "4":
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
print("The result is " + str(int(num1) / int(num2)))
else:
print("Invalid Entry")

LimexAim
Автор

I've made a Calculator program,
hope you like it :

Edit : Just added another function that can calculate times tabels.

# Calculator program
# In python

def addition(x, y):
output1 = (x + y)
return output1

def subtraction(x, y):
output2 = (x - y)
return output2

def multiplication(x, y):
output3 = (x * y)
return output3

def division(x, y):
output = (x / y)
return output

def square(z):
output4 = (z * z)
return output4

def cube(z):
output5 = (z * z * z)
return output5

def factorial_pos(z):
output6 = 1
for i in range(z, 1, -1):
output6 = (output6 * i)
return output6

def factorial_neg(z):
output7 = (-1)
for i in range(z, -1):
output7 = (output7 * i)
return output7

def exp_pos(b, p):
output8 = 1
for i in range(p):
output8 = (output8 * b)
return output8

def exp_neg(b, p):
output9 = (-1)
for i in range(p):
output9 = (output9 * b)
return output9

def mtp_tables_ps(x, y):
print("\nResult:\n")
for i in range(1, y+1):
print(f"{x} x {i} = {x*i}")
else:
print(f'''\nThese are the multiplication tables
of {x} with-in the range of {y}''')

def mtp_tables_ng(x, y):
print("\nResult:\n")
for i in range(-1, (y-1), -1):
print(f"{x} x {i} = {x*i}")
else:
print(f'''\nThese are the multiplication tables
of {x} with-in the range of {y}''')

def operator(c):
if(c == ('+')):
try:
x = float(input("Enter 1st number\n: "))
y = float(input("Enter 2nd number\n: "))
except ValueError:
print("\nYou can only enter integers.Try to run again!")
else:
print("Result:")
print(addition(x, y))
elif(c == ('-')):
try:
x = float(input("Enter 1st number\n: "))
y = float(input("Enter 2nd number\n: "))
except ValueError:
print("\nYou can only enter integers.Try to run again!")
else:
print("Result:")
print(subtraction(x, y))
elif(c == ('*')):
try:
x = float(input("Enter 1st number\n: "))
y = float(input("Enter 2nd number\n: "))
except ValueError:
print("\nYou can only enter integers.Try to run again!")
else:
print("Result:")
print(multiplication(x, y))
elif(c == ('/')):
try:
x = float(input("Enter 1st number\n: "))
y = float(input("Enter 2nd number\n: "))
division(x, y)
except ValueError:
print("\nYou can only enter integers.Try to run again!")
except ZeroDivisionError:
print("\nYou cant divide by 0.Try to run again!")
else:
print("Result:")
print(division(x, y))
elif(c == ("**")):
try:
z = float(input("Enter the number to sqaure it\n: "))
except ValueError:
print("\nYou can only enter integers.Try to run again!")
else:
print("Result:")
print(square(z))
elif(c == ("***")):
try:
z = float(input("Enter the number to cube it\n: "))
except ValueError:
print("\nYou can only enter integers.Try to run again!")
else:
print("Result:")
print(cube(z))
elif(c == ('!')):
try:
z = int(input("Enter the number to calculate its factorial\n: "))
if(z > 0):
print("Result:")
print(factorial_pos(z))
elif(z < 0):
print("Result:")
print(factorial_neg(z))
else:
if(z == 0):
print("Result:")
print(z*0)
else:
pass
except ValueError:
print("\nYou can only enter Integers.Try to run again!")
elif(c == ('exp')):
try:
b = int(input("Enter the base number\n: "))
p = int(input("Enter the power number\n: "))
if(p < 0):
print("\nYou cant enter negative integers as Power.Try to run again!")
elif(b > 0):
print("Result:")
print(exp_pos(b, p))
elif(b < 0):
print("Result:")
print(exp_neg(b, p))
elif(b == 0):
print("Result:")
print(b*0)
else:
pass
except ValueError:
print("\nYou can only enter Integers.Try to run again!")
elif(c == "mtp"):
try:
x = int(input("Enter the number for its multiplication tables\n: "))
y = int(input("Enter the range for the tables\n: "))
if(y > 0):
mtp_tables_ps(x, y)
elif(y < 0):
mtp_tables_ng(x, y)
else:
print("Result:")
print(x*y)
except ValueError:
print("\nYou can only enter Integers.Try to run again!")
else:
print("\nInvalid operator!")

def new_program(c):
c = input('''Enter an operator sign:
('+', '-', '*', '/', '**', '***', '!', 'exp', 'mtp')\n: ''')
operator(c)

c = input('''Enter an operator sign:
('+', '-', '*', '/', '**', '***', '!', 'exp', 'mtp')\n: ''')
operator(c)
print()
ctn = input('''Do you want to continue your calculation?
Enter 'y' for Yes / 'n' for No.\n: ''')

ctn_cmd = ['y', 'Y', 'n', 'N']

while(ctn == 'y' or ctn == 'Y'):
print()
new_program(c)
print()
ctn = input('''Do you want to continue your calculation?
Enter 'y' for Yes / 'n' for No.\n: ''')
if(ctn == 'n' or ctn == 'N'):
print()
print("Thank you for using the calculator.\n")
else:
if(ctn not in ctn_cmd):
print("\nInvalid command!Try to run again.\n")
else:
pass

# Code finished successfully.

adityanaik
Автор

Thank you so much, you are a lifesaver

sheda
Автор

Thank you so much this is my first ever coding experience

gustavofring
Автор

I have 1 question (its not about the video): How can I check if the number after the decimal . is 0 then make the number to int

the_master
Автор

Nice class, correcting and rewriting helps me to understand clearly and doesn’t felt robotic

shamlafathima
Автор

Thanks a lot, you have helped a lot. The video is amazing and easy for me to understand.

piyushashinde
Автор

I think instead of using

operation = input()

if operation == “1”

You can use

operation = int(input()
If you want it to run without error instead of int use float() so if the user enters ‘1.5’ it’ll come back as invalid entry instead of error.
Also if you used int instead of float on num1 etc it will not read floats (numbers with a decimal)

legiteh
Автор

yea but when you convert this into bat file or exe it crashes and does not repeate the first steps you do. it would be good if you just could tell us how to LOOP IT..

serious
Автор

Thank you so much, this is easy to understand

calmmap
Автор

To save the num1 and num2 as integers you could use something like

num1 = int(input("enter first num"))

and then the same for num2

EvilSpesh_Gvng
Автор

Suppose we want two or more numbers add ..what I do?

gohilap
Автор

I git an error at minus i needed to add an coma after the twxt xan someone explain?😅

ebngoon
Автор

When print() the final value... You can type (, num1 + num2)
Instead of + str(int(num2) + int(num2)
👍

chak_dz
visit shbcf.ru