【问题标题】:Running python script in terminal, nothing prints or shows up - why?在终端中运行 python 脚本,没有打印或显示 - 为什么?
【发布时间】:2012-04-28 21:37:56
【问题描述】:

通过艰难的方式学习 Python,第 25 课。

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

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)

请帮忙!

【问题讨论】:

  • 应该打印什么代码?

标签: python terminal


【解决方案1】:

您的所有代码都是函数定义,但您从不调用任何函数,因此代码不会做任何事情。

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

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

【讨论】:

  • 嘎。呃。我很困惑,因为他说:“首先,像平常一样使用 python ex25.py 运行它,以找出你犯的任何错误。”我认为这意味着它应该显示 /something/。
  • @user1186742 如果你有语法错误等,那么运行代码会找到它们——这可能就是这个意思。
【解决方案2】:

您可以在交互模式下执行该文件

python -i l25

然后在 python 提示符下调用你的函数

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

请安装ipython 以获得更好的用户交互

【讨论】:

    猜你喜欢
    • 2017-06-13
    • 2020-12-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多