2016-11-16 39 views
-2

我一直在開發一個小程序。 它完美地工作,但我想使代碼更小一點。減少小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那麼做的一切10三多。

+0

請寫出更好地描述您的問題 – Chr

+0

你應該看看在工地附近看到如何寫一個描述性標題標題 - 您目前還不是特別清楚。另外,看看Python中的模運算符(提示:你可以用'age%10 == 3'替換你的第一個檢查)。 – Aurora0001

+1

這已經在這裏回答:http://stackoverflow.com/questions/739241/date-ordinal-output – denvaar

回答

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) 
+0

謝謝大家對於Answering, – Bilbo

+0

它工作完美 – Bilbo

+0

@Bilbo你應該考慮接受這個答案,在這種情況下 –

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

你可以試試這個:

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

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

謝謝你的想法, – Bilbo

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

感謝, 比爾博