Making a calculator in python
Question:
So i Tried using this chunk of code to create a calculator in python, since I have just started learning. Thing is, it always says I enter an invalid option, passing through all my if-else statements, even when I do enter a valid option. What did I do wrong ?
#!/usr/bin/env python
def add():
return float(input ("Enter a number: ")) + float(input ("Enter another number: "))
def subt():
return float(input ("Enter a number: ")) - float(input ("Enter another number: "))
def mult():
return float(input ("Enter a number: ")) * float(input ("Enter another number: "))
def power():
return float(input ("Enter a number: ")) ** float(input ("Enter another number: "))
def division():
return float (input ("Enter a number: ")) / float (input ("Enter another number: "))
s = input("Add, Subtract, Multiply, Divide or Power two Numbers: ")
if s == "add":
print(add ())
elif s == "subtract":
print(subt ())
elif s == "multiply":
print(mult ())
elif s == "power":
print(power ())
elif s == "division":
print(division ())
else:
print ("Enter a valid option")
Answers:
If sounds like you’re using Python2. In that case, use raw_input
instead of input
, otherwise it tries to locate a variable/function by the users string input and place the object-name in s
. Where as raw_input
takes a user input as a string and places the string s
.
This is the short answer of the difference between the two.
#!/usr/bin/env python
def add():
return float(input ("Enter a number: ")) + float(input ("Enter another number: "))
def subt():
return float(input ("Enter a number: ")) - float(input ("Enter another number: "))
def mult():
return float(input ("Enter a number: ")) * float(input ("Enter another number: "))
def power():
return float(input ("Enter a number: ")) ** float(input ("Enter another number: "))
def division():
return float (input ("Enter a number: ")) / float (input ("Enter another number: "))
s = raw_input("Add, Subtract, Multiply, Divide or Power two Numbers: ")
if s == "add":
print(add())
elif s == "subtract":
print(subt())
elif s == "multiply":
print(mult())
elif s == "power":
print(power())
elif s == "division":
print(division())
else:
print("Enter a valid option")
There’s a lot of differences in Python2 and Python3, specifying which one you’re using helps a lot. It either says it at the top of your terminal when you enter the python interpreter or if you execute python --version
.
from tkinter import*
def btnClick(numbers):
global operator
operator = operator + str(numbers)
text_Input.set(operator)
def btnClearDisplay():
global operator
operator = "" text_Input.set("")
def btnEqualsInput():
global operator
sumup = str(eval(operator))
text_Input.set(sumup)
operator=""
cal = Tk()
cal.title("Suhail calculator")
operator = ""
text_Input = StringVar()
txtDisplay = Entry(cal, font=('arial', 20, 'bold'), textvariable=text_Input, bd=30, insertwidth=4, bg="powder blue", justify='right').grid(columnspan=4)
btn7 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="7", bg="powder blue", command=lambda:btnClick(7)).grid(row=1, column=0)
btn8 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="8", bg="powder blue", command=lambda:btnClick(8)).grid(row=1, column=1)
btn9 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="9", bg="powder blue", command=lambda:btnClick(9)).grid(row=1, column=2)
addition = Button(cal, padx=16, bd=8, fg="black", font=('arial',20,'bold'), text="+", bg="powder blue", command=lambda:btnClick("+")).grid(row=1, column=3) #================================================================================
btn4 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="4", bg="powder blue", command=lambda:btnClick(4)).grid(row=2, column=0)
btn5 = Button(cal, padx=16, bd=8, fg="black",font=('arial', 20, 'bold'), text="5", bg="powder blue", command=lambda:btnClick(5)).grid(row=2, column=1)
btn6 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="6", bg="powder blue", command=lambda:btnClick(6)).grid(row=2, column=2)
subtraction = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="-", bg="powder blue", command=lambda:btnClick("-")).grid(row=2, column=3) #=================================================================================
btn1 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="1", bg="powder blue", command=lambda:btnClick(1)).grid(row=3, column=0)
btn2 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="2", bg="powder blue", command=lambda:btnClick(2)).grid(row=3, column=1)
btn3 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="3", bg="powder blue", command=lambda:btnClick(3)).grid(row=3, column=2)
multiply = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="", bg="powder blue", command=lambda:btnClick("")).grid(row=3, column=3)
#===================================================================================
btn0 = Button(cal, padx=16, pady=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="0", bg="powder blue", command=lambda:btnClick(0)).grid(row=4, column=0)
btnClear = Button(cal, padx=16, pady=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="C", bg="powder blue", command=btnClearDisplay).grid(row=4, column=1)
btnEqual = Button(cal, padx=16, pady=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="=", bg="powder blue", command=btnEqualsInput).grid(row=4, column=2)
Division = Button(cal, padx=16, pady=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="/", bg="powder blue", command=lambda:btnClick("/")).grid(row=4, column=3) #==================================================================================
cal.mainloop()
So, I’m practicing Python atm and wanted to make a simple calculator (enter 2 numbers to get the answer). The problem I have right now is that, when I enter the string as input, the program breaks, even if I entered the IF statement for that case. This is the code, what should I do to make it work?
def again():
calc_again = input("Calculate again? ('Y' or 'N')")
if calc_again.upper() == "Y":
calculate()
elif calc_again.upper() == "N":
print("Goodbye!")
quit()
else:
again()
def calculate():
answer = 0
n = float(input("Enter the number: "))
if not isinstance(n, float):
print("Wrong input, try again!")
again()
else:
m = float(input("Enter another number: "))
k = input("Input the symbol (+, -, * or /): ")
if k == "+":
answer = n + m
print(f"Answer is: {answer}")
elif k == "-":
answer = n - m
print(f"Answer is: {answer}")
elif k == "*":
answer = n * m
print(f"Answer is: {answer}")
elif k == "/":
answer = n / m
print(f"Answer is: {answer}")
else:
print("Wrong input, try again!")
again()
calculate()
So i Tried using this chunk of code to create a calculator in python, since I have just started learning. Thing is, it always says I enter an invalid option, passing through all my if-else statements, even when I do enter a valid option. What did I do wrong ?
#!/usr/bin/env python
def add():
return float(input ("Enter a number: ")) + float(input ("Enter another number: "))
def subt():
return float(input ("Enter a number: ")) - float(input ("Enter another number: "))
def mult():
return float(input ("Enter a number: ")) * float(input ("Enter another number: "))
def power():
return float(input ("Enter a number: ")) ** float(input ("Enter another number: "))
def division():
return float (input ("Enter a number: ")) / float (input ("Enter another number: "))
s = input("Add, Subtract, Multiply, Divide or Power two Numbers: ")
if s == "add":
print(add ())
elif s == "subtract":
print(subt ())
elif s == "multiply":
print(mult ())
elif s == "power":
print(power ())
elif s == "division":
print(division ())
else:
print ("Enter a valid option")
If sounds like you’re using Python2. In that case, use raw_input
instead of input
, otherwise it tries to locate a variable/function by the users string input and place the object-name in s
. Where as raw_input
takes a user input as a string and places the string s
.
This is the short answer of the difference between the two.
#!/usr/bin/env python
def add():
return float(input ("Enter a number: ")) + float(input ("Enter another number: "))
def subt():
return float(input ("Enter a number: ")) - float(input ("Enter another number: "))
def mult():
return float(input ("Enter a number: ")) * float(input ("Enter another number: "))
def power():
return float(input ("Enter a number: ")) ** float(input ("Enter another number: "))
def division():
return float (input ("Enter a number: ")) / float (input ("Enter another number: "))
s = raw_input("Add, Subtract, Multiply, Divide or Power two Numbers: ")
if s == "add":
print(add())
elif s == "subtract":
print(subt())
elif s == "multiply":
print(mult())
elif s == "power":
print(power())
elif s == "division":
print(division())
else:
print("Enter a valid option")
There’s a lot of differences in Python2 and Python3, specifying which one you’re using helps a lot. It either says it at the top of your terminal when you enter the python interpreter or if you execute python --version
.
from tkinter import*
def btnClick(numbers):
global operator
operator = operator + str(numbers)
text_Input.set(operator)
def btnClearDisplay():
global operator
operator = "" text_Input.set("")
def btnEqualsInput():
global operator
sumup = str(eval(operator))
text_Input.set(sumup)
operator=""
cal = Tk()
cal.title("Suhail calculator")
operator = ""
text_Input = StringVar()
txtDisplay = Entry(cal, font=('arial', 20, 'bold'), textvariable=text_Input, bd=30, insertwidth=4, bg="powder blue", justify='right').grid(columnspan=4)
btn7 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="7", bg="powder blue", command=lambda:btnClick(7)).grid(row=1, column=0)
btn8 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="8", bg="powder blue", command=lambda:btnClick(8)).grid(row=1, column=1)
btn9 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="9", bg="powder blue", command=lambda:btnClick(9)).grid(row=1, column=2)
addition = Button(cal, padx=16, bd=8, fg="black", font=('arial',20,'bold'), text="+", bg="powder blue", command=lambda:btnClick("+")).grid(row=1, column=3) #================================================================================
btn4 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="4", bg="powder blue", command=lambda:btnClick(4)).grid(row=2, column=0)
btn5 = Button(cal, padx=16, bd=8, fg="black",font=('arial', 20, 'bold'), text="5", bg="powder blue", command=lambda:btnClick(5)).grid(row=2, column=1)
btn6 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="6", bg="powder blue", command=lambda:btnClick(6)).grid(row=2, column=2)
subtraction = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="-", bg="powder blue", command=lambda:btnClick("-")).grid(row=2, column=3) #=================================================================================
btn1 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="1", bg="powder blue", command=lambda:btnClick(1)).grid(row=3, column=0)
btn2 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="2", bg="powder blue", command=lambda:btnClick(2)).grid(row=3, column=1)
btn3 = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="3", bg="powder blue", command=lambda:btnClick(3)).grid(row=3, column=2)
multiply = Button(cal, padx=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="", bg="powder blue", command=lambda:btnClick("")).grid(row=3, column=3)
#===================================================================================
btn0 = Button(cal, padx=16, pady=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="0", bg="powder blue", command=lambda:btnClick(0)).grid(row=4, column=0)
btnClear = Button(cal, padx=16, pady=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="C", bg="powder blue", command=btnClearDisplay).grid(row=4, column=1)
btnEqual = Button(cal, padx=16, pady=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="=", bg="powder blue", command=btnEqualsInput).grid(row=4, column=2)
Division = Button(cal, padx=16, pady=16, bd=8, fg="black", font=('arial', 20, 'bold'), text="/", bg="powder blue", command=lambda:btnClick("/")).grid(row=4, column=3) #==================================================================================
cal.mainloop()
So, I’m practicing Python atm and wanted to make a simple calculator (enter 2 numbers to get the answer). The problem I have right now is that, when I enter the string as input, the program breaks, even if I entered the IF statement for that case. This is the code, what should I do to make it work?
def again():
calc_again = input("Calculate again? ('Y' or 'N')")
if calc_again.upper() == "Y":
calculate()
elif calc_again.upper() == "N":
print("Goodbye!")
quit()
else:
again()
def calculate():
answer = 0
n = float(input("Enter the number: "))
if not isinstance(n, float):
print("Wrong input, try again!")
again()
else:
m = float(input("Enter another number: "))
k = input("Input the symbol (+, -, * or /): ")
if k == "+":
answer = n + m
print(f"Answer is: {answer}")
elif k == "-":
answer = n - m
print(f"Answer is: {answer}")
elif k == "*":
answer = n * m
print(f"Answer is: {answer}")
elif k == "/":
answer = n / m
print(f"Answer is: {answer}")
else:
print("Wrong input, try again!")
again()
calculate()