常用的輸入方式
s = input() # 會輸入一行,讀進來 a 是一個字串。
a = int(s) #s 轉換為整數
a = int(input()) # 將輸入的字串轉換為整數,整數才能加減乘除
n = int(input('please input n:')) # 可以輸出一段訊息再讀入
所以其實 input() 是一個函數,他會回傳輸入的一行文字。
如何在同一行輸入兩個整數(空白間格):
a,b = map(int, input().split())
input().split() 的作用:將 input()字串以空白間格切斷成多個字串。試試
a,b = "foo bar".split()
map() 的作用:map(某函數名, 一些東西,可能是個 list) 把這些東西一一丟進該函數運作。
在一行輸入三個整數的方法:
a,b,c = map(int, input().split())
.split() (翻譯:分開)
a,b = "foo bar".split() # 變成 ["foo", "bar"]
print(a,b) # foo bar
c,d = "Aa,Bb".split(",")
print(c,d) # Aa Bb
map()
map(某函數名, 一些東西) 把這些東西一一丟進該函數運作。
nums = ["1", "2", "3"]
result = map(int, nums)
這時 result = [ int("1"), int("2"), int("3") ]
nums = ["1", "2", "3"]
a, b, c = map(int, nums)
print(a, b, c) # 1 2 3