2017-10-04 50 views
1
print("\n\nThis is a basic program to find the letter grade for a student.") 
student = input("What is the students name? : ") 
test1 = input("What is the first test grade " + student.capitalize() + " recieved? : ") 
test2 = input("What is the second test grade " + student.capitalize() + " recieved? : ") 
test3 = input("What is the third test grade " + student.capitalize() + " recieved? : ") 
averageTest = (int(test1) + int(test2) + int(test3)) 
print(student.capitalize() + " recieved an average test grade of " + ((averageTest)/3)) 

我寫一個基本級的計算器程序並不能解決這個問題類型錯誤:不能連接「海峽」和10

TypeError: cannot concatenate 'str' and 'float' objects

我有這麼多寫和IM上線「浮動」對象卡在這條線上 print(student.capitalize() + " recieved an average test grade of " + ((averageTest)/3))

+2

考慮尋找到['str.format()'](https://docs.python.org/2 /library/string.html#format-examples) – rob

回答

3

您不能添加字符串和數字(​​浮點數)。相反,將您的float轉換爲一個字符串,然後再使用另一個字符串進行添加。你可以用

str(x) 

在你的情況下做到這一點,這將是:

# converting the float to a string 
print(student.capitalize() + " recieved an average test grade of " + str((averageTest)/3)) 

# or, to avoid using addition or conversion at all in a console print 
print student.capitalise(), "recieved an average test grade of", averageTest/3 

# or even using string formatting (example is py2.7) 
print '%s recieved an average test grade of %s' % (student.capitalise(), averageTest/3) 
+0

謝謝!還有什麼我該做的嗎?這是一個項目,您可以讓老師選擇每篇研究論文/課堂參與/期末考試的分量。它必須是用戶友好的...任何建議?謝謝 –

+0

除了我會建議創建功能,如'平均測試',返回的平均值,而不是稍後分開。這將爲您提供更多靈活性,以便爲每個測試添加額外參數(如加權),並允許您以更有組織的方式編寫代碼,因爲它鼓勵根據您希望代碼執行的操作在「塊」中進行思考。例如 - 定義測試和權重,請求輸入(名稱和測試結果),計算加權結果,根據加權結果計算字母等級。 – MattWBP

+0

謝謝!我真的很感激它,從昨天開始已經走過了很長的一段路... –

相關問題