2012-04-28 193 views
3

要通過學習Python堅硬方式,教訓25.在終端中運行python腳本,沒有打印或顯示 - 爲什麼?

我嘗試執行腳本,其結果是,像這樣:在終端

myComp:lphw becca$ python l25 

myComp:lphw becca$ 

不打印或顯示。

這是代碼。

def breaks_words(stuff): 
    """This function will break up words for us.""" 
    words = stuff.split(' ') 
    return words 

def sort_words(words): 
    """Sorts the words.""" 
    return sorted(words) 

def print_first_word(words): 
    """Prints the first word after popping it off.""" 
    word = words.pop(0) 
    print word 

def print_last_word(words): 
    """Prints the last word after popping it off.""" 
    word = words.pop(-1) 
    print word 

def sort_sentence(sentence): 
"""Takes in a full sentence and returns the sorted words.""" 
    words = break_words(sentence) 
    return sort_words(words) 

def print_first_and_last(sentence): 
    """Prints the first and last words of the sentence.""" 
    words = break_words(sentence) 
    print_first_word(words) 
    print_last_word(words) 

def print_first_and_last_sorted(sentence): 
    """Sorts the words then prints the first and last one.""" 
    words = sort_sentence(sentence) 
    print_first_word(words) 
    print_last_word(words) 

請幫忙!

+0

什麼是代碼假設o正在打印? – weronika 2012-04-28 21:42:24

回答

11

你所有的代碼都是函數定義,但是你永遠不會調用的任何函數,所以代碼不會做任何事情。

僅使用def關鍵字定義函數,那麼定義了函數。它不運行它。

例如,假設你只有這個功能在你的程序:

def f(x): 
    print x 

你告訴程序,每當你叫f,你想讓它打印的說法。但你實際上並沒有告訴你,你要想要撥打電話f,只是當你打電話時該怎麼辦。

如果你想打電話一些參數的函數,你需要做的是,像這樣:

# defining the function f - won't print anything, since it's just a function definition 
def f(x): 
    print x 
# and now calling the function on the argument "Hello!" - this should print "Hello!" 
f("Hello!") 

所以,如果你希望你的程序打印的東西,你需要把一些調用的你定義的功能。什麼調用和什麼參數取決於你想要的代碼做什麼!

+0

Gah。咄。我感到困惑,因爲他說,「首先,用python ex25.py像普通程序一樣運行,以發現你所犯的任何錯誤。」我想這意味着它應該顯示/某事/。 – user1186742 2012-04-28 21:49:58

+0

@ user1186742如果你有語法錯誤等,然後運行代碼會發現他們 - 這可能是什麼意思。 – weronika 2012-04-28 21:51:07

+0

非常感謝。 – user1186742 2012-04-28 21:52:34

0

可以在Interative的模式

python -i l25 

執行該文件,然後在Python提示符調用您的函數

words = ["Hello", "World"] 
print_first_word(words) 

請了更好的用戶交互操作ipython

0

是正確的答案,因爲的方法沒有任何呼叫使用

相關問題