目标:编写一个函数,将整数作为其唯一参数,并返回该整数的序数缩写作为其唯一结果。例如,如果传递给函数的是整数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当我运行它。但是上面我已经定义了,所以不确定问题是什么。你知道吗
这可能更接近你想要的:
问题很少。在
convert()
中定义时,不能在main()
中使用n
。而且%n
不是有效的格式字符。您需要定义suffix = ''
当您还希望通过转换函数运行年份时,因为年份可以大于100。另外,您可能从类定义中复制了代码。我删除了self
。你知道吗相关问题 更多 >
编程相关推荐