Reputation: 227
I'm writing out this program with the hopes of getting this output:
True
True
False
False
and I'm getting it with "none" printed in between my expected output:
True
None
True
None
False
None
False
None
I have no idea why these "none" strings are printing, any help would be greatly appreciated! Here is my code:
# function: check_answer
# input: two numbers (number1 & number2, both integers); an answer (an integer)
# and an operator (+ or -, expressed as a String)
# processing: determines if the supplied expression is correct. for example, if the operator
# is "+", number1 = 1, number2 = 2 and answer = 3 then the expression is correct
# (1 + 2 = 3).
# output: returns True if the expression is correct, False if it is not correct
def check_answer (number1, number2, answer, operator):
if operator == "+":
test = number1 + number2
if test == answer:
print ("True")
else:
print ("False")
if operator == "-":
test2 = number1 - number2
if test2 == answer:
print ("True")
else:
print ("False")
return
answer1 = check_answer(1, 2, 3, "+")
print (answer1)
answer2 = check_answer(1, 2, -1, "-")
print (answer2)
answer3 = check_answer(9, 5, 3, "+")
print (answer3)
answer4 = check_answer(8, 2, 4, "-")
print (answer4)
Thanks so much!!
Upvotes: 0
Views: 92
Reputation: 473813
This is because of the print(answer1)
like calls - your function returns nothing which is why you see None
printed. Just don't print what your function returns:
check_answer(1, 2, 3, "+")
check_answer(1, 2, -1, "-")
check_answer(9, 5, 3, "+")
check_answer(8, 2, 4, "-")
Or, return True/False
from the function and print the result:
def check_answer(number1, number2, answer, operator):
if operator == "+":
test = number1 + number2
return test == answer
if operator == "-":
test2 = number1 - number2
return test2 == answer
answer1 = check_answer(1, 2, 3, "+")
print (answer1)
answer2 = check_answer(1, 2, -1, "-")
print (answer2)
answer3 = check_answer(9, 5, 3, "+")
print (answer3)
answer4 = check_answer(8, 2, 4, "-")
print (answer4)
As a side note, you can simplify your function by using the operator
module and mapping the operation strings into actual operations. Working sample for +
and -
:
from operator import add, sub
def check_answer(number1, number2, answer, operator):
operations = {
"+": add,
"-": sub
}
if operator not in operations:
raise ValueError("Operator '%s' not supported" % operator)
return operations[operator](number1, number2) == answer
Upvotes: 1