Python代码有问题。目的是在inpu过程中对后缀进行编码

2024-04-27 02:48:07 发布

您现在位置:Python中文网/ 问答频道 /正文

目标:编写一个函数,将整数作为其唯一参数,并返回该整数的序数缩写作为其唯一结果。例如,如果传递给函数的是整数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当我运行它。但是上面我已经定义了,所以不确定问题是什么。你知道吗


Tags: orthe函数字符串convertinput整数year
1条回答
网友
1楼 · 发布于 2024-04-27 02:48:07

这可能更接近你想要的:

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()

问题很少。在convert()中定义时,不能在main()中使用n。而且%n不是有效的格式字符。您需要定义suffix = ''当您还希望通过转换函数运行年份时,因为年份可以大于100。另外,您可能从类定义中复制了代码。我删除了self。你知道吗

相关问题 更多 >