求助:整数转序数词字符串代码异常,所有输出均带th后缀
Fixing Your Ordinal Number Converter Code
Hey there! Let's figure out why your code is only outputting "xxth" every time—great job on writing your first ordinal number converter, by the way! 😊
The Core Issues
Your logic is totally on the right track, but two small bugs are throwing everything off:
- You're comparing string characters to integers: After converting
numberto a string, you check conditions likenumber[-2] == 1. Butnumber[-2]is a string character (e.g.,"1"for the number 12), and you're comparing it to the integer1. These types don't match, so none of your early conditions ever trigger—everything falls through to the finalelseclause. - No safety for single-digit numbers: If someone inputs a single-digit number (like 5),
number[-2]will try to access a character that doesn't exist, which would cause an error.
Fixed Code with Explanations
Here's the corrected version, with comments to walk you through each change:
# Get input and convert to integer first number = int(input('Input a number: ')) # Convert to string for easy digit checking (renamed for clarity) num_str = str(number) # First handle numbers where tens digit is 1 (11-19, 111-119, etc.) # Add a check to make sure the number has at least two digits first if len(num_str) >= 2 and num_str[-2] == '1': ordinal_number = num_str + 'th' # Now handle single-digit numbers or numbers with non-1 tens digit elif num_str[-1] == '1': ordinal_number = num_str + 'st' elif num_str[-1] == '2': ordinal_number = num_str + 'nd' elif num_str[-1] == '3': ordinal_number = num_str + 'rd' else: ordinal_number = num_str + 'th' print(ordinal_number)
Key Fixes Breakdown
- String-to-string comparisons: We now compare string characters to string literals (like
'1'instead of1), so your conditions will trigger exactly when you want them to. - Single-digit safety: The
len(num_str) >= 2check ensures we only look at the tens digit if the number has two or more digits—no more errors for inputs like 3 or 7. - Clearer variable names: Renamed
ordinalnumbertoordinal_numberand split the number intonumber(integer) andnum_str(string) to make the code easier to follow as you learn.
Test Cases to Verify
- Input
31→31st(correct, since tens digit is 3, not 1) - Input
12→12th(correct, tens digit is 1) - Input
5→5th(correct) - Input
2→2nd(correct)
内容的提问来源于stack exchange,提问作者FearlessDoggo21
相关产品推荐
相关产品推荐

