【发布时间】:2015-05-03 16:44:15
【问题描述】:
我正在尝试利用 TeamTreehouse 学习订阅和这本从编程逻辑和设计开始这本书来尝试学习编程和 python。
目标:结合第 12 行中通过引用传递接收到的输入,然后将传入的每个后续输入添加到 testScoreAverage 以及之前的值。相反,它只是保留一个值而不是运行总计。
我添加了 cmets,逐行指示我的错误/对代码的理解
我真的认为我通过将变量设置为数据类型 int 以某种方式将变量设置为 0,但我不明白这是怎么回事,因为我过去能够做到这一点?
#///////////////Defining Variables/////////////
testScore1=0
testScore2=0
testScore3=0
testScore4=0
testScore5=0
tests=5
testScoreAverage=0
#///////////////Defining Variables/////////////
#///////////////calcAverage Function/////////////
#L2g2h: defines function & receives current testScore int value
def calcAverage(testScore):
#L2g2h: initiates variable testScoreAverage as an int value type (but doesn't set it to any value)
testScoreAverage=int()
#L2g2h: again initiating a variable, variable testScores, to int value type (but not setting it to any numeric value)
testScores=int()
#L2g2h: for loop starting
for i in range(1, tests + 1):
#L2g2h: testScores is set equal to the current testScores value PLUS the current value of testScore to become a running total
testScores=testScores+testScore
#L2g2h: testScoreAverage is dividing the current testScores value by the current counter variable i's value to come up with an average
testScoreAverage=testScores/i
#////NEED TO SET NUMBER TO HOLD ONLY 2 DECIMAL PLACES
#L2g2h: print out the current testScoreAverage
print("Your test score average so far is ", float(testScoreAverage))
#///////////////calcAverage Function/////////////
#///////////////determineGrade Function/////////////
def determineGrade(testScore):
# for i in range(1, tests + 1):
if testScore>=90 and testScore <= 100:
print("Your test score grade is an A.")
elif testScore>=80 and testScore <= 89:
print("Your test score grade is a B.")
elif testScore>=70 and testScore <= 79:
print("Your test score grade is a C.")
elif testScore>=60 and testScore <= 69:
print("Your test score grade is a D.")
elif testScore<=60:
print("Your test score grade is a F.")
else:
print("That is invalid.")
#///////////////determineGrade Function/////////////
for i in range(1, tests + 1):
testScore=int(input("Enter test score #" + str(i)))
calcAverage(testScore)
determineGrade(testScore)
【问题讨论】:
-
testScores=int()确实 将其设置为一个值;int()返回0。只需写testScores = 0。
标签: python function for-loop average python-3.3