私はPython(バージョン2.7)が新しく、1行に2つの数値を入力して両方の数値の合計を計算する方法を知りたいと思います。私はこのように読み取るために出力を探しています:追加のためのpython出力
11 + 11 = 22
入力は次のようになります。
私はPython(バージョン2.7)が新しく、1行に2つの数値を入力して両方の数値の合計を計算する方法を知りたいと思います。私はこのように読み取るために出力を探しています:追加のためのpython出力
11 + 11 = 22
入力は次のようになります。
あなたがそうのようにそれを行うことができます。
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
ORここにある別の何か:
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
あなたは言語に新しいしていることから、私は単純な答えは最高だと思います。だから、私はそれについて行くだろう方法は
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]
'raw_input'と' str.split'を使います。 –