数字转换器只在第二次尝试时工作



这是一个简单的控制台应用程序,它只提供一个电话号码并用字母书写,但问题是你需要先输入一个数字,它在第一个数字之后开始工作。

print("---Give numbers by letters---"+"n")
#number=input("Phone: ")
number_convertor={
"0":"oh",
"1":"one",
"2":"two",
"3":"three",
"4":"four",
"5":"five",
"6":"six",
"7":"seven",
"8":"eight",
"9":"nine"
}
while True:
result=""
number=input("Phone: ")
for ch in number:
result+=number_convertor.get(ch,"!")+" "
print(result)

输出:

---Give numbers by letters---
Phone: 0
Phone: 0
oh
Phone: 0
oh
Phone: 0
oh
Phone:

当我删除第2行时,它会打印多次!

---Give numbers by letters---
Phone: 021
oh
oh two
oh two one
Phone:

1-您提示用户输入2次

2-最终打印不必在for循环内,而是在循环外。

试试这个,你就不需要while循环了。

print("---Give numbers by letters---"+"n")
number_convertor={
"0":"oh",
"1":"one",
"2":"two",
"3":"three",
"4":"four",
"5":"five",
"6":"six",
"7":"seven",
"8":"eight",
"9":"nine"
}
result=""
number=input("Phone: ")
for ch in number:
result+=number_convertor.get(ch,"!")+" "
print(result)

有两个错误;丢弃第一个input的结果,并在生成result时重复打印。

如果您只想一次打印一个数字,则无需将任何内容收集到result中。

第一个print可能在字典初始化后与其他I/O一起执行更有意义。我还建议简化初始化。

numbers = "oh one two three four five" 
" six seven eight nine ten".split()
print("---Give numbers by letters---")
while True:
sep = ""
number = input("Phone: ")
for ch in number:
print("%s%s" % (sep, numbers[int(ch)]), end=sep)
sep = " "
print()

相关内容

  • 没有找到相关文章

最新更新