【发布时间】:2021-04-07 01:14:34
【问题描述】:
例如,我想动态找到正确的序数根:
111 = 111st
112 = 112nd
113 = 113rd ...
我尝试了其他解决方案,但找不到好的解决方案。
这是我的代码:
for number in range(1, 114):
print(number)
ex1 = 11
ex2 = 12
ex3 = 13
if number == ex1:
print("is the " + str(number) + "th number.")
elif number % 10 == 1 or not ex1:
print("is the " + str(number) + "st number.")
elif number == ex2:
print("is the " + str(number) + "nd number.")
elif number % 10 == 2 or not ex2:
print("is the " + str(number) + "nd number.")
elif number == ex3:
print("is the " + str(number) + "rd number.")
elif number % 10 == 3 or not ex3:
print("is the " + str(number) + "rd number")
else:
print("is the " + str(number) + "th number.")
【问题讨论】:
-
我真的不明白你想要完成什么。是不是只想“1是第1个数字”“2是第2个数字”……“114是第114个数字”?
-
它似乎运行良好 - 它确实输出了预期的格式化数字。那么你的问题是什么?
-
这不是 for 循环的问题;这是循环内部逻辑的问题。请阅读how to debug small programs 并尝试诊断逻辑错误的地方。特别是,检查哪些数字给出了错误的结果,并尝试使用这些值跟踪您的逻辑。
-
所以基本上你是在尝试打印给定范围内的基数,并且正在寻找一种更短的方法来做到这一点?
-
嗯,那是因为条件
111 == 11不是True:) 你可能需要找到一种方法来测试一个数字是否以异常结尾,而不仅仅是等于它
标签: python python-3.x loops for-loop ordinal