2 回答
TA贡献1810条经验 获得超4个赞
实际上,最大的问题是缩进。
这应该有效:
letter= input(" type (b) for Boy (g) for Girl or (q) for quit")
boycount= 0
girlcount=0
scoreB = 0
scoreG = 0
while True:
if letter == 'b':
print("Enter score for boy")
scoreB += float(input())
boycount = boycount +1
letter=input(" type (b) for Boy (g) for Girl or (q) for quit")
elif letter == 'g':
print("enter score fo Girl")
scoreG += float(input())
girlcount= girlcount +1
letter=input(" type (b) for Boy (g) for Girl or (q) for quit")
elif letter == 'q':
print("the average for the girls is",scoreG/girlcount)
print("the average for the boys is",scoreB/boycount)
exit()
TA贡献1777条经验 获得超3个赞
这确实是一个缩进问题(或逻辑流程问题)。对于大多数编程语言来说这无关紧要,但在 python 中却是必不可少的。
这是您的代码实际执行的操作:
# initialize boycount and girlcount
while(letter != 'q'):
# do some stuff inside the while loop
# do some stuff inside the while loop
if letter == 'b':
# increment boycount
# do some stuff inside the while loop
# do some stuff after the while loop
# letter must be 'q' now that the while loop ended
if letter == 'g':
# increment girlcount
# this will never happen, because letter cannot be 'g' here
else:
# print summary
# this will always happen because letter is 'q'
这是您的代码应该执行的操作:
# initialize boycount and girlcount
while(letter != 'q'):
# do some stuff inside the while loop
# do some stuff inside the while loop
if letter == 'b':
# increment boycount
if letter == 'g':
# increment girlcount
# do some stuff inside the while loop
# do some stuff after the while loop
# letter must be 'q' now that the while loop ended
# print summary
与大多数其他编程语言不同,python 需要缩进来定义复合语句块的范围。我有时会使用pass带有注释的什么都不做的语句来表明我的意图:
# initialize boycount and girlcount
while(letter != 'q'):
# do some stuff inside the while loop
if letter == 'b':
# increment boycount
pass # end if
if letter == 'g':
# increment girlcount
pass # end if
pass # end while
# print summary
该pass语句只是一个什么都不做的占位符,但它可以帮助我使预期的控制流程更清晰,并且可以帮助我检测设计错误。
您可以使用的另一个诊断工具是 print() 语句。
# initialize boycount and girlcount
print("start of while letter loop")
while(letter != 'q'):
# do some stuff inside the while loop
if letter == 'b':
print("letter b: increment boycount")
# increment boycount
pass # end if
if letter == 'g':
print("letter g: increment girlcount")
# increment girlcount
pass # end if
pass # end while
print("end of while letter loop")
# print summary
当您测试包含这些打印语句的程序时,您将能够确认每个命令都按照您的预期执行。在验证逻辑有效后,您只需#在打印语句前放置一个即可将其转换为注释。
为了完整起见,官方python教程提到
循环体是缩进的:缩进是 Python 对语句进行分组的方式
添加回答
举报