2014-03-06 115 views
-4

我是編寫代碼的新手,我正在通過「瞭解Python的難題」。我想定義PersonName和Hoarder,以便得到以下結果:在Python中定義多個函數

Fred有45只貓。
比爾有20只狗。
這是很多動物。
尋找治療師!

def PersonName(name1, name2): 
def Hoarder(number_of_cats, number_of_dogs): 
    print "%r had %d cats." % (name1, number_of_cats) 
    print "%r had %d dogs." % (name2, number_of_dogs) 
    print "That is a lot of animals." 
    print "Find a therapist!" 

print 
Person("Fred", "Bill") 
Hoarder(45,20) 
+1

問題是什麼? – juankysmith

+0

那麼,這有什麼問題? –

+0

如果沒有某種全局變量,這將不起作用,這不是一個好主意。你能否給我們一個練習的鏈接? – Matthias

回答

0
def PersonName(name1, name2): 
    def Hoarder(number_of_cats, number_of_dogs): 
     print "%r had %d cats." % (name1, number_of_cats) 
     print "%r had %d dogs." % (name2, number_of_dogs) 
     print "That is a lot of animals." 
     print "Find a therapist!" 
    Hoarder(45,20) 

PersonName("Fred", "Bill") 

'Fred' had 45 cats. 
'Bill' had 20 dogs. 
That is a lot of animals. 
Find a therapist! 

如果你真的想定義兩個函數,你需要把它們寫如上。另請注意功能範圍。

+0

@Ashoka Lella,將PersonName更改爲包含名稱和貓/狗數是最簡單的解決方案。 – PaulWritesCode

+0

你的作品也是如此,儘管我不確定它爲什麼沒有在收集者或PersonName之前說'打印'。 – PaulWritesCode