Teach yourself python--basic grammar

Encoding
By default, Python 3 source code files are encoded in UTF-8, and all strings are unicode strings. Of course, you can also specify a different encoding for the source file:

-- coding: cp-1252 --

Identifier
· The first character must be a letter in the alphabet or an underscore'_'.
· The other parts of the identifier consist of letters, numbers and underscores.
· Identifiers are case sensitive.
In Python 3, non-ASCII identifiers are also allowed.

Python reserved words
Reserved words are keywords, we cannot use them as any identifier names. Python's standard library provides a keyword module that can output all keywords of the current version:

import keyword>>> keyword.kwlist[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]

Comments
Single-line comments in Python begin with #, examples are as follows:
#!/usr/bin/python3

The first comment print (“Hello, Python!”) ​​# The second comment

执行以上代码,输出结果为:
Hello, Python!
多行注释可以用多个 # 号:
#!/usr/bin/python3

The first note# The second note

print ("Hello, Python!") 
执行以上代码,输出结果为:
Hello, Python!

行与缩进
python最具特色的就是使用缩进来表示代码块,不需要使用大括号({})。
缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。实例如下:
if True:
print ("True")else:
print ("False")
以下代码最后一行语句缩进数的空格数不一致,会导致运行错误:
if True:
    print ("Answer")
    print ("True")else:
    print ("Answer")
  print ("False")    # 缩进不一致,会导致运行错误
以上程序由于缩进不一致,执行后会出现类似以下错误:
 File "test.py", line 6
    print ("False")    # 缩进不一致,会导致运行错误
                                      ^IndentationError: unindent does not match any outer indentation level

Guess you like

Origin blog.csdn.net/weixin_47580822/article/details/112926942