我用Python 3,Windows 10,PyCharm工作。
我正在构建一个小程序,让你输入你的年龄并返回 "Happy {age}{termination, eg: st, nd}!"。
问题是,我想以某种方式避免这样的情况,即你将你的年龄写成1041岁,然后它就会说 "第1041次快乐!"。所以我用了 list(range(21, 1001, 10))
例如,终止符 "st"。然而,我希望能够使用 infinite
而不是1001。如果我用 math.inf
我的代码中不接受这个浮点数。另外,我也不能把它转换为int。
我想用一个 n
比100还高的数字,并且有 list(range(21, n, 10))
但我是个初学者,不知道怎么做,谢谢你的帮助。这是我的代码。
age = int(input('Type age: '))
if int(age) == 1:
term = 'st'
elif int(age) == 2:
term = 'nd'
elif int(age) == 3:
term = 'rd'
elif int(age) in list(range(21, 1001, 10)):
term = 'st'
elif int(age) in list(range(22, 1002, 10)):
term = 'nd'
elif int(age) in list(range(23, 1003, 10)):
term = 'rd'
else:
term = 'th'
if int(age) >= 130:
print("C'mon! you can't be THAT old, you geezer!\nStill, here you go:")
message = f"Happy {age}{term} birthday!"
print(message)
没有理由在一个庞大的系统中检查成员资格。list
这会占用大量的内存。你可以直接查看你的年龄 endswith
.
age = input('Type age: ')
if age.endswith('11') or age.endswith('12') or age.endswith('13'):
term = 'th'
elif age.endswith('1'):
term = 'st'
elif age.endswith('2'):
term = 'nd'
elif age.endswith('3'):
term = 'rd'
else:
term = 'th'
if int(age) >= 130:
print("C'mon! you can't be THAT old, you geezer!\nStill, here you go:")
message = f"Happy {age}{term} birthday!"
print(message)
模数运算是解决这个问题的一个更好的(完全通用的)方法。
age = int(input('Type age: '))
if 11 <= (age % 100) <= 13:
term = 'th'
elif age % 10 == 1:
term = 'st'
elif age % 10 == 2:
term = 'nd'
elif age % 10 == 3:
term = 'rd'
else:
term = 'th'
if age >= 130:
print("C'mon! you can't be THAT old, you geezer!\nStill, here you go:")
message = f"Happy {age}{term} birthday!"
print(message)
你不需要把它改成list, 如果你把它改成list,可能会出错. 你只要输入 age in range(s, e, i)
. 如果你想要更高的,比如无穷大,就用这样的方法。age in range(21, sys.maxsize**100, 10)
import sys
inf = sys.maxsize**10
age = int(input('Type age: '))
if int(age) == 1: term = 'st'
elif int(age) == 2: term = 'nd'
elif int(age) == 3: term = "rd"
elif int(age) in range(21, inf, 10): term = 'st'
elif int(age) in range(22, inf, 10): term = "nd"
elif int(age) in range(23, inf, 10): term = 'rd'
else: term = 'th'
if int(age) >= 130:
print("C'mon! you can't be THAT old, you geezer!\nStill, here you go:")
message = f"Happy {age}{term} birthday!"
print(message)
但是,你为什么要使用 range
如果有比它更容易?就像让它成为 string
然后检查最后一个数字。
age = int(input("Type age: "))
term = ["st", "nd", "rd", "th"][3 if age%10 > 3 or age%100 in range(10, 20) else age%10-1]
if age > 130: message = "blah-blah-blah"
print(message)
是的,我知道结果是不同的。但是,接下来我给你看的代码也可以处理高于百的数字。比如101,在你的代码中会是第101次,我想这是不对的。变量 term
我有投入 ternary operator
或 conditional expression
.在Python中 [if_true] if [condition] else [if_false]
在JS中 condition? if_true:if_false