首页 > 解决方案 > python新手需要使用while循环的帮助

问题描述

任务:_

用 Python 编写一个交互式应用程序,向用户显示一个简单的菜单。让他们选择男孩 (b)女孩 (g)退出 (q)以退出程序。程序应该一直循环,直到用户选择退出。此应用程序将使用循环和条件来完成任务。您的程序应该输出平均男孩分数和平均女孩分数。

代码:_

 letter= input(" type (b) for Boy (g) for Girl or (q) for quit")
 boycount= 0
 girlcount=0


while(letter != 'q'):
   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")

if 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")

else:

   print("the average for the girls is",scoreG/girlcount)
   print("the average for the boys is",scoreB/boycount)

不知道如何做 python 新手。我了解我需要做什么以及我收到的错误消息,但是在 python 中实现它是我卡住的地方。

我得到的错误:在为 b 输入一个值并尝试为 bi 输入另一个值后,得到一个错误,说 scoreG 没有定义

标签: pythonloopswhile-loop

解决方案


实际上,最大的问题是缩进。

这应该有效:

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()

推荐阅读