加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python逻辑 – 如果是elif语句,则简化/更有效

发布时间:2020-12-20 12:37:53 所属栏目:Python 来源:网络整理
导读:I’m taking an Intro to Python course online并希望更有效地解决这个问题. 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 ou
I’m taking an Intro to Python course online并希望更有效地解决这个问题.

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")

我无法弄清楚如何在四行中更有效地写这个.它涉及清单吗?他们还没有教过列表或数组.

解决方法

x = int(input())
if x == 1:
   print("1st")
elif x == 2:
   print("2nd")
elif x == 3:
   print("3rd")
else:
   print(str(x)+"th")

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读