![](/img/trans.png)
[英]How to fix “TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'”
[英]How to fix 'TypeError: unsupported operand type(s) for -: 'NoneType' and 'int''
我已經工作了一個多小時,無法讓我的函數通過單元測試。 我的代碼如下:
def miles_to_laps(x):
laps = float(x * 4)
return print('%0.2f' % laps)
if __name__ == '__main__':
user_miles = float(input())
miles_to_laps(user_miles)
輸出是正確的,但是當它執行單元測試時,我得到了正確的答案,但是之后它拋出了一個錯誤。 我在下一個實驗室也試過這個,它也在做同樣的事情……見下文。
例如,如果輸入是 2.2 我得到 8.80
但如果輸入是miles_to_laps(1.5) 我得到
6.00
Traceback (most recent call last):
File "zyLabsUnitTestRunner.py", line 10, in <module>
passed = test_passed(test_passed_output_file)
File "/home/runner/local/submission/unit_test_student_code/zyLabsUnitTest.py", line 20, in test_passed
diff_amount = student_result - 6
TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'
4: Unit test
看來問題不在給定的代碼中,通過我的測試,它工作得很好。 也許是因為您嘗試使用它的任何功能都不支持浮點格式
編輯:剛剛發現問題,您從函數返回一個 None 值,您不能從中減去
修復:將函數返回到一個變量中,並執行這樣的代碼 - (float(variable)-6) 這會讓你在之前失敗的地方得到你想要的
您的問題是您從函數中返回None
,但其他一些代碼希望您return
一個數字。
這一行不符合您的預期:
return print('%0.2f' % laps)
這會打印出圈數(帶兩個小數位),然后返回print
返回的值,該值始終為None
。 如果你想返回數字,你應該只做return laps
,可能。 如果需要,調用者可以處理打印。 您可能想要打印並返回值,在這種情況下,您需要使用單獨的語句:
print('%0.2f' % laps)
return laps
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.