【问题标题】:I am writing a program which adds numbers inputed by the user and then outputting the total. With the total how can i output all the inputed numbers我正在编写一个程序,它将用户输入的数字相加,然后输出总数。有了总数,我如何输出所有输入的数字
【发布时间】:2018-11-29 11:57:24
【问题描述】:

例如我是用户,我输入 1 然后 3 然后 7 然后 5

我会得到输出 16,但我怎样才能显示我输入的数字,即 1,3,7,5

【问题讨论】:

  • 发布您的错误代码和尝试
  • 将您的输入一一保存到列表中,然后最终打印出来:)
  • 你能告诉我们输出16的代码吗?
  • inputs = [input('Enter Number:') for _ in range(4)]; print('+'.join(inputs), ,'=',sum(map(int,inputs))
  • 你试过什么没用?

标签: python python-3.x


【解决方案1】:

您可以简单地将所有输入存储在一个列表中并在最后打印出来。

inputs = []
#for each input
inputs.append(userinput)

for value in inputs:
    print(value)

如果您希望数字采用 1、3、7、5 格式,请使用

numbers = ",".join(str(value) for value in inputs) 
print(numbers)

【讨论】:

    【解决方案2】:

    您可以使用变量来存储用户输入,下面是两个数字之和的示例代码 n1 = int(input()) n2 = int(input()) s = n1 + n2 print(n1, n2, s)

    【讨论】:

      【解决方案3】:

      最常见的代码:

      假设您有以下代码:

      num1 = int(input())
      num2 = int(input())
      num3 = num1+num2
      print(num3)
      

      现在,你想要显示 num1 和 num3,所以你只需要执行以下操作即可。

      num1 = int(input())
      num2 = int(input())
      num3 = num1+num2
      print(num3)
      print(num1)
      print(num2)
      

      【讨论】:

        【解决方案4】:

        检查一下:

        >>> inputs = [input('Enter Number [%d]:' % (i+1)) for i in range(4)]
        Enter Number [1]:1
        Enter Number [2]:3
        Enter Number [3]:5
        Enter Number [4]:7
        
        >>> print('{}={}'.format('+'.join(inputs), sum(map(int,inputs))))
        1+3+5+7=16
        

        【讨论】:

        • 第一行代码抛出Type Error: TypeError: must be str, not int,改成这样inputs = [input('Enter Number [%d]:' %(i+1)) for i in range(4)]
        • 错过了大括号。现在修复。谢谢。
        【解决方案5】:
        a = input('number: ').split()
        print (a, sum(int(_) for _ in a))
        

        【讨论】:

          猜你喜欢
          • 2014-12-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-08
          • 1970-01-01
          相关资源
          最近更新 更多