2016-03-30 53 views
0

我寫了此程序得到這個輸出的希望:Python的「無」印刷

True 
True 
False 
False 

,我與「無」我的預期輸出之間的印刷得到它:

True 
None 
True 
None 
False 
None 
False 
None 

我不知道爲什麼這些「無」字符串正在打印,任何幫助將不勝感激!這裏是我的代碼:

# 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) 

非常感謝!

回答

1

這是因爲print(answer1)像調用 - 你的函數沒有返回任何東西,這就是爲什麼你看到None打印。只是不打印您的函數返回什麼:

check_answer(1, 2, 3, "+") 
check_answer(1, 2, -1, "-") 
check_answer(9, 5, 3, "+") 
check_answer(8, 2, 4, "-") 

或者,從函數返回True/False和打印結果:

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) 

作爲一個側面說明,您可以通過簡化功能使用operator模塊並將操作字符串映射到實際操作中。工作樣品爲+-

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