Python代码问题。目标是在输入期间编码后缀

时间:2015-11-14 08:48:10

标签: python python-3.x

目标:编写一个以整数作为唯一参数的函数,并返回该整数的序号缩写作为唯一结果。例如,如果你的函数传递整数1,那么它应该返回字符串" 1st"。如果它传递整数12那么它应该返回字符串" 12th"。如果它是通过2003那么它应该返回字符串" 2003rd"。您的功能不得在屏幕上打印任何内容。

def convert (n):
    self.num = num
    n = int(self.num)
    if 4 <= n <= 20:
         suffix = 'th'
    elif n == 1 or (n % 10) == 1:
         suffix = 'st'
    elif n == 2 or (n % 10) == 2:
         suffix = 'nd'
    elif n == 3 or (n % 10) == 3:
        suffix = 'rd'
    elif n < 100:
        suffix = 'th'
    ord_num = str(n) + suffix
    return ord_num

def main ():

    day = int(input("Enter the day:"))
    month = int(input("Enter the month:"))
    year = int(input("Enter the year:"))

    print("on the %n" %n, convert(day), "day of the %n" %month,
          convert(month), "month of the %n" %year, convert(year),",
          something amazing happened!")

    main()

这是我的代码,但它一直说我在运行时没有定义n。但是上面我已经定义了它,所以不确定问题是什么。

1 个答案:

答案 0 :(得分:0)

这可能更接近你想要的东西:

def convert(n):
    n = int(n)
    suffix = ''
    if 4 <= n <= 20:
         suffix = 'th'
    elif n == 1 or (n % 10) == 1:
         suffix = 'st'
    elif n == 2 or (n % 10) == 2:
         suffix = 'nd'
    elif n == 3 or (n % 10) == 3:
        suffix = 'rd'
    elif n < 100:
        suffix = 'th'
    return str(n) + suffix


def main ():
    day = int(input("Enter the day: "))
    month = int(input("Enter the month: "))
    year = int(input("Enter the year: "))

    print("on the %s day of the %s month of the %s, something amazing happened!" %
          (convert(day), convert(month), convert(year)))

main()

几乎没有问题。在n中定义时,您无法在main()中使用convert()%n也不是有效的格式字符。当需要通过转换函数运行年份时,您需要定义suffix = '',因为年份可能大于100.此外,您可能从类定义中复制了代码。我删除了self