为啥我的代码出现类型错误?
Posted
技术标签:
【中文标题】为啥我的代码出现类型错误?【英文标题】:Why am I getting a Type Error on my code?为什么我的代码出现类型错误? 【发布时间】:2021-10-18 02:57:34 【问题描述】:当我的代码在我的代码中达到“if(entered_score
def calc_average(score_1, score_2, score_3, score_4, score_5):
average = (score_1 + score_2 + score_3 + score_4 + score_5) / 5
return average
def determine_grade_letter(entered_score):
if(entered_score < 60):
return "F"
elif(entered_score < 70):
return "D"
elif(entered_score < 80):
return "C"
elif(entered_score < 90):
return "B"
elif(entered_score < 101):
return "A"
def enter_scores():
score_1 = float(input("test score #1: "));
score_2 = float(input("test score #2: "));
score_3 = float(input("test score #3: "));
score_4 = float(input("test score #4: "));
score_5 = float(input("test score #5: "));
return score_1, score_2, score_3, score_4, score_5
def results(score_1, score_2, score_3, score_4, score_5):
print("test score #1: " + str(score_1) + "\n\n" + "grade letter: " +
determine_grade_letter(score_1), \
"test score #2: " + str(score_2) + "\n\n" + "grade letter: " +
determine_grade_letter(score_2), \
"test score #3: " + str(score_3) + "\n\n" + "grade letter: " +
determine_grade_letter(score_3), \
"test score #4: " + str(score_4) + "\n\n" + "grade letter: " +
determine_grade_letter(score_4), \
"test score #5: " + str(score_5) + "\n\n" + "grade letter: " +
determine_grade_letter(score_5), \
"average score: " + str(calc_average(score_1, score_2, score_3, score_4, score_5)) +
"\n" \
+ "grade leter: " + determine_grade_letter(calc_average))
def main():
score_1, score_2, score_3, score_4, score_5 = enter_scores()
results(score_1, score_2, score_3, score_4, score_5)
main()
【问题讨论】:
【参考方案1】:比较时您正在使用函数。您应该使用带参数的函数。
determine_grade_letter(score_5), \
"average score: " + str(calc_average(score_1, score_2, score_3, score_4, score_5)) +
"\n" \
+ "grade leter: " + determine_grade_letter(calc_average(score_1, score_2, score_3, score_4, score_5)))
【讨论】:
谢谢 - 我之前曾考虑过这样做,但我认为这些问题直接是我遇到 TypeError 的地方。谢谢你的澄清!代码完美运行!【参考方案2】:首先: 您在 enter_scores 方法中的返回不在正确的位置(需要选项卡)
第二:
在您的情况下,您将返回多个变量的函数与整数进行比较
您必须将这些数字之一与整数进行比较 这可以帮助: Returning Multiple Values in Python
【讨论】:
道歉 - 在我的代码中,enter_scores 中的返回是选项卡,但我在这里忘了这样做。我感谢您发送的链接,但我想知道 - 这种比较到底发生在哪里,我怎样才能可行地纠正它?以上是关于为啥我的代码出现类型错误?的主要内容,如果未能解决你的问题,请参考以下文章