Python的基本语法(附示例)
Python 类似于“C 家族”的语言,但有一些显着的差异和独特的属性。
Python 与 C 和 ST 等语言之间最明显的句法差异是 Python 解析器通过缩进识别块结构。没有 BEGIN/END
或大括号 {}
识别块 IF/ELSE
条件, FOR
和 WHILE
循环或函数。
评论开头 #
并延伸到行尾。在源代码的第一行和第二行,可以设置一个特殊的标记来声明文件的编码。如果不需要 ASCII 字符,我们建议您使用 UTF-8 作为编码。
出于调试目的,您使用 print
方便输出。随着 %
运算符,您可以实现类似于 C 函数的功能 printf()
.输出显示在消息视图中 CODESYS.
print
# encoding:utf-8 # defining a function with the parameter i def do_something(i): # if branch if i>0: print("The value is: %i" % i) sum += i print("The new sum is: %i" % sum) # else if (optional, there can be none or several elif branches) elif i=0: print("The sum did not change: %i" % sum) # and the final else branch (also optional). else: handle_error() # an endless while loop while True: print("I got stuck forever!")
属于同一块的所有内容都必须缩进相同的距离。压痕的大小无关紧要。括号和大括号等元素的优先级高于缩进。因此,以下代码段是完全正确的,即使它是用“糟糕的编程风格”编写的:
# warning: bad style below. Kids, don't try this at home! if foo >= bar: print("foobar") else: print( "barfoo" )
为避免歧义,您不应在文件中混合使用制表符和空格。
提示
目前,在 Python 3 中混合制表符和空格 gilt 被视为语法错误。
官方 Python 样式指南建议使用四个空格的缩进,并包含一些好的和差的样式示例。 Python 教程提供了编码风格的总结。
Python 是“区分大小写”的,与 C 相似,与 ST 不同。关键字,例如 def
, if
, else
, 和 while
, 必须是小写的(与 ST 规则相反:关键字是大写的)。两个标识符,例如“i”和“I”,也标识了两个不同的变量。
以下关键字在 Python 中是保留的,不允许用作变量、函数等的标识符: and | as | assert | break | class | continue | def | del | elif | else | except | exec | finally | for | from | global | if | import | in | is | lambda | not | or | pass | print | raise | return | try | while | with | yield
.
Python 3 定义了另外四个关键字: False | None | True | nonlocal
.虽然前三个确实是新的,但前三个已经是 Python 2 中预定义的常量,不应用于任何其他目的。
有关更多信息,请参阅: Python 风格指南 和 Python 教程
变量和数据类型
Python 是一种功能强大的动态类型语言——所有类型信息都在运行时进行评估。变量持有对对象的引用,并且对象知道它的类型,而不是变量。当程序员试图执行一个不可能的操作时(例如,添加一个整数和一个字符串),Python 在运行时抛出一个异常。
因此,没有变量及其类型的声明。在 Python 中,创建变量只是为了给它们赋值。这在 C 和 ST 中完全不同,其中类型是强的和静态的。每个变量都声明了一个类型,并且在编译时编译器检查该类型和运算符是否被允许。
有关处理变量的信息,请参见以下示例:
# assign the integer 1 to the variable i (also "creates" the variable") i = 1 # assign the string "foobar" to the variable s s = "foobar" # Add 5 to the integer i - this is equivalent to i = i + 5 i += 5 # i now holds the integer 6. # Try to add i and s - this will throw an exception when executed # TypeError: unsupported operand type(s) for +: 'int' and 'str' result = i + s # variables can also be "undeclared" by deleting them. # Further access to the variable i will throw a NameError exception, # as the variable does not exist any more. del i i += 5 # now throws an exception: NameError: name 'i' is not defined
所有现有变量仅引用一个值。 Python 中没有任何未分配或未初始化的变量。为了表示没有值,Python 提供了一个特殊的对象: None
.在 C 或 ST 中,您将使用空指针。它的唯一目的是表达“这里没有价值”,虽然 None
实际上是该类的现有实例 NoneType
.
数值类型和浮点数
与 IEC 或 C 中的数十种整数类型相比,Python 中只有一种整数类型。 Python 中的整数类型没有固定的大小。相反,它们会根据需要增长,并且仅受可用内存的限制。
Integers.py
from __future__ import print_function i = 1 print(i) j = 0x1234 # hex number, is 16#1234 in IEC and 4660 in decimal k = 0o123 # octal number, is 8#123 in IEC and 83 decimal l = 0b101010 # binary number, is 2#101010 in IEC and 42 in decimal print(j, k, l) m = (2 + 3)*10 # k is 50 now print(m) n = 10 ** 100 # 10 to the power of 100 print(n)
结果输出:

Python 中也只有一种浮点类型,类似于 IEC 数据类型 LREAL
.它提供 64 位 IEEE 浮点运算。
语法在很大程度上类似于基于 C 的语言:
# A simple float... a = 123.456 # A float containing the integral value 2 b = 2. # Leading zeroes can be left off c = .3 # same as 0.3 # Exponential / scientific representation d = -123e-5
两种特殊情况是 True
和 False
,定义布尔真值的两个常数。它们的行为类似于整数值 0
和 1
, 除非它们被转换为字符串并返回它们的名称。
Booleans.py
# booleans behave like integers, except when converted to strings. # The built-in function "type" can be used to query the type of a value. print("True: ", True, type(True)) print("False: ", False, type(False)) print("1: ", 1, type(1)) print("False + 0: ", False + 0, type(False + 0)) print("True * 5: ", True * 5, type(True * 5))
结果输出:

字符串
在 IronPython 中,字符串总是 Unicode 和任意长度。如果将它们包含在 '
或者 "
.字符串也可以有三引号 """
或者 '''
,它允许多行字符串文字。
与 C 类似,可以通过反斜杠字符排除特殊字符。作为比较,美元符号 ($
) 在 IEC 中用于此目的。
还有一些原始字符串具有其他反斜杠规则。当字符串应该有文字反斜杠时,这很实用。示例:Windows 文件路径或正则表达式。
Strings.py
# encoding:utf-8 from __future__ import print_function a = "a simple string" b = 'another string' c = "strings may contain 'quotes' of the other type." d = "multiple string literals" ' are concatenated ' '''by the parser''' e = "Escaping: quotes: \" \' backslash: \\ newline: \r\n ascii code: \x40" f = """triple-quoted strings may contain newlines, "single" 'quotes' and '''multiquotes''' of the other type""" g = "Üňíçǿđȩ is also possible: 北京, Москва, Αθήνα, القاهرة" h = r"c:\raw\strings\retain\backslashes.txt" # we iterate over a sequence of all the variables defined above: for i in (a,b,c,d,e,f,g,h): print(i) # prints the contents of the variable
结果输出:

Python 没有字符类型。字符通过使用长度为 1 的字符串来表示。这样,通过字符串进行迭代,或在字符串中进行索引,将返回单个字符串。
列表和元组(数据集)
列表和元组基本上对应于 C 和 IEC 中的数组,但有一些明显的区别:
始终检查索引访问。访问具有无效索引的列表或元组会引发异常。
列表和元组都可以包含不同类型的元素(也可以包含其他列表和元组)。与 C 和 IEC 相比,数组只能包含单一类型的元素。
列表是动态的,可以随时添加、删除或替换元素。
元组是不可更改的:一旦创建了元组,就不能再修改它。
列表是用 list()
构造函数。作为替代方案,您可以使用括号 []
.元组是用 tuple()
构造函数或括号 ()
.
list_tuples.py
from __future__ import print_function print("Testing tuples and lists") # We define a tuple with the numbers from 1 to 10: t = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) print("Tuple:", t) # We can access the 6th element of the tuple. # As in C, index counting starts with 0. print("Element 5:", t[5]) # Subscription is more powerful using the range syntax: print("Range[2:5]:", t[2:5]) # lower bound is inclusive, upper bound is exclusive. print("Range[2::2]:", t[2::2]) # start with 3rd element, and print every 2nd element. print("Range[-3:-1]:", t[-3:-1]) # Start with the 3rd last element, end just before the last element (upper bound is exclusive) print("Range[::-1]:", t[::-1]) # negative step with - print backwards # lists are similar to tuples... l = [11, 12, 13, "8", t] # contains mixed types: 3 integers, a string, and the tuple defined above. print("List:", l) # ... but elements can be added or removed dynamically. l.append(9) # Add a 9 to the list. print("List with 9:", l) print("List Range[3:6:2]:", l[3:6:2]) # print the 4th and 6th element. del l[1] # remove the element at index 1, the 12. print("Removed[1]:", l) del l[1:3] # Remove the elements at index 1 and 2, the 13 and the '8'. print("Removed[1:3]:", l)
结果输出:

字典
Python 还具有哈希表类型(也称为“hashmap”)。与列表相反,它可以使用任何元素(例如字符串)进行索引。它的构造函数是 dict()
并且它的文字用大括号声明 {}
.
示例脚本 dictionaries.py
创建下面显示的输出。在最后一行,脚本以“KeyError”异常终止:
dictionaries.py
from __future__ import print_function print("Testing dictionaries") # Declare a dictionary with three entries, the third being a list d = {1: "a", 2: "b", "my list": [1, 2, 3]} print(d) # print the value of the key 1 print(d[1]) # remove the value with the key "my list" del d["my list"] # Add a value 4 with the key 3 d[3] = 4 print(d) # The "get" method returns the second argument if the key cannot be found. print(d.get(1, 42)) print(d.get(23, 42)) # print all keys in the dictionary for key in d: print(key) # index access for unknown keys will throw a "KeyError" exception! print(d[23])
结果输出:

然后在最后一行,脚本终止:

点击 细节 按钮查看堆栈跟踪。在这里你确定行号 27
和未知的钥匙 23
.
