Python中的语句和函数有什么区别?

时间:2017-04-16 09:39:29

标签: python python-2.7 python-3.x function statements

编辑:建议的副本,不回答我的问题,因为我主要关注Python的差异。建议的副本比这个问题要广泛得多。

我最近开始学习Python。我正在阅读“以艰难的方式学习Python”。我有一些特殊的编程经验,但是我回到开始时就从头开始学习所有内容。

在本书中,首批课程之一涉及print,作者在Python 2.7中提供了各种使用说明,例如:

print "This is fun."

我发现自己想知道从编程的角度来看,print在技术上是什么。 Some research found this, PEP-3105

在哪种情况下使print成为一个函数:

  

印刷声明早已出现在可疑语言清单上   要在Python 3000中删除的功能,例如Guido的   “Python遗憾”演示文稿1。因此,这个PEP的目标   虽然它可能在Python中引起很大争议但并不新鲜   开发者。

所以print是Python 2.7中的一个语句,也是Python 3中的一个函数。

但我无法找到statementfunction之间差异的直接定义。我发现了this也是发明Python的人, Guido van Rossum ,他在其中解释了为什么将print作为函数而不是声明是好的。

从我所看到的内容看来,函数是一些带参数并返回值的代码。但是不是print在python 2.7中这样做吗?是不是接受字符串并返回串联字符串?

Python中的语句和函数有什么区别?

3 个答案:

答案 0 :(得分:3)

语句是一种语法结构。函数是一个对象。有创建函数的语句,如def

def Spam(): pass

因此,语句是向Python指示您希望它创建函数的方法之一。除此之外,他们之间的关系并不多。

答案 1 :(得分:0)

Python中的语句是您编写的任何代码块。它更是一个理论概念,而不是真实的事物。如果在编写代码时使用正确的语法,则语句将被执行(“求值”)。如果使用不正确的语法,则代码将引发错误。大多数人交替使用“陈述”和“表达”。

查看语句和函数之间差异的最简单方法可能是查看一些示例语句:

5 + 3 # This statement adds two numbers and returns the result
"hello " + "world" # This statement adds to strings and returns the result
my_var # This statement returns the value of a variable named my_var
first_name = "Kevin" # This statement assigns a value to a variable.
num_found += 1 # This statement increases the value of a variable called num_found
print("hello") # This is a statement that calls the print function
class User(BaseClass): # This statement begins a class definition
for player in players: # This statement begins a for-loop
def get_most_recent(language): # This statement begins a function definition
return total_count # This statement says that a function should return a value
import os # A statement that tells Python to look for and load a module named 'os'

# This statement calls a function but all arguments must also be valid expressions.
# In this case, one argument is a function that gets evaluated
mix_two_colors(get_my_favorite_color(), '#000000')

# The following statement spans multiple lines and creates a dictionary
my_profile = {
  'username': 'coolguy123' 
}

以下是无效语句的示例:

first+last = 'Billy Billson'
# Throws a Syntax error. Because the plus sign is not allowed to be part of a variable name.

在Python中,除了嵌套语句,您倾向于将每个语句放在自己的行上。但是在其他编程语言(如C和Java)中,只要它们之间用冒号(;)隔开,就可以根据需要在任意一行上放置任意数量的语句。

在Python2和Python3中,您都可以调用

print("this is a message") 

,它将打印标准字符串。这是因为它们都有一个定义为print的函数,该函数接受一个字符串参数并将其打印出来。

Python2还允许您在不调用函数的情况下声明要打印到标准输出。该语句的语法是,它以单词print开头,之后出现的就是打印出来的内容。在Python3中,这不再是有效的语句。

print "this is a message"

答案 2 :(得分:-1)

语句是python可以理解的一切。函数就是其中之一,他具有与其他语句不同的功能。函数是一个语句,但是有很多不是函数的语句。

if语句不是函数之一。 for和while也是很好的例子。所有这些都是“复合语句”组的一部分。

在Python中,函数必须返回一个值。即使您不使用return语句,该函数也将返回None。有些语句不返回任何值,例如if,for,while等。 如何检查语句是否为函数?您可以使用类型函数,该函数将为函数返回类“函数”。您可以尝试询问if的类型,但会收到SyntaxError。

在python 2中,print语句是简单语句的一部分,例如import,global,break等。但是在PEP 3105之后,新的打印功能取代了打印简单语句。在PEP 3105中,您可以了解社区决定更改python语句的原因,这可以更清楚地说明为什么某些语句不是函数。