2016-08-05 168 views
0

我的Python代码有问题。我正在尝试显示用户输入的序号。所以如果我输入32就会显示第32位,或者如果我输入576则显示576。唯一不起作用的是93,它显示93。其他数字的作品,我不知道为什么。这里是我的代码:序号错误,Python 3

num = input ('Enter a number: ') 
end = '' 
if num[len(num) - 2] != '1' or len(num) == 1: 
    if num.endswith('1'): 
    end = 'st' 
    elif num.endswith('2'): 
    end = 'nd' 
    elif num == '3': 
    end = 'rd' 
    else: 
    end = 'th' 
else: 
    end = 'th' 
ornum = num + end 
print (ornum) 

回答

1

您在2个​​地方使用endswith(),而不是3:

if num.endswith('1'): 
    end = 'st' 
elif num.endswith('2'): 
    end = 'nd' 
#elif num == '3': WRONG 
elif num.endswith('3'): 
    end = 'rd' 

在你的代码中,它会测试'如果num等于3'而不是'如果num以3结尾'。

1

出于某种原因,你忘了检查endswith()当谈到3

elif num.endswith('3'): 
    end = 'rd' 

在一个侧面说明,你可以提高你的代码通过SE代码审查阅读this question ,其中包括这真棒版本:

SUFFIXES = {1: 'st', 2: 'nd', 3: 'rd'} 
def ordinal(num): 
    if 10 <= num % 100 <= 20: 
     suffix = 'th' 
    else: 
     suffix = SUFFIXES.get(num % 10, 'th') 
    return str(num) + suffix