我是python的初级程序员,我需要一些代码方面的帮助。附件是我一直在工作的代码。其目的是取一个美元金额,如305.67,并将其转换为文本短语,如“三百零五美元六十七美分”。到目前为止,我已经得到了大部分的代码来将它分解成文本,但是我仍然对数字11-19有问题,这是一个特殊情况。我需要帮助来弄清楚程序如何决定在哪里正确地应用11-19,以及在不需要时何时删除“零”字符串。如果你运行这个程序,你就会明白我的意思了。下面main函数中的循环将根据函数的需要运行循环。另外,还有一个名为“getDollarFormatText”的函数,它将获取货币的数字版本,如305.67或45.13,并给出它的文本格式。我遇到的问题是如何让程序忽略小数点,然后将所有内容适当地转换到小数点左右的位置。这是一个沉重的问题,我将非常感激。基本上这个问题很容易解决,但我不知道如何解决它。代码从一个处理两位数的函数开始(我已经处理了只由一位数分隔的函数)。在
def getWordForTwoDigits(amount):
#This value uses integer division to get the number of tens within a number.
tensAmount = int(amount) / 10
#This variable uses the first function above to find the equivalent single number within the number given using modulo. (Zero through 9)
singlesWord = getWordForDigit(int(amount)%10)
#For this decision structure, the structure is set to figuring out the number of tens within a number and appropriately naming it after its correct name (ten, twenty, etc.)
if tensAmount == 1:
wordTen = "TEN"
else:
if tensAmount == 2:
wordTen = "TWENTY"
else:
if tensAmount == 3:
wordTen = "THIRTY"
else:
if tensAmount == 4:
wordTen = "FORTY"
else:
if tensAmount == 5:
wordTen = "FIFTY"
else:
if tensAmount == 6:
wordTen = "SIXTY"
else:
if tensAmount == 7:
wordTen = "SEVENTY"
else:
if tensAmount == 8:
wordTen = "EIGHTY"
else:
if tensAmount == 9:
wordTen = "NINETY"
return "%s-%s"%(wordTen, singlesWord)
########################################
def getWordForThreeDigits(dolamount):
hundredAmount = int(dolamount) / 100
twoDigits = getWordForTwoDigits(int(dolamount) % 100)
if hundredAmount == 0:
return twoDigits
else:
if hundredAmount == 1:
wordHun = "ONE HUNDRED"
else:
if hundredAmount == 2:
wordHun = "TWO HUNDRED"
else:
if hundredAmount == 3:
wordHun = "THREE HUNDRED"
else:
if hundredAmount == 4:
wordHun = "FOUR HUNDRED"
else:
if hundredAmount == 5:
wordHun = "FIVE HUNDRED"
else:
if hundredAmount == 6:
wordHun = "SIX HUNDRED"
else:
if hundredAmount == 7:
wordHun = "SEVEN HUNDRED"
else:
if hundredAmount == 8:
wordHun = "EIGHT HUNDRED"
else:
if hundredAmount == 9:
wordHun = "NINE HUNDRED"
return "%s %s"%(wordHun, twoDigits)
####################################
def getDollarFormatText(dollarAndCents):
#how would you separate 190.67 (example) to 190 and 67 and and give the text form for eacn
使用
elif
代替这是快速解决办法。 对于,零件要处理11-19,之前
^{pr2}$使用
但我强烈建议你用字典,让你这样开始。在
为了您的练习,我们采用了现有的nice解决方案ref将数字转换为单词,如下所示:
结果:
^{pr2}$注意,它适用于整数。然而,将一个浮点数分成两个整数部分并不重要。在
好吧。。。这里有很多问题。让我们从一些基本的语法开始。在
首先,您需要回顾一下Python中格式化的工作原理。它的工作空间为4,如果您使用的是正确的处理器,则相当于“tab”。当您定义一个函数时,该函数中包含的所有内容都应该至少超出4个空格。在函数“getWordForTwoDigits()”中,可以看到:
返回值应该是四个空格(顺便说一句,这两个函数都是这样做的)。在
第二,你的else if结构是扭曲和不必要的。不要像现在这样,只需这样做:
^{pr2}$然后再加上“elif”到9。在
还有,你说
但你从来没有定义过这个函数。在
对于如何区分196和97的实际问题,请尝试以下方法:
“rsplit”基本上根据第一个参数中的字符将字符串分成两部分。它返回一个list[“partone”,“parttwo”],因此您需要提取列表的两个部分,并将它们转换回主代码中的int。在
希望有帮助!在
相关问题 更多 >
编程相关推荐