爲input
的文檔已經說明了這一點:
該函數然後從輸入中讀取一行,將其轉換爲字符串(剝離尾隨換行符),並返回該行。
所以你的ui
是一個字符串,但你的字典中的鍵是數字。所以它找不到任何匹配(因爲2 != '2'
)並且產生了KeyError
。已經通過@讓FrançoisFabre提到
當你需要將其轉換爲整數:
ui = input('type a number from 1 to 303: ')
if len(ui) == 3:
ones_ui = int(ui[2])
tens_ui = int(ui[1])
hund_ui = int(ui[0])
elif len(ui) == 2:
ones_ui = int(ui[1])
tens_ui = int(ui[0])
elif len(ui) == 1:
ones_ui = int(ui[0])
else:
print('ups')
或者更好的扭轉字符串,然後每個數字映射到一個整數:
ui = input('type a number from 1 to 303: ')
nums = list(map(int, ui[::-1]))
對於輸入爲20
的示例返回[0, 2]
如果使用索引,那麼你需要改變你的字典了一下:
ones = {1 : "I", 2 : "II", 3 : "III", 4 : "IV", 5: "V", 6 : "VI", 7 : "VII", 8 : "VIII", 9 : "IX", 0: ""}
tens = {1 : "X", 2 : "XL", 3 : "XXX", 4 : "XL", 5 : "L", 6 : "LX", 7 : "LXX", 8 : "LXXX", 9 : "XC", 0: ""}
hun = {1 : "C", 2 : "CC", 3 : "CCC", 0: ""}
我加入了數0
到所有的人,因爲你不需要特殊的情況他們,你可以去把這些:
print(''.join([dct[val] for val, dct in zip(nums, (ones, tens, hun))][::-1]))
[::-1]
在連接所有零件之前再次反轉所得到的字符串。
樣品:
type a number from 1 to 303: 10
X
type a number from 1 to 303: 303
CCCIII
type a number from 1 to 303: 158
CLVIII
type a number from 1 to 303: 19
XIX
我使用的代碼是:
ones = {1 : "I", 2 : "II", 3 : "III", 4 : "IV", 5: "V", 6 : "VI", 7 : "VII", 8 : "VIII", 9 : "IX", 0: ""}
tens = {1 : "X", 2 : "XL", 3 : "XXX", 4 : "XL", 5 : "L", 6 : "LX", 7 : "LXX", 8 : "LXXX", 9 : "XC", 0: ""}
hun = {1 : "C", 2 : "CC", 3 : "CCC", 0: ""}
ui = input('type a number from 1 to 303: ')
nums = list(map(int, ui[::-1]))
print(''.join([dct[val] for val, dct in zip(nums, (ones, tens, hun))][::-1]))
也許我們應該適應問題的「稱號」 - 因爲它已經成爲誤導,現在的答案你清除了霧;-) – Dilettant
@Dilettant完成 –