2015-12-21 34 views
-2

當我運行該程序並鍵入性別作爲其他任何事情,但不是男性或女性時,該程序無法按預期方式工作。我掙扎了一天,無法弄清楚。我怎樣才能把它的功能調用後,仍然使程序運行?我讀了一個主函數,但無法弄清楚如何用它修改代碼。python中的最後一個else子句不起作用

from sys import exit 
birthdays = {'Alice': 'April 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'} 

def dateOfBirth(): 
    bday = raw_input("> ") 
    birthdays[name] = bday 
    print "Database records updated." 
    print "The number of records is now " + str(len(birthdays)) + "." 
    print birthday`enter code here`s 
    exit(0) 

while True: 
    print "Enter a name: (blank to quit)" 
    name = raw_input("> ") 

    if name == '': 
     exit(0) 

    if name in birthdays: 
     print birthdays[name] + " is the birthday of " + name + "." 
     exit(0) 

    else: 
     print "I do not have the birthday information for " + name + "." 
     print " What is the sex?" 
     gender = raw_input("> ") 
     if gender == 'male': 
      print "What is his birthday?" 
      dateOfBirth() 
     elif gender == 'female' or 'Female': 
      print "What is her birthday?" 
      dateOfBirth() 
     else: 
      print " The gender is not recognised. Anyway we will continue." 
      dateOfBirth() 
+0

「不按預期工作」,怎麼樣? – Tgsmith61591

+1

看來你必須堅持在這裏==>而真:name = raw_input(「>」)。當 – obayhan

+0

可以使用'return'而不是'exit(0)'時,沒有辦法離開。 – Lafexlos

回答

5

更改此:

elif gender == 'female' or 'Female': 

這樣:

elif gender in ('female', 'Female'): 

或者我建議:

elif gender.lower()=='female': 

你有什麼跟

elif gender == 'female' or 'Female': 

本質上是否則如果性別是女性,或者如果字符串「女」不是空的。無論gender的值如何,情況總是如此。

+0

謝謝,問題的第二部分呢。 – user7479

+0

請參閱[此問題](http://stackoverflow.com/questions/22492162/understanding-the-main-method-of-python)瞭解如何使用'main'函數。 – khelwood