2013-03-17 25 views
1

好吧,所以我正在爲我們的女朋友製作我們的6週年代碼。 我是一個完整的編程noob。我正在編寫一些非常簡單的代碼,基本上是一個輸入數字輸入機器,以便用戶(她)接收字符串輸出。Python:函數定義在所需輸出的中間不斷返回'None'

我一直看到「無」,當我運行我的代碼。爲什麼? 在這裏。

def love(n): 
    if n < 0 : 
    print "Why would it be negative?!" 
    if n == 0 : 
     print "well that is just hurtful" 
    if n == 1 : 
    print "I REALLY love you" 
    if n == 2 : 
    print "You make me smile at least once, each and every day" 
    if n == 3 : 
    print"you wouldn't believe how annoying it was to get this program to run properly! but it was worth it" 
    if n == 4 : 
     print "let's " + "shoot a little higher than that" 
    else: 
    print "I honestly can't see myself without you anymore" 


print love(0) 

print "Wanna try again? :D " 
+0

我不知道爲什麼它的格式非常糟糕...... – davidawad 2013-03-17 03:02:33

+0

創建帖子時,可以選擇突出顯示代碼塊並單擊「代碼塊」選項將其格式化爲代碼。 – Snukus 2013-03-17 03:04:30

+0

你可以做Snukus所說的,點擊_code_按鈕,或者你可以將所有代碼縮進4個空格 - 這正是我編輯帖子時所做的。 – DaoWen 2013-03-17 03:05:31

回答

1

你的函數具有None默認的返回值,所以當你print出來,將打印None

只需調用沒有print語句的函數即可。

或者,您可以將函數中的所有print語句替換爲return,並將其變爲if-elif-else塊,因爲它們都是互斥的操作。然後,打印love(0)實際上會打印出返回值。

+0

Sheesh,談論挑剔。 :P – Makoto 2013-03-17 03:08:48

7
love(0) # is all you need. 

你不需要調用print love(),因爲你已經擁有內love打印報表。 你正在看到Nonelove正在做所有的工作,它沒有返回任何東西。


另外,你需要爲你只想要一個,出所有的打印操作的,在同一時間運行,以使用if-elif-else塊的功能。

if n < 0 : 
    print "Why would it be negative?!" 
elif n == 0 : 
     print "well that is just hurtful" 
elif n == 1 : 
    print "I REALLY love you" 
elif n == 2 : 
    print "You make me smile at least once, each and every day" 
elif n == 3 : 
    print"you wouldn't believe how annoying it was to get this program to run properly! but it was worth it" 
elif n == 4 : 
     print "let's " + "shoot a little higher than that" 
else: 
    print "I honestly can't see myself without you anymore" 

雖然,超越2,打印一切不會傷害;)

我100 答案就這樣!好極了 !

+0

好完美!謝謝。我的另一個問題是爲什麼總是打印else語句,即使對於前者。 n == 4是真的嗎? – davidawad 2013-03-17 03:11:26

+0

您需要在第一個「elif」之後而不是if之後製作所有if語句。其他方面,你說的是:如果n不等於4,則打印else塊中的內容。 – Snukus 2013-03-17 03:12:01

+0

ohhhhhhkay。我不知道它是這樣工作的。謝謝! – davidawad 2013-03-17 04:22:21