【问题标题】:python output for addition [duplicate]用于添加的python输出[重复]
【发布时间】:2017-02-11 04:58:24
【问题描述】:

我是 python(2.7 版)的新手,我想知道如何在一行中输入两个数字并计算这两个数字的总和。我正在寻找这样的输出:

11 + 11 = 22

输入看起来像这样:

11 11

【问题讨论】:

  • 使用raw_inputstr.split

标签: python input output addition


【解决方案1】:

你可以这样做:

a = raw_input("Enter numbers separated by space: ").split() # input() for Python3 
print ' + '.join(a) + ' = ' + str(sum(map(int, a)))         # print() for Python3

输出:

Enter numbers separated by space: 2 34 234
2 + 34 + 234 = 270

或者这里有些不同:

def add():
    ans = None
    while ans not in ['q', 'quit', '']:
        ans = input('> ')
        print(sum(map(int, ans.strip().split(' ')))

add()

还有,解释如下:

def add():
    ans = None
    while ans not in ['q', 'quit', '']: # stops if you type 'q', 'quit', or nothing
        ans = input('> ') # for python 3
        ans = raw_input('> ') # for python 2
        # it asks the user for a string
        ans.strip() # remove the spaces at the end and at the beginning of the string
        ans.split(' ') # splits the string each time it sees a space (so, you get a list)
        map(int, ans.strip().split(' ') # because we splited a string, we have a list of string.
        # Here, we transform them to integer, so we can add them. map() calls a function (here
        # int) on every element of the array we passed as the second argument
        sum(...) # sum is a function that takes a list and adds every number that it contains
        print(...) # you know what that does ;)
        # not that one python 2, you don't need the parentheses 

add() # call our function

【讨论】:

    【解决方案2】:

    由于您是该语言的新手,我认为最好使用更简单的答案。所以我的做法是

    nums = input("Enter two integers: ")
    nums.split(' ')
    print nums[0]
    print nums[1]
    print '11 ','+ ','11 ','=', 11+11
    
    # OR
    
    nums = input("Enter two integers: ")
    numList = nums.split(',')
    nums = [int(x) for x in numList]
    print '11',' + ','11',' = ', nums[0]+nums[1]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-01
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多