I wrote a simple calculator program by using functions, I don't know what exactly wrong with this code, its showing error. I did possible steps to debug this, but I couldn't.
#!/usr/bin/python
def add():
print "Enter the two numbers to Add"
A=int(raw_input("Enter A:"))
B=int(raw_input("ENter B:"))
c = A + B
def sub():
print "Enter the two numbers to Subtract"
A=int(raw_input("Enter A:"))
B=int(raw_input("Enter B:"))
c = A - B
def Mul():
print "Enter the two numbers to Multiply"
A=int(raw_input("Enter A:"))
B=int(raw_input("Enter B:"))
c = A * B
def Div():
print "Enter the two number to Divide"
A=float(raw_input("Enter A:"))
B=float(raw_input("Enter B:"))
c = A / B
print "1: ADDITION"
print "2: SUBTRACTION"
print "3: MULTIPLICATION"
print "4: DIVITION"
print "0: QUIT"
while true:
CHOICE = int(raw_input(("ENTER THE CORRESPONDING NUMBER FOR CALCULATION"))
if CHOICE == "1":
print 'ADDING TWO NUMBERS:'
add(c):
elif CHOICE == "2":
print 'SUBTRACTING TWO NUMBERS:'
sub(c):
elif CHOICE == "3":
print 'MULTIPLYING TWO NUMBERS:'
Mul(c):
elif CHOICE == "4":
print "DIVIDEING TWO NUMBERS"
Div(c):
elif CHOICE == "0":
return 0:
else
Print "The value Enter value from 1-4"
Error:
File "cal_fun.py", line 44
if CHOICE == "1":
^
SyntaxError: invalid syntax
You're missing an end parenthesis on the previous line (a common cause of mysterious syntax errors), change:
to
This is not the only syntax error in the program- you end many lines with
:
when you shouldn't, like:You also
:
for anelse
statement (it's required)Print
when it should beprint
There are also errors that are not syntax errors:
True
astrue
CHOICE
, an int, to a string like"1"
or"2"
c
to a function that takes no argumentsI've have tried to cover all of the problems with your code, of which there are numerous.
Starting with
syntax
errors:The code now has no
syntax
errors but still has many problems.c
to your function,c
is never initialized, what isc
?def add():
(even though pass the mysteriousc
value).print
orreturn
the result it just computes.CHOICE
as anint
are do comparisons with strings so theelse
case is always executed and there is no way to exit the loop (infinite looping).Fixed code:
The code is now functional.
Output:
Functional but not perfect, for instance no error handling for erroneous input.
You are passing a variable
c
to your functionsadd()
sub()
etc. but they are defined to take no arguments.on top of the syntax errors already mentioned what I think you actually want is for each function to return values to the main programme loop, which will then display them:
or alternatively make the programme shorter by inputting A and B in the main loop then passing those as parameters to the calculating functions: