“我当地的学区需要一个应用程序来比较某项测试中男孩的平均分数与女孩的平均分数。用Python编写一个交互式应用程序以向用户显示一个简单的菜单。让他们为男孩选择一个选项( b),女孩(g)或退出(q)退出程序,程序应一直循环播放,直到用户选择退出为止。此应用程序将使用循环和条件来完成任务。您的程序应输出平均男孩得分和平均女生分数。您的Python程序应接受用户输入的数据。您的程序应允许任意数量的男生分数和女生分数,并在用户输入“ q”时终止。”
*该程序无法正常运行,我不确定我要去哪里。
这是我到目前为止所拥有的:
bscore = 0
gscore = 0
gtotal = 0
btotal = 0
baverage = 0
gaverage = 0
bcount = 0
gcount = 0
gen = 0
while(gen != "q"):
gen = input("Please enter the scores for Boy(b), Girl(g) or Quit(q): ")
if(gen == "b"):
bscore = int(input("Boy score: "))
bcount += 1
btotal = btotal + bscore
baverage = btotal/bcount
elif(gen == "g"):
gscore = int(input("Girl score: "))
gcount += 1
gtotal = gtotal + gscore
gaverage = gtotal/gcount
else:
gen = input("Boy (b), Girl (g) or Quit (q): ")
print("Boy average is: ", baverage)
print("Girl average is: ", gaverage)
已更新:
bscore = 0
gscore = 0
gtotal = 0
btotal = 0
baverage = 0
gaverage = 0
bcount = 0
gcount = 0
gen = input("Boy(b), Girl(g) or Quit(q): ")
while(gen != "q"):
if(gen == "b"):
bscore = int(input("Boy score: "))
bcount += 1
btotal = btotal + bscore
elif(gen == "g"):
gscore = int(input("Girl score: "))
gcount += 1
gtotal = gtotal + gscore
gen = input("Boy (b), Girl (g) or Quit (q): ")
baverage = btotal/float(bcount)
gaverage = gtotal/float(gcount)
print("Boy average is: ", baverage)
print("Girl average is: ", gaverage)
答案 0 :(得分:0)
您可能已将ll.3-10(将许多变量设置为0)放置在循环中,而您似乎想将它们放在前面,因此它们只执行一次,而不执行每次循环时重置您的统计信息。
答案 1 :(得分:0)
除了少数语法错误外,您还需要在while
循环之外声明变量,因为每次您询问用户有关 boy <的信息时,变量都会重置为 0 / em>或 girl :
修正逻辑后,您的代码可能如下所示
# Declare your variables outside the while loop here
bscore = 0
gscore = 0
gtotal = 0
btotal = 0
baverage = 0
gaverage = 0
bcount = 0
gcount = 0
# Ask the user for input
gen = input("Boy (b), Girl (g) or Quit (q): ")
while(gen != "q"):
if(gen == "b"):
bscore = int(input("Boy score: "))
bcount += 1
btotal = btotal + bscore
elif(gen == "g"):
gscore = int(input("Girl score: "))
gcount += 1
gtotal = gtotal + gscore
# Ask the user if he wants another entry
gen = input("Boy (b), Girl (g) or Quit (q): ")
# The average should only be calculated one time when user stops the program
# Therefore calculate average scores outside the while loop
baverage = btotal/float(bcount)
gaverage = gtotal/float(gcount)
print("Boy average is: ", baverage)
print("Girl average is: ", gaverage)