减少小python脚本中的条件数量

时间:2016-11-16 16:08:43

标签: python

我一直在开发一个小程序。 它的工作原理完全如此,但我想让代码变得更小。

import time, math 
name= input("Enter Your Name: ")
age= int(input("Enter Your Age: "))
end= "th"
if age == 3 or age == 13 or age == 23 or age == 33 or age == 43 or age == 53 or age == 63 or age == 73 or age == 83 or age == 93:
 end= "rd"

if age == 2 or age == 22 or age == 32 or age == 42 or age == 52 or age == 62     or age == 72 or age == 82 or age == 92:
 end= "nd"

print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(5)

我想有一个更简单的方法来改变结局'对于其他值而不必全部写出来,我可以从3开始,然后为超过3的所有内容进行操作。

6 个答案:

答案 0 :(得分:3)

使用modulo operator

if age % 10 == 3:
    end = "rd"
elif age % 10 == 2:
    end = "nd"

或使用词典:

ends = {2: "nd", 3: "rd"}
end = ends[age % 10]

您还可以使用默认值:

ends = {1: "st", 2: "nd", 3: "rd"}
end = ends.get(age % 10, "th)

答案 1 :(得分:2)

在第十位提取数字。然后它很简单。虽然这个问题属于SO的codereview对应物。

import time, math
name= input("Enter Your Name: ")
age= int(input("Enter Your Age: "))

tenth_place = age % 10
if tenth_place == 3:
    end = "rd"
elif tenth_place == 2:
    end = "nd"
else:
    end = "th"

print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(5)

答案 2 :(得分:0)

if age in range(3,93,10) :
    end = "rd"

答案 3 :(得分:0)

你可以试试这个:

if int(age[-1]) == 3:
   end= "rd"

if int(age[-1]) == 2:
   end= "nd"

答案 4 :(得分:0)

可能不一定短,但它有效(并保持第12和第13适当)。

import time, math 

name = input("Enter Your Name:")
age = int(input("Enter Your Age:"))
end = "th"

# initializing age lists
list1 = []
list2 = []  

# filling list1 with ages 3-93 
for i in range(0,10):
    list1.append(10*i+3)

# filling list2 with ages 2-92
 for i in range(0,10):
    list2.append(10*i+2)

# if block to include correct suffix
for ages in list1:
    if ages == 13:
        end = end;
    elif ages == age:
        end = "rd"

for ages in list2:
    if ages == 12:
        end = end
    elif ages == age:
        end = "nd"

print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(5)

答案 5 :(得分:0)

感谢所有人,

我还发现了另一个缺陷并修复了它,这是我目前的代码。 感谢。

import time, math 
name= input("Enter Your Name: ")
age= int(input("Enter Your Age: "))
end= "th"



if age % 10 == 3:
     end = "rd"

elif age % 10 == 2:
     end = "nd"

elif age % 10 == 1:
     end = "st"

if age < 20 and age > 10:
 end = "th"



print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(2)

谢谢, 比尔博