【问题标题】:How can I fix unnecessary print statements from being printed while i run this function containing two while loops?当我运行这个包含两个while循环的函数时,如何修复不必要的打印语句?
【发布时间】:2018-07-11 16:50:39
【问题描述】:

如您所见,我很新,我什至无法表达我的问题,但我的问题是当您退出循环时类型为“A”,当我只需要项目和总计时,它会打印出项目和总计两次.其次,当类型为“T”时,我只希望在退出循环时打印总数,但它会打印出我第一个循环所需的上述语句。

def ar(type):
    total = 0
    items = ""
    print("Input an integer to add to the total or \"Q\" to quit")
    while type == "A":
        user_input = input("Enter an integer or \"Q\": ")
        if user_input.isdigit():
            items += user_input + "\n"
            total += int(user_input)
        elif user_input == "q":
            break
        elif user_input == "Q":
            break
        else:
            print(user_input, " is not an invalid input")
    print("Items \n" + items) 
    print("\nTotal \n" + str(total))          
    while type == "T":
        user_input = input("Enter an integer or \"Q\": ")
        if user_input.isdigit():
            total += int(user_input)
        elif user_input == "q":
            break
        elif user_input == "Q":
            break
        else:
            print(user_input, " is not an invalid input")
    print("\nTotal \n" + str(total))

这是输出的样子:

输入一个整数加到总数或“Q”退出

输入一个整数或“Q”:3

输入一个整数或“Q”:6

输入一个整数或“Q”:24

输入一个整数或“Q”:17

输入一个整数或“Q”:61

输入一个整数或“Q”:九

九个无效输入

输入一个整数或“Q”:q

物品

3

6

24

17

61

总计

111

用“T”调用(只打印总数)

输入一个整数加到总数或“Q”退出

输入一个整数或“Q”:5

输入一个整数或“Q”:7

输入一个整数或“Q”:退出

总计

12

这是我的输出的样子:

如果我调用 ar("A")

输入一个整数加到总数或“Q”退出

输入一个整数或“Q”:3

输入一个整数或“Q”:6

输入一个整数或“Q”:24

输入一个整数或“Q”:17

输入一个整数或“Q”:61

输入一个整数或“Q”:九

九个无效输入

输入一个整数或“Q”:q

物品

3

6

24

17

61

总计

111

总计

111

如果我用 ar("T") 调用

输入一个整数加到总数或“Q”退出

物品

总计

0

输入一个整数或“Q”:5

输入一个整数或“Q”:7

输入一个整数或“Q”:退出

总计

12

附言这不是硬件,我正在参加关于 edx 的免费课程,这只是练习。

【问题讨论】:

  • 你可能想试试这个方法:rubberduckdebugging.com - 这看起来像个笑话,但你会惊讶于严格应用它的效果。我个人改用毛绒企鹅,但效果也一样。

标签: python printing while-loop


【解决方案1】:

几件事:

print("\nTotal \n" + str(total))

在您的代码中出现两次 - 在每个 while 之后出现一次。如果您需要在这两种情况下打印总数,请删除第一个 while 之后的那个,只保留文件末尾的那个。

你可以改变

elif user_input == "q": break elif user_input == "Q": break

elif user_input == "q" or user_input == "Q":
    break

type 是您的函数接收的变量,它在函数中不会改变。没有理由使用while,可以使用if type == 'A': ... elif type == 'T': ...命令

【讨论】:

  • elif user_input.lower() == "q"
  • elif user_input in ("q","Q")
  • 要求我在代码中包含一个while循环。我正在考虑将其更改为 while True: 并将我的所有代码放入其中。
猜你喜欢
  • 2015-06-12
  • 1970-01-01
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多