2011-03-15 35 views
0

我真的很新的這一切,現在我試圖讓兩個功能進行打印,但我似乎無法掌握它:如何讓兩個函數在Python中同時工作?

import datetime 

def get_date(prompt): 
    while True: 
     user_input = raw_input(prompt) 
     try: 

      user_date = datetime.datetime.strptime(user_input, "%m-%d") 
      break 
     except Exception as e: 
      print "There was an error:", e 
      print "Please enter a date" 
    return user_date.date() 

def checkNight(date): 
    date = datetime.strptime('2011-'+date, '%Y-%m-%d').strftime('$A') 

birthday = get_date("Please enter your birthday (MM-DD): ") 
another_date = get_date("Please enter another date (MM-DD): ") 

if birthday > another_date: 
    print "Your friend's birthday comes first!" 
    print checkNight(date) 

elif birthday < another_date: 
    print "Your birthday comes first!" 
    print checkNight(date) 

else: 
    print "You and your friend can celebrate together." 

get_date需要能夠功能檢查日期是否有5個字符,並允許分割爲任何東西。此外,如果有人輸入「02-29」,則會將其視爲「02-28」。 checkNight需要能夠檢查早前生日的晚上。

下面是一些例子:

 
Please enter your birthday (MM-DD): 11-25 
Please enter a friend's birthday (MM-DD): 03-05 
Your friend's birthday comes first! 
Great! The party is on Saturday, a weekend night. 

Please enter your birthday (MM-DD): 03-02 
Please enter a friend's birthday (MM-DD): 03-02 
You and your friend can celebrate together! 
Too bad! The party is on Wednesday, a school night. 

Please enter your birthday (MM-DD): 11-25 
Please enter a friend's birthday (MM-DD): 12-01 
Your birthday comes first! 
Great! The party is on Friday, a weekend night. 
+0

寫下你想做的事,但不能在代碼中表達。沒有這個,這不是一個問題,而是一個任務描述。 – 2011-03-15 17:57:52

+0

我會推薦一個python教程讓你開始http://wiki.python.org/moin/BeginnersGuide/Programmers – MattiaG 2011-03-15 18:15:31

回答

2
  • 一個錯誤是由於主叫checkNight(date),而不必被定義變量「日期」。
  • datetime.strptime應該爲datetime.datetime.strptime
  • 同一行('2011-'+date)中的字符串和日期的連接也可能導致錯誤。
  • checkNight(date)功能不返回任何東西
  • 等等

也許這是一個有點接近你想要什麼:

import datetime 

def get_date(prompt): 
    while True: 
     user_input = raw_input(prompt) 
     try: 
      user_date = datetime.datetime.strptime(user_input, "%m-%d") 
      user_date = user_date.replace(year=2011) 
      break 
     except Exception as e: 
      print "There was an error:", e 
      print "Please enter a date" 
    return user_date 

def checkNight(date): 
    return date.strftime('%A') 

birthday = get_date("Please enter your birthday (MM-DD): ") 
another_date = get_date("Please enter another date (MM-DD): ") 

if birthday > another_date: 
    print "Your friend's birthday comes first!" 
    print checkNight(another_date) 

elif birthday < another_date: 
    print "Your birthday comes first!" 
    print checkNight(birthday) 

else: 
    print "You and your friend can celebrate together." 

注意,因爲我改變權後的一年2011年用戶輸入它,我可以更簡單地在checkNight()中提取一週中的哪一天。

相關問題