变量不在Python中存储正确的值

时间:2017-03-22 19:18:07

标签: python

所以我在python中编写了一个程序,尝试将输入的数字转换为该数字的字母版本。例如:323 - >三百二十三 我遇到的问题是,当进程完成并显示输出时,其中一个变量没有显示正确的值。所需的输出看起来像这样:

Enter a number under 999: 323
323 -> three hundred twenty-three

但是看起来像这样:

Enter a number under 999: 323
23 -> three hundred twenty-three

如果有人能帮助我解决这个问题,我将不胜感激。这是我的代码:

from __future__ import print_function, division
import sys
input = raw_input

n = int(input("Enter a number under 999: "))

if n >= 999:
print("Well, you didn't follow directions.")
sys.exit(1)

word = ""
hundred = n//100
if hundred == 1:
    word += "one hundred"
elif hundred == 2:
    word += "two hundred"
elif hundred == 3:
    word += "three hundred"
elif hundred == 4:
    word += "four hundred"
elif hundred == 5:
    word += "five hundred"
elif hundred == 6:
    word += "six hundred"
elif hundred == 7:
    word += "seven hundred"
elif hundred == 8:
    word += "eight hundred"
elif hundred == 9:
    word += "nine hundred"  
if hundred > 0:
    word += " "
n = n%100
if n == 10:
    word += ' ten'
elif n == 11:
    word += ' eleven'
elif n == 12:
    word += ' twelve'
elif n == 13:
    word += ' thirteen'
elif n == 14:
    word += ' fourteen'
elif n == 15:
    word += ' fifteen'
elif n == 16:
    word += ' sixteen'
elif n == 17:
    word += ' seventeen'
elif n == 18:
    word += ' eighteen'
elif n == 19:
    word += ' nineteen'
else:
    ones = n%10
    tens = n//10
    if tens == 2:
        word += "twenty"
    elif tens == 3:
        word += "thirty"
    elif tens == 4:
        word += "fourty"
    elif tens == 5:
        word += "fifty"
    elif tens == 6:
        word += "sixty"
    elif tens == 7:
        word += "seventy"
    elif tens == 8:
        word += "eighty"
    elif tens == 9:
        word += "ninety"

    if tens > 0 and ones > 0:
        word += '-'

    if ones == 1:
        word += 'one'
    elif ones == 2:
        word += 'two'
    elif ones == 3:
        word += 'three'
    elif ones == 4:
        word += 'four'
    elif ones == 5:
        word += 'five'
    elif ones == 6:
        word += 'six'
    elif ones == 7:
        word += 'seven'
    elif ones == 8:
        word += 'eight'
    elif ones == 9:
        word += 'nine'

print("{} -> {}".format(n, word))

哦,顺便说一下,我的班级正在学习python 3,同时使用python 2解释器,这就是为什么代码有一些奇怪的方面。

2 个答案:

答案 0 :(得分:1)

    preg_replace_callback("/(\/(.*?)\.htm)/", "HandleLinks", $filenames); 

变异“n”,你需要先“保存”“n”的值。最简单的方法是:

声明后

n = n%100

将另一个变量设为n

n = int(input("Enter a number under 999: "))

然后替换

n = int(input("Enter a number under 999: "))
num = n

print("{} -> {}".format(n, word))

答案 1 :(得分:0)

将您的代码更改为

n = int(input("Enter a number under 999: "))
user_number = n
(...)
print("{} -> {}".format(user_number, word))

每次在n上进行操作时,都要对其进行修改:

n = n%100

所以在修改它之前将它保存在另一个变量中(user_number)并在最后打印它。