Python不会调用简单的测试函数。但是它可以编译。这是怎么回事?

时间:2018-11-08 02:20:01

标签: python function

我正在Lynda.com上学习一些课程,以介绍一些python基础知识。我还是一个整体编程的新手,但是以前用C做过一些项目。

我们花了5分钟的时间解释了如何调用函数。现在我们讨论条件句。没问题吧?

此简单功能将不会打印。但是编译就可以了。为什么?

def func1():
    x, y = 100, 100

    if (x < y):
        st = "x is less than y"

    elif (x == y):
        st = "x is equal to y"

    else:
        st = "x is greater than y"

    print (st)
    # I have also tried changing this to print(funct1(st)) but still doesn't work. 

在我们上一部“功能”下的视频中,他的例子是:

def func1():
  print ("I am a function")

func1()
print (func1())
print (func1)

这很好用。这3种打印示例以及调用该函数的方式。

如果我取出该函数并保留if逻辑语句和内容,则将其打印出来。所以我不明白这是怎么回事。让我觉得自己是个白痴。

这是使用pycharm IDE和python 3.7,也尝试直接从CMD控制台运行。编译并运行,但不打印任何内容。

2 个答案:

答案 0 :(得分:2)

您已经定义了函数,但没有调用它。

def func1():
    x, y = 100, 100

    if (x < y):
        st = "x is less than y"

    elif (x == y):
        st = "x is equal to y"

    else:
        st = "x is greater than y"

    print (st)

# Call the function after having defined it
func1()

定义一个功能只是准备将来使用。您必须实际调用该函数才能运行该函数的代码。

答案 1 :(得分:0)

函数的重点是重用代码,因此您无需将x和y变量初始化为值,而是可以将其作为参数传递给函数。

def func1(x, y):
    if (x < y):
        st = "x is less than y"

    elif (x == y):
        st = "x is equal to y"

    else:
        st = "x is greater than y"

    print (st)

# Call the function after having defined it
func1(100, 100) # Outputs: x is equal to y
# You can use the same code to compare even more values
func1(12, 35) # Outputs: x is less than y