Megan Vezina
Megan Vezina

Reputation: 21

How do I fix this if else statement in python?

The question is to have each number display once with the appropriate term (1 through 9, going 1st, 2nd, 3rd, etc.) each displaying on seperate lines. When I run this code:

ordinal_numbers = ('1','2','3','4','5','6','7','8','9')
for ordinal_number in ordinal_numbers:
    if '1' in ordinal_number:
        print('1st')
    if '2' in ordinal_number:
        print('2nd')
    if '3' in ordinal_number:
        print('3rd')
    else:
        print(ordinal_number + 'th')

I get each code on its own line, but for 1 and 2, it also displays 1th and 2th, along with 1st and 2nd. For the number 3, it only displays 3rd. How do I fix this?

Upvotes: 1

Views: 37

Answers (2)

Frank
Frank

Reputation: 2029

Your original code is multiple different if statements, and so the else clause always executes for the '1' and '2' cases. You should use 'elif' ("else if") to ensure only one of the cases ever executes.

ordinal_numbers = ('1','2','3','4','5','6','7','8','9')
for ordinal_number in ordinal_numbers:
    if '1' in ordinal_number:
        print('1st')  # 1
    elif '2' in ordinal_number:
        print('2nd')  # 2
    elif '3' in ordinal_number:
        print('3rd')  # 3
    else:
        print(ordinal_number + 'th')  # 4,5,6,7,8,9

In your example ordinal_number can match two expressions:

ordinal_numbers = ('1','2','3','4','5','6','7','8','9')
for ordinal_number in ordinal_numbers:
    if '1' in ordinal_number:
        print('1st')  # 1
    if '2' in ordinal_number:
        print('2nd')  # 2
    if '3' in ordinal_number:
        print('3rd')  # 3
    else:
        print(ordinal_number + 'th')  # 1,2,4,5,6,7,8,9

Do you see the difference? Please ask if something is unclear.

This little example would be a little more pythonic:

def get_suffix(number):
    """Returns the suffix from the dictionary or 'th'
    Works for numbers from 1 to 20
    """
    return {1: 'st', 2: 'nd', 3: 'rd'}.get(int(number), 'th')

def get_suffix2(number):
    """same as above but works with all numbers"""
    return {1: 'st', 2: 'nd', 3: 'rd'}.get(
        int(number) % 10 * (int(number) % 100 not in [11, 12, 13]), "th"
        )

for ordinal_number in ordinal_numbers:
    print(ordinal_number + get_suffix(ordinal_number))

Upvotes: 1

rdas
rdas

Reputation: 21275

Here's a more succinct solution:

ordinal_numbers = ('1', '2', '3', '4', '5', '6', '7', '8', '9')
postfixes = ['st', 'nd', 'rd'] + ['th'] * (len(ordinal_numbers) - 3)

for num, ppostfix in zip(ordinal_numbers, postfixes):
    print(num + ppostfix)

Output:

1st
2nd
3rd
4th
5th
6th
7th
8th
9th

Upvotes: 0

Related Questions