2017-03-16 89 views
-1

我試圖編寫一個代碼,如果用戶提示今天的日期和他們的出生日期,以確定他們的年齡。年齡將決定他們的門票價格是多少。它會詢問客戶是否有優惠券,這會從他們的價格中扣除一美元。我想出了這個至今:計算入場費價格

print ("Hello, welcome to Hopper's Computer Museum! To determine your enterance fee, please enter the following:") 

print("Your date of birth (mm dd yyyy)") 
Date_of_birth = input("--->") 

print("Today's date: (mm dd yyyy)") 
Todays_date = input("--->") 


from datetime import date 

def calculate_age(born): 
    Todays_date = date.today() 
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) 

if age <= 14: 
    price==5.00 
elif age > 15 and age < 64: 
    price==9.00 
elif age > 65: 
    price==7.50 

print ('Do you have a coupon (y/n)?') 
Discount = input("--->") 
if Discount == "y" or Discount == "Y": 
    price = price-1 
elif Discount == "n" or Discount == "N": 
    price = price 

print ('Your admission fee is '+str(price)) 

我一直在尋找一些類似的問題,我他們幫助解決了一些自己的問題,但我不知道要定義什麼「年齡」爲使該程序會讀取它。

因此,看到迴應後,它會看起來更像這樣嗎?

print ("Hello, welcome to Hopper's Computer Museum! To determine your enterance fee, please enter the following:") 

print("Your date of birth (mm dd yyyy)") 
Date_of_birth = input("--->") 

print("Today's date: (mm dd yyyy)") 
Todays_date = input("--->") 


from datetime import date 
def calculate_age(born): 
    today = date.today() 
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) 

age = calculate_age(Date_of_birth) 

if age <= 14: 
    price==5.00 
elif age > 15 and age < 64: 
    price==9.00 
elif age > 65: 
    price==7.50 

print ('Do you have a coupon (y/n)?') 
Discount = input("--->") 
if Discount == "y" or Discount == "Y": 
    price = price-1 
elif Discount == "n" or Discount == "N": 
    price = price 

print ('Your admission fee is '+str(price)) 
+1

你是什麼意思?「但我不知道該怎麼定義」年齡「,以便程序能夠讀取它。」? – Carcigenicate

+1

當我運行我的程序時,它提出了兩個問題,但只要它收到一個答案,它說'年齡'沒有定義 –

回答

1

你永遠定義age,或致電calculate_age。只需撥打calculate_age今天的日期:

def calculate_age(born): 
    Todays_date = date.today() 
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) 

# Here. You need to define age 
age = calculate_age(Date_of_birth) 

if age <= 14: 
    price==5.00 
elif age > 15 and age < 64: 
    price==9.00 
elif age > 65: 
    price==7.50 

不過請注意,有一些時髦的東西與你的代碼怎麼回事。您向用戶詢問今天的日期,然後用Todays_date = date.today()覆蓋他們輸入的內容,然後您永遠不會使用它。你的意思是today = date.today()?無論如何,這是除了問題。

2

你的代碼有幾個問題。你的高級邏輯很好,但你沒有完全實現。你會得到這個錯誤,因爲你永遠不會給變量年齡一個值。你的calculate_age功能將做這項工作如果你懶得給它發送正確的數據並保存答案。還要注意,你對日期的結構做了幾個假設,但是你沒有編寫任何代碼來給出結構的日期。

您有兩個基本選擇:

  1. 瞭解Python的日期時間包,並使用預先定義的過程寫在這裏;
  2. 構建您自己的數據類型。

請注意,你的程序有沒有日期包和無結構今天出生;對這些對象的屬性的引用也將不確定。您需要充分組織您的程序才能獲得所需的結果。爲此,我強烈推薦增量編程:編寫一小塊代碼,並調試它,直到它按照您期望的方式工作。 然後繼續下一個塊。當然,請將此程序作爲設計參考,但不要依賴您在此使用的名稱和流程。例如,從指定特定的出生日期和特定的「今天」日期開始,以任何形式適用於您。剔除邏輯。確保您可以計算年齡(全年),然後分配適當的門票價格。之後,回去處理日期輸入。