2011-03-23 147 views
0

Python是簡單地造就另一個提示,當我從Zed的肖鍛鍊18爲什麼這個def函數沒有在Python中執行?

# this one is like our scripts with argv 
def print_two(*args): 
    arg1, arg2 = args 
    print "arg1: %r, arg2: %r" % (arg1, arg2) 

# ok, that *args is actually pointless, we can just do this 
def print_two_again(arg1, arg2) : 
    print "arg1: %r, arg2: %r" % (arg1, arg2) 

# this just takes one argument 
def print_one(arg1) : 
    print "arg1: %r" % arg1 

# this one takes no argument 
def print_none() : 
    print "I got nothin'." 


    print_two("Zed","Shaw") 
    print_two_again("Zed","Shaw") 
    print_one("First!") 
    print_none() 
+1

對不起,*其中*一段代碼?你在Python REPL中輸入了所有的東西嗎? – 2011-03-23 03:12:30

+0

哪段代碼? – 2011-03-23 03:12:55

+0

@senderle對此表示歉意!感謝您的支持! – 2011-04-13 03:00:13

回答

4

最後四行的縮進是錯誤輸入下面的一段代碼。由於它們縮進,python解釋器認爲它們是print_none()的一部分。取消他們的意圖,口譯員會按照預期給他們打電話。它應該看起來像這樣:

>>> print_two("Zed","Shaw") 
[... etc ...] 
+0

是的我只是想通了,我是一個塗料。非常感謝。 – 2011-03-23 03:17:03

1

def定義了一個函數。函數是潛在的......他們有一系列等待執行的步驟。 要在python中執行一個函數,它必須被定義,並且被稱爲

# this one takes no argument 
def print_none() : 
    print "I got nothin'." 

#brings up prompt..then execute it 
print_none() 
1

刪除最後一行的縮進。因爲它們是縮進的,所以它們是print_none()的一部分,而不是在全局範圍內執行。一旦他們回到全球範圍,你應該看到它們在運行。

1

您需要保持代碼對齊。您對以上方法的調用被視爲函數print_none()的一部分。

試試這個:

# this one is like our scripts with argv 
def print_two(*args): 
    arg1, arg2 = args 
    print "arg1: %r, arg2: %r" % (arg1, arg2) 

# ok, that *args is actually pointless, we can just do this 
def print_two_again(arg1, arg2) : 
    print "arg1: %r, arg2: %r" % (arg1, arg2) 

# this just takes one argument 
def print_one(arg1) : 
    print "arg1: %r" % arg1 

# this one takes no argument 
def print_none() : 
    print "I got nothin'." 


print_two("Zed","Shaw") 
print_two_again("Zed","Shaw") 
print_one("First!") 
print_none() 
相關問題