3

I'm taking an Intro to Python course online and would like to solve this problem more efficiently.

The words 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th are called ordinal adjectives. Write a program which reads an integer x between 1 and 9 from input. The program should output the ordinal adjective corresponding to x. Hint: you don't need to have 9 separate cases; 4 is enough.

x = int(input())
if x == 1:
   print("1st")
elif x == 2:
   print("2nd")
elif x == 3:
   print("3rd")
elif x == 4:
   print("4th")
elif x == 5:
   print("5th")
elif x == 6:
   print("6th")
elif x == 7:
   print("7th")
elif x == 8:
   print("8th")
elif x == 9:
   print("9th")

I can't figure out how to write this more efficiently in four lines. Does it involve lists? They have not taught lists or arrays yet.

StacyM
  • 1,036
  • 5
  • 23
  • 41

5 Answers5

8
x = int(input())
if x == 1:
   print("1st")
elif x == 2:
   print("2nd")
elif x == 3:
   print("3rd")
else:
   print(str(x)+"th")
freakish
  • 54,167
  • 9
  • 132
  • 169
8

Just use string formatting. And account for different suffixes between 1, 2, 3, and the rest of the numbers

x = int(raw_input())
if x == 1:
    suffix = "st"
elif x == 2:
    suffix = "nd"
elif x == 3:
    suffix = "rd"
else:
    suffix = "th"
print "{number}{suffix}".format(number=x,suffix=suffix)

You could actually do it in a more pythonic manner with a mapping instead of an if/else block

x = int(raw_input())
suffix = {1: "st", 2: "nd", 3: "rd"}.get(x, "th")
print "{number}{suffix}".format(number=x, suffix=suffix)
Greg
  • 5,422
  • 1
  • 27
  • 32
2

Why convert to int?

x = input()
if x == "1":
    print("1st")
elif x == "2":
    print("2nd")
elif x == "3":
    print("3rd")
else:
    print(x+"th")
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
1

I needed my function to go above 9, but none of the answers were exactly what I needed. I came up with this and thought I'd share. I know it's not the most elegant solution, but it worked for what I needed it to do.

def ordinal_adjective(n):
    if ('%s' % (n,))[-2:] in ['11','12','13']:
        return '%sth' % n
    elif ('%s' % (n,))[-1] == '1':
        return '%sst' % n
    elif ('%s' % (n,))[-1] == '2':
        return '%snd' % n
    elif ('%s' % (n,))[-1] == '3':
        return '%srd' % n
    else:
        return '%sth' % n

x = input()
print ordinal_adjective(x)
Matt
  • 891
  • 1
  • 8
  • 14
-1

you can't do switch case statement in python, but you can use these examples to do it in a different way, not necessary better:

Community
  • 1
  • 1
No Idea For Name
  • 11,411
  • 10
  • 42
  • 70