在终端中运行 python 脚本,没有打印或显示 - 为什么? [英] Running python script in terminal, nothing prints or shows up - why?

查看:140
本文介绍了在终端中运行 python 脚本,没有打印或显示 - 为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习 Python the Hard Way,第 25 课.

Going through Learn Python the Hard Way, lesson 25.

我尝试执行脚本,结果是这样的:

I try to execute the script, and the result is like so:

myComp:lphw becca$ python l25 

myComp:lphw becca$ 

终端中没有任何打印或显示.

Nothing prints or displays in terminal.

这是代码.

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)

请帮忙!

推荐答案

你所有的代码都是函数定义,但你从不调用任何函数,所以代码什么也不做.

All your code is function definitions, but you never call any of the functions, so the code doesn't do anything.

def 关键字定义一个函数,好吧,定义一个函数.它不运行它.

Defining a function with the def keyword just, well, defines a function. It doesn't run it.

例如,假设您的程序中只有这个函数:

For example, say you just have this function in your program:

def f(x):
    print x

您是在告诉程序,每当您调用 f 时,您都希望它打印参数.但是您实际上并不是在告诉它您想要调用 f,而是在调用它时要做什么.

You're telling the program that whenever you call f, you want it to print the argument. But you're not actually telling it that you want to call f, just what to do when you do call it.

如果你想在某个参数上调用函数,你需要这样做,就像这样:

If you want to call the function on some argument, you need to do so, like this:

# 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!")

所以如果你想让你的程序打印一些东西,你需要对你定义的函数进行一些调用.调用什么以及使用什么参数取决于您希望代码做什么!

So if you want your program to print something, you need to put in some calls to the functions you defined. What calls and with what arguments depends on what you want the code to do!

这篇关于在终端中运行 python 脚本,没有打印或显示 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆