1. 程式人生 > >Python3 計算A+B+C,輸入為一行,包括了用空格分隔的三個整數 A,B,C

Python3 計算A+B+C,輸入為一行,包括了用空格分隔的三個整數 A,B,C

問題:
輸入為一行,包括了用空格分隔的三個整數 A、B、C(資料範圍均在−40 ~ 40 之間)。輸出為一行,為“A+B+C”的計算結果。

程式碼實現:

sum = 0

#或者直接用split()

for x in input().split(' '):
    sum = sum+int(x)

print(sum)

解釋:
for x in …迴圈就是把每個元素代入變數x,然後執行縮排塊的語句;

split()通過指定分隔符對字串進行切片,如果引數num 有指定值,則僅分隔 num 個子字串。

語法:
split()方法語法:

str.split(str=”“, num=string.count(str))

引數

  • str – 分隔符,預設為所有的空字元,包括空格、換行(\n)、製表符(\t)等。
  • num – 分割次數。

返回值
返回分割後的字串列表。

例項

str = "this is string example....wow!!!"
print (str.split( ))
print (str.split('i',1))
print (str.split('w'))

輸出

['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string
example....', 'o', '!!!']