You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复含双while循环的Python函数中的多余打印语句问题?

帮你修复这个函数的小问题

嘿,作为编程新手遇到这种逻辑结构的问题太正常啦,我帮你拆解一下问题原因,再给你修正后的代码~

问题原因分析

  1. 当type为"A"时,items和total被重复打印?
    你的代码里把print("Items...")和print("\nTotal...")写在了所有循环的外面,不管type是什么都会执行一次。另外你代码里的else语句还有个小错误:" is not an invalid input"是双重否定,应该改成" is an invalid input"哦。

  2. 当type为"T"时,出现了多余的打印语句?
    因为你把针对"A"类型的提示语(print("Input an integer..."))和Items打印都放在了函数最外层,不管type是不是"T"都会执行,所以才会出现多余的输出。而且你希望type="T"时只打印total,那就要把total的打印放到"T"循环的退出逻辑里。

修正后的代码

def ar(type):
    total = 0
    items = ""
    
    if type == "A":
        print("Input an integer to add to the total or \"Q\" to quit")
        while True:
            user_input = input("Enter an integer or \"Q\": ")
            if user_input.isdigit():
                items += user_input + "\n"
                total += int(user_input)
            elif user_input.lower() == "q":
                break
            else:
                print(f"{user_input} is an invalid input")
        # 仅当type为"A"时打印items和total
        print("Items \n" + items)
        print("\nTotal \n" + str(total))
    
    elif type == "T":
        print("Input an integer to add to the total or \"Q\" to quit")
        while True:
            user_input = input("Enter an integer or \"Q\": ")
            if user_input.isdigit():
                total += int(user_input)
            elif user_input.lower() == "q":
                break
            else:
                print(f"{user_input} is an invalid input")
        # 仅当type为"T"时,退出循环后打印total
        print("\nTotal \n" + str(total))

关键修改点

  • 用if-elif把不同type的逻辑完全分开,各自的提示语、循环、打印都放在对应分支里,不会互相干扰。
  • 把while循环条件改成while True,配合break退出,比原来反复判断type更清晰(毕竟type在函数执行过程中不会改变)。
  • 用user_input.lower() == "q"简化了大小写判断,不用写两次条件。
  • 修正了else里的双重否定错误。
  • 把打印语句放到对应type的分支内,确保"A"时打印items和total,"T"时只打印total,不会出现多余输出。

这样你再测试的话,两种type的逻辑就完全符合你的需求啦~

内容的提问来源于stack exchange,提问作者yeah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:14:46