我正在尝试将1到99之间的数字转换为单词形式,大于20的数字打印为“二十一”,“二十二”等等。不知道我的代码中缺少什么。
zero2nineteen = ['zero', 'one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine', 'ten',
'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen',
'sixteen', 'seventeen', 'eighteen', 'nineteen']
zero2ninety = ['zero', 'ten', 'twenty', 'thirty', 'fourty',
'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
def number(Number):
if (Number >= 1) or (Number <= 19):
return (zero2nineteen[Number])
elif (Number >= 20) or (Number <= 99):
return (zero2ninety[Number])
else:
print("Done")
def main():
Number = int(input("Please enter a number between 0 and 99: "))
number(Number)
main()
答案 0 :(得分:1)
首先,尽量避免对变量名使用大写单词 - 它们主要用于class
定义。除此之外,您的转换逻辑不正确。您的number()
方法会被修改,以便产生正确的结果:
def number(n):
# 1. Rename variable
# 2. Change "or" to "and"
# If the number is between 0 and 19 (inclusive), refer directly to zero2nineteen list
if (n >= 0) and (n <= 19):
return (zero2nineteen[n])
# If the number is between 20 and 99 (inclusive):
elif (n >= 20) and (n <= 99):
# First check if the number is a multiple of ten
if not n % 10:
# If it is, refer directly to the zero2ninety list
return (zero2ninety[n // 10])
# Else, use the zero2ninety list in conjunction with zero2nineteen
return (zero2ninety[n // 10] + "-" + zero2nineteen[n % 10])
# If the number is not between 0 and 99 inclusive, exit
else:
print("Done")
希望这有帮助!
答案 1 :(得分:0)
导入变形 p = inflect.engine() p.number_to_words(99) 99