Python while循环无法终止及全局平均值计算错误问题排查
问题描述
- while循环无法终止,输入"No"后程序仍会继续询问是否有其他客户
- 全局平均值计算结果始终不正确
原代码
csum=0 ccount=0 clients=int(input("How Many Clients?")) while clients==clients: sum=0 counter=0 determiner=str(input("Do you have another client to enter?")) if determiner==str('Yes' or "Y" or "YES"): clientname=str(input("What is the client's name?")) for i in range(4): stock=int(input("Enter Stock Amount:")) sum=sum+stock counter=counter+1 avg=sum/counter csum=csum+avg print("The Average for",clientname,"is:",avg) if determiner==str('No' or 'no' or 'NO'): cavg=csum/clients print("The average for all the clients is:",f'{cavg:.2f}')
运行输出
How Many Clients? 3 Do you have another client to enter?Yes What is the client's name?Owen Enter Stock Amount:5000 Enter Stock Amount:-6000 Enter Stock Amount:7000 Enter Stock Amount:3000 The Average for Owen is: 2250.0 Do you have another client to enter?Yes What is the client's name?John Enter Stock Amount:1000 Enter Stock Amount:2000 Enter Stock Amount:3000 Enter Stock Amount:4000 The Average for John is: 2500.0 Do you have another client to enter?Yes What is the client's name?Matt Enter Stock Amount:7000 Enter Stock Amount:8000 Enter Stock Amount:6000 Enter Stock Amount:5600 The Average for Matt is: 6650.0 Do you have another client to enter? No The average for all the clients is: 14633.33 Do you have another client to enter?
问题分析与修正
1. while循环无法终止
- 错误原因:
while clients==clients这个条件永远为真,变量和自身必然相等,没有设置循环终止的触发逻辑;输入"No"后也没有跳出循环的语句。 - 修正方法:
- 用一个布尔变量控制循环状态,比如
running = True,当输入"No"时将running设为False,循环条件改为while running: - 或者直接在处理"No"的分支里添加
break语句强制跳出循环。
- 用一个布尔变量控制循环状态,比如
2. 全局平均值计算错误
- 错误原因:
- 字符串判断逻辑失效:
determiner==str('Yes' or "Y" or "YES")等价于determiner == 'Yes',因为'Yes' or "Y" or "YES"的运算结果是第一个真值'Yes',导致输入"Y"或"YES"时不会触发客户录入分支。 - 平均值累加逻辑错误:在for循环内部每次都把当前的临时平均值加到
csum里,相当于每个客户的4次中间计算结果都被累加,而不是只加一次客户的最终平均值。比如Owen的4次中间平均值分别是5000、-500、2000、2250,这四个数都被计入了csum,而非仅最终的2250。
- 字符串判断逻辑失效:
- 修正方法:
- 字符串判断改为
determiner.strip().lower() in ['yes', 'y'],忽略输入的大小写和前后空格,提升兼容性。 - 将
csum=csum+avg移到for循环外部,仅在计算完客户最终平均值后进行累加。
- 字符串判断改为
修正后的代码
csum = 0 clients = int(input("How Many Clients?")) current_client = 0 running = True while running: sum_stock = 0 determiner = input("Do you have another client to enter?").strip().lower() if determiner in ['yes', 'y']: if current_client >= clients: print("已达到设定的客户数量上限") continue clientname = input("What is the client's name?") for _ in range(4): stock = int(input("Enter Stock Amount:")) sum_stock += stock avg = sum_stock / 4 csum += avg current_client += 1 print(f"The Average for {clientname} is: {avg}") elif determiner in ['no', 'n']: if current_client == 0: print("没有录入任何客户数据") break cavg = csum / current_client print(f"The average for all the clients is: {cavg:.2f}") running = False else: print("请输入Yes/Y或No/N")
内容的提问来源于stack exchange,提问作者Owen Adams-Mejia
相关产品推荐
相关产品推荐

