【问题标题】:How to create an addition function using a while loop?如何使用 while 循环创建加法函数?
【发布时间】:2018-11-02 01:34:31
【问题描述】:

当我选择报告类型“A”时,我需要弄清楚如何打印所有输入以及总数。当我选择报告类型“T”时,它只按计划提供总数。如果我选择报告类型“A”,它会给我输入“Q”加上所有输入的总和。

def addition_function():
  sum = 0

while True:
    add = input("Enter a number to add or \"Q\" to quit:")
    if add.isdigit() == True:
        sum = sum + int(add)
    elif add.lower() == "q":
        rep_type = input("Enter report type (A/T):")
        if rep_type.lower() == "a":
            return print(add,sum)
            break
        elif rep_type.lower() == "t":
            return print("Total =",sum)
            break
        else:
            print("Invalid input.")
    else:
        print("Invalid input.")

addition_function()

【问题讨论】:

  • 你应该添加一个语言标签。
  • 代码复制粘贴的不太好。
  • 那不重要了。如果我知道它是什么语言,我会为你标记这个。它将帮助您找到问题。
  • 我正在使用 Python 3。
  • 不是您问题的答案,但这里的 return 语句什么也不做。 (因为你不在函数内部。如果你在,他们会结束函数的执行,看起来你不希望这样。)

标签: python python-3.x function


【解决方案1】:

您可以使用列表来跟踪用户输入的所有数字,并在用户输入“A”时打印它,并使用该变量来打印它们:

def addition_function():
    sum = 0
    nums_entered = []

    while True:
        add = input("Enter a number to add or \"Q\" to quit:")
        if add.isdigit() == True:
            nums_entered.append(add)
            sum = sum + int(add)
        elif add.lower() == "q":
            rep_type = input("Enter report type (A/T):")
            if rep_type.lower() == "a":
                return print(nums_entered,sum)
            elif rep_type.lower() == "t":
                return print("Total =",sum)
            else:
                print("Invalid input.")
        else:
            print("Invalid input.")

addition_function()

【讨论】:

    猜你喜欢
    • 2018-12-13
    • 2021-04-30
    • 2014-04-16
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 2012-10-07
    • 2015-02-11
    • 1970-01-01
    相关资源
    最近更新 更多