[英]This Python code basically prompts the user to type their valid phone number and tries to produces equivalent word for each digit in phone number
編譯器在運行時吐出 KeyError: '9'。 有人可以幫我從這段代碼中省略上述錯誤嗎? 提前致謝!
phone = input("Phone: ")
if len(phone) < 10:
print("Phone number should be at least 10 digit long!")
else:
li = []
for item in range(0, 10, 1):
li.append(phone[item])
print(li)
word_num = {
0: "Zero",
1: "One",
2: "Two",
3: "Three",
4: "Four",
5: "Five",
6: "Six",
7: "Seven",
8: "Eight",
9: "Nine"
}
for item in li:
print(word_num[int(item)])
因為電話號碼中的字符是字符串,所以字典鍵必須是字符串:
word_num = {
"0": "Zero",
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four",
"5": "Five",
"6": "Six",
"7": "Seven",
"8": "Eight",
"9": "Nine"
}
您的代碼中還有其他問題。 最后一個 for 循環應該是:
for item in li:
print(word_num[item])
此外,如果電話號碼長度小於 10,則需要停止代碼執行,否則程序會嘗試打印尚不存在的li
。
word_num
的鍵為int
,但您試圖以word_num['0']
而不是word_num[0]
的形式訪問它們。 此外,最后一個for
循環應該是:
for item in li:
for item in range(0, 10, 1):
的for
循環可以重寫為:
for item in range(10):
phone = input("Phone: ")
if len(phone) < 10:
print("Phone number should be at least 10 digit long!")
else:
li = []
for item in range(10):
li.append(phone[item])
print(li)
word_num = {
0: "Zero",
1: "One",
2: "Two",
3: "Three",
4: "Four",
5: "Five",
6: "Six",
7: "Seven",
8: "Eight",
9: "Nine"
}
for item in li:
print(word_num[int(item)]) # convert item to int
Phone: 0123456789
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
Zero
One
Two
Three
Four
Five
Six
Seven
Eight
Nine
編輯 1:如果輸入少於 10 個字符,則什么也不做。
您的代碼有很多問題。 您需要確保作為phone
一部分輸入的每個字符實際上都是一個數字。 然后您必須將字符串值轉換為 int 才能使用它來索引word_num
。 最后,如果用戶輸入的內容少於 10 個字符,您會因為li
未初始化而失敗。
import re
while True:
phone = input("Phone: ")
if len(phone) >= 10 and re.fullmatch(r'[0-9]+', phone):
break
print("Phone number should be at least 10 digit long!")
li = [int(d) for d in phone]
print(li)
word_num = {
0: "Zero",
1: "One",
2: "Two",
3: "Three",
4: "Four",
5: "Five",
6: "Six",
7: "Seven",
8: "Eight",
9: "Nine"
}
for item in li:
print(word_num[item])
樣品運行:
Phone: aaa
Phone number should be at least 10 digit long!
Phone: a012349499595
Phone number should be at least 10 digit long!
Phone: 1234567890
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
One
Two
Three
Four
Five
Six
Seven
Eight
Nine
Zero
如果您在程序開始時定義“li”,那么它就可以正常工作。
我無法粘貼代碼,所以這里有一個鏈接001.py
你需要像這樣重寫最后一個for循環
for item in li:
print(word_num[item])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.