I'm trying to get convert this from python 3 to 2.7 and I think I may have messed up with the indentation. The shell provides an error message of:
line 20, if(operation == '+'), IndentationError: unexpected indent
I'd like to keep the code as intact as possible but I cannot see the bug! Ugh!
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
def main():
operation = raw_input("What do you want ot do (+,-,*,/): ")
if(operation != '+' and operation != '-' and operation != '*' and operation != '/'):
print "you must enter a valid operation"
else:
var1 = int(raw_input("Enter num1: "))
var2 = int(raw_input("Enter num2: "))
if(operation == '+'):
print add(var1, var2)
elif(operation == '-'):
print sub(var1, var2)
elif(operation == '*'):
print mul(var1, var2)
else(operation == '/'):
print div(var1, var2)
main()
PEP8 recommends using 4 space indentation, here is the code of your calculator reformatted to 4 spaces:
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
def main():
operation = raw_input("What do you want ot do (+,-,*,/): ")
if(operation != '+' and operation != '-' and
operation != '*' and operation != '/'):
print "you must enter a valid operation"
else:
var1 = int(raw_input("Enter num1: "))
var2 = int(raw_input("Enter num2: "))
if(operation == '+'):
print add(var1, var2)
elif(operation == '-'):
print sub(var1, var2)
elif(operation == '*'):
print mul(var1, var2)
else:
print div(var1, var2)
main()
The IndentationError exception on compilation, happened because you had the 20th line and those appearing after it overindented.
After that I found the else (else(operation == '/'):) which is invalid, because it does not need a condition, I replaced it by and else, because at this stage we are really sure the operation is '/'.
Side note:
As #Jkdc proposes we can also check operator strings using this approach, which is more readable, in my opinion:
if(operation not in ['+', '-', '*', '/']):
print "you must enter a valid operation"
else:
#Rest of the code
Basically, it checks if the operation string is not found in the list of operators, instead of comparing them separately on 4 conditions.
Related
This question already has answers here:
What does "while True" mean in Python?
(18 answers)
Closed 2 years ago.
when i run this code it keeps on giving me the answer
here is my code
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
while True:
if operation == "+":
print num1 + num2
elif operation == "-":
print num1 - num2
elif operation == "*":
print num1 * num2
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
What you might want is to put the input taking code into the while loop:
while True:
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
if operation == "+":
print (num1 + num2)
elif operation == "-":
print (num1 - num2)
elif operation == "*":
print (num1 * num2)
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
`while True:` means Infinite Loop.
You can take input inside while loop or you can change the condition of while loop.
remove the while True: and it will only print out the answer once. while loops continue running as long as the argument is true and True is always true :P
What you probably want is for the application to keep calculating input from the user.
Try this
def calculate():
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
if operation == "+":
print (num1 + num2)
elif operation == "-":
print (num1 - num2)
elif operation == "*":
print (num1 * num2)
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
while True:
calculate()
My code will not run and i'm not sure whats wrong.
I have changed the kernel multiple times, but it is still not running.
This is the addition function of a calculator
def add(num1, num2):
sum = num1 + num2
return sum
This is the subtraction function of a calculator
def subtract(num1, num2):
difference = num2 - num2
return difference
This is the multiplication function of a calculator
def multiply(num1, num2):
product = num1 * num2
return product
This is the division function of a calculator
def divide(num1, num2):
if num1 != 0:
quotient = num2 / num1
return quotient
else:
return 0
num1 = int(input("Please enter a number:"))
num2 = int(input("Please enter a second number:"))
operator = input("What is your operation? Enter a + - * or / only.")
if operator == "+":
answer = add(num1, num2)
elif operator == "-":
answer = subtract(num1, num2)
elif operator == "*":
answer = multiply(num1, num2)
elif operator == "/":
answer = divide(num1, num2)
else:
print("This is not a valid operation!")
print(str(answer))
I have not gotten any error messages at all. It just won't run.
Your print output was inside the division function.
You could do this as Short version:
def calc(operator, x, y):
return {
'+': lambda: x + y,
'-': lambda: x - y,
'*': lambda: x * y,
'/': lambda: x / y,
}.get(operator, lambda: "This is not a valid operation!")()
num1 = int(input("Please enter a number:"))
num2 = int(input("Please enter a second number:"))
operator = input("What is your operation? Enter a + - * or / only.")
print(calc(operator, num1, num2))
it seems like you mistakenly put your "main" stuff (i.e the bit that actually controls
the flow your program) inside of your divide(num1, num2) function. Which is why when you run your program nothing seems to happen.
To fix it, try the following (note that indentation level!)
def add(num1, num2):
sum = num1 + num2
return sum
def subtract(num1, num2):
difference = num2 - num2
return difference
def multiply(num1, num2):
product = num1 * num2
return product
def divide(num1, num2):
if num1 != 0:
quotient = num2 / num1
return quotient
else:
return 0
#Here is the code that actually runs the program, takes input, calls the functions, etc.
num1 = int(input("Please enter a number:"))
num2 = int(input("Please enter a second number:"))
operator = input("What is your operation? Enter a + - * or / only.")
if operator == "+":
answer = add(num1, num2)
elif operator == "-":
answer = subtract(num1, num2)
elif operator == "*":
answer = multiply(num1, num2)
elif operator == "/":
answer = divide(num1, num2)
else:
print("This is not a valid operation!")
print(str(answer))
This program is supposed to be a calculator. When I run the program it prints operation as this
I'm not sure how to fix this. I have been trying to make a simple calculator that runs in terminal for a few days now but nothing seems to work. I think I need to re-define the operation var to print it. I'm not sure how to do that.
#The functions of this program #
def add(num1, num2):
return (num1 + num2)
def sub(num1,num2):
return (num1 - num2)
def mul(num1, num2):
return (num1 * num2)
def div(num1, num2):
return (num1 / num2)
##The variables of this program ##
num1 = input ("Number 1: ")
num2 = input ("Number 2: ")
operation = input ("Operation: ")
###The if statements of this program ###
if operation == "add":
(num1 + num2)
elif operation == "sub":
(num1 - num2)
elif operation == "mul":
(num1 * num2)
elif operation == "div":
(num1 / num2)
####The final code to print the product ####
print operation
You didn't call your functions in your if statements
if operation == "add":
print(add(num1, num2))
elif operation == "sub":
print(sub(num1, num2))
elif operation == "mul":
print(mul(num1, num2))
elif operation == "div":
print(div(num1, num2))
Also note that you can use a dict to grab the function and evaluate it
ops = {'add': add,
'sub': sub,
'mul': mul,
'div': div}
if operation in ops:
print(ops[operation](num1, num2))
else:
print('Invalid operator requested')
There are some issues in your code:
You're not calling the functions you defined.
You're not printing the result, you're printing the operator (and not even correctly).
You're applying the operations on string not numbers (input returns a string).
Use raw_input instead of input in Python-2.x.
A solution:
#The functions of this program #
def add(num1, num2):
return (num1 + num2)
def sub(num1,num2):
return (num1 - num2)
def mul(num1, num2):
return (num1 * num2)
def div(num1, num2):
return (num1 / num2)
##The variables of this program ##
num1 = float(raw_input("Number 1: ")) # convert the input to float
num2 = float(raw_input("Number 2: ")) # convert the input to float
operation = raw_input("Operation: ")
# The result variable, it holds an error message, in case the use inputs another operation
result='Unsupported operation'
###The if statements of this program ###
if operation == "add":
result = add(num1, num2)
elif operation == "sub":
result = sub(num1, num2)
elif operation == "mul":
result = mul(num1, num2)
elif operation == "div":
result = div(num1, num2)
####The final code to print the product ####
print result
Here is what you need .............
python 3 and the following code
Make sure you are using python3 and not python
e.g. root#Windows-Phone:~$ python3 anyName.py
#The functions of this program
def add(num1, num2):
return (num1 + num2)
def sub(num1,num2):
return (num1 - num2)
def mul(num1, num2):
return (num1 * num2)
def div(num1, num2):
return (num1 / num2)
#The variables of this program
num1 = int(input ("Number 1: "))
num2 = int(input ("Number 2: "))
operation = input ("Operation: ")
#The if statements of this program
if operation == "add":
print(add(num1, num2))
if operation == "sub":
print(sub(num1 ,num2))
if operation == "mul":
print(mul(num1,num2))
if operation == "div":
print(div(num1,num2))
I am a beginner in python programming and I encountered an issue with my code.
When a user types an invalid operation, it notifies the users but exits the program (line 33). How can I get it to ask user to enter a math operation again?
#This python program calculates the sum, difference, product, or quotient of two numbers defined by users.
#Define add function and return the result of num1 + num2
def add(num1, num2):
return num1 + num2
#Define subract function and return the result of subtracting num1 - num2
def sub(num1, num2):
return num1 - num2
#Define multiplication function and return the result of multiplying num1 * num2
def mul(num1, num2):
return num1 * num2
#Define division function and return the result of dividing num1 / num2
def div(num1, num2):
return num1 / num2
#Define main purpose/function of the program
def main():
#Ask what math operation to perform
operation = input("What do you want to do? (+, -, *, /): ")
#If the operation is not +, -, *, or /, invalid operation
if(operation != '+' and operation != '-' and operation != '*' and operation != '/'):
print("You must enter a valid operation!")
#If valid, perform specified operation
else:
var1 = int(input("Enter num1: "))
var2 = int(input("Enter num2: "))
if(operation == '+'):
print(add(var1, var2))
elif(operation == '/'):
print(div(var1, var2))
elif(operation == '-'):
print(sub(var1, var2))
else:
print(mul(var1, var2))
main()
Simply ask the user to input it again:
#This python program calculates the sum, difference, product, or quotient of two numbers defined by users.
#Define add function and return the result of num1 + num2
def add(num1, num2):
return num1 + num2
#Define subract function and return the result of subtracting num1 - num2
def sub(num1, num2):
return num1 - num2
#Define multiplication function and return the result of multiplying num1 * num2
def mul(num1, num2):
return num1 * num2
#Define division function and return the result of dividing num1 / num2
def div(num1, num2):
return num1 / num2
#Define main purpose/function of the program
def main():
#Ask what math operation to perform
operation = input("What do you want to do? (+, -, *, /): ")
#If the operation is not +, -, *, or /, invalid operation
while (operation != '+' and operation != '-' and operation != '*' and operation != '/'):
print("You must enter a valid operation!")
operation = input("What do you want to do? (+, -, *, /): ")
var1 = int(input("Enter num1: "))
var2 = int(input("Enter num2: "))
if(operation == '+'):
print(add(var1, var2))
elif(operation == '/'):
print(div(var1, var2))
elif(operation == '-'):
print(sub(var1, var2))
else:
print(mul(var1, var2))
main()
In case you are using Python2, you can't use input here because input() evaluates the input in the execution context. So, you should be using raw_input(). In case of Python-3.x, you can use input().
As far as your question is concerned, you can put it into a while loop.
#This python program calculates the sum, difference, product, or quotient of two numbers defined by users.
#Define add function and return the result of num1 + num2
def add(num1, num2):
return num1 + num2
#Define subract function and return the result of subtracting num1 - num2
def sub(num1, num2):
return num1 - num2
#Define multiplication function and return the result of multiplying num1 * num2
def mul(num1, num2):
return num1 * num2
#Define division function and return the result of dividing num1 / num2
def div(num1, num2):
return num1 / num2
#Define main purpose/function of the program
def main():
while True:
#Ask what math operation to perform
operation = raw_input("What do you want to do? (+, -, *, /): ")
print "operation is ", operation, type(operation)
#If the operation is not +, -, *, or /, invalid operation
if operation != '+' and operation != '-' and operation != '*' and operation != '/':
print("You must enter a valid operation!")
#If valid, perform specified operation
else:
var1 = int(input("Enter num1: "))
var2 = int(input("Enter num2: "))
if(operation == '+'):
print(add(var1, var2))
elif(operation == '/'):
print(div(var1, var2))
elif(operation == '-'):
print(sub(var1, var2))
else:
print(mul(var1, var2))
return 0
main()
def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def multi(num1, num2):
return num1 * num2
def div(num1, num2):
return num1 / num2
print("\t\t\tCalculator App")
def main():
operation = input("\nWhat do you want to do: (+, -, *, /)? ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
#invalid operation
print("You have entered an invalid key")
else:
var1 = int(input("Please number : "))
var2 = int(input("Please enter another number : "))
if(operation == "+"):
print("Answer is: ", add(var1, var2))
elif(operation == "-"):
print("Answer is: ", sub(var1, var2))
elif(operation == "*"):
print("Answer is: ", multi(var1, var2))
else:
print("Answer is: ", div(var1,var2))
main()
rerun = input("ReRun? (y/n)")
while(rerun == "y"):
main()
rerun = input("ReRun? (y/n) ")
else:
exit()
Reading books, watching videos, and self study has been challenging.
Please let me know if this is the correct way to loop this program, i'm sure there are alternatives.
If you mean the rerun loop down at the bottom, the following is probably cleaner:
while True:
main()
if input("ReRun? (y/n) ") == 'n':
break
It should be noted that it defaults to rerunning if the user enters something not expected.
I would have done something like
operators = dict()
operators['+'] = lambda x,y: x+y
operators['-'] = lambda x,y: x-y
operators['*'] = lambda x,y: x*y
operators['/'] = lambda x,y: x/y
def main():
operation = input("\nWhat do you want to do: (+, -, *, /)? ")
if operation in operators:
var1 = int(input("Please number : "))
var2 = int(input("Please enter another number : "))
print("Answer is: ", operators[operation](var1, var2))
else:
print("You have entered an invalid key")
while True:
main()
if input("ReRun? (y/n) ") == 'n':
break
Which I believe is more readeable and easier to expand (add new operators)