努力学习python的方法ex24函数不工作,没有错误消息

2024-04-25 03:59:21 发布

您现在位置:Python中文网/ 问答频道 /正文

此程序的函数部分(在def之后的所有内容)不起作用。我没有错误信息,而且我相信我已经像Zed那样把所有的东西都打出来了。怎么了?你知道吗

print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tell'
# newline and a space are put in, tab and a space are put in

# this doesn't print the poem, only stores it
poem = """
\tThe lovely world 
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\t where there is none
"""

print "--------------"
print poem
print "--------------"

five = 10 - 2 + 3 -6
print "This should be five: %s" % five

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates
    # these are local variables, they are inside the function

    start_point = 10000
    # whatever happened to started now happens to start point
    # these are global variables, they are outside the function, could be called x, y, and z
    beans, jars, crates = secret_formula(start_point)

    print "With a starting point of: %d" % start_point
    print "We'd have %d beans, %d jars, and %d crates." (beans, jars, crates)

    # reassigns with new value based on old value
    start_point = start_point / 10

    print "We can also do that this way:"
    # brings down the info from line 29
    print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)

Tags: andthetosecretwithstartarepoint
1条回答
网友
1楼 · 发布于 2024-04-25 03:59:21

你的代码从不调用函数。这是因为你把应该称之为的代码缩进得太深了。你知道吗

您的功能只能定义为:

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates
    # these are local variables, they are inside the function

这些行之后的所有内容都应不应缩进:

start_point = 10000
# whatever happened to started now happens to start point
# these are global variables, they are outside the function, could be called x, y, and z
beans, jars, crates = secret_formula(start_point)

print "With a starting point of: %d" % start_point
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)

# reassigns with new value based on old value
start_point = start_point / 10

print "We can also do that this way:"
# brings down the info from line 29
print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)

注意,这些代码都应该从行首开始,行首和每行上的指令之间没有空格。你知道吗

我还纠正了其中一行的一个拼写错误。您键入了:

print "We'd have %d beans, %d jars, and %d crates." (beans, jars, crates)

这将尝试调用字符串((...)直接位于"..."字符串文本之后)。该行缺少%运算符;请将该运算符也放进去,以使格式化操作正常工作:

print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)

相关问题 更多 >