Python3 Basic Syntax
Encoding
By default, Python3 source files use theUTF-8encoding, and all strings are unicode strings.
Of course you can also specify a different encoding for the source file:
# -*- coding: cp-1252 -*-
The above definition allows the source file to use characters from the Windows-1252 character set, suitable for Bulgarian, Belarusian, Macedonian, Russian, and Serbian.
Identifiers
- The first character must be a letter (a-z, A-Z) or an underscore_ 。
- The other parts of an identifier consist of letters, digits, and underscores.
- Identifiers are case-sensitive; count and Count are different identifiers.
- Identifiers have no hard length limit, but it is recommended to keep them concise (generally no more than 20 characters).
- Reserved keywords are prohibited; for example, if, for, and class cannot be used as identifiers.
Valid identifiers:
age = 25 # 普通变量名,最常见 user_name = "Alice" # 用下划线连接单词,清晰易读 _total = 100 # 下划线开头通常表示“内部使用”或“私有” MAX_SIZE = 1024 # 全大写通常表示“常量”(固定不变的值) calculate_area() # 函数名,动词+名词 StudentInfo # 类名,首字母大写(驼峰命名法) __private_var # 双下划线开头,有特殊含义
Invalid identifiers:
2nd_place = "silver" # 错误:以数字开头 user-name = "Bob" # 错误:包含连字符 class = "Math" # 错误:使用关键字 $price = 9.99 # 错误:包含特殊字符 for = "loop" # 错误:使用关键字
Python 3 allows Unicode characters as identifiers, so Chinese can be used for variable names; non-ASCII identifiers are also allowed.
姓名 = "张三" # 合法 π = 3.14159 # 合法
Test whether an identifier is valid:
Example
try:
exec(f"{name} = None")
return True
except:
return False
print(is_valid_identifier("2var")) # False
print(is_valid_identifier("var2")) # True
Python Reserved Keywords
Reserved words are keywords; we cannot use them as any identifier name. 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', 'async', 'await', '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'] >>>
| Category | Keyword | Description |
|---|---|---|
| Boolean values | True | Boolean true value |
False | Boolean false value | |
None | Represents empty or no value | |
| Logical operations | and | Logical AND operation |
or | Logical OR operation | |
not | Logical NOT operation | |
| Conditional control | if | Conditional statement |
elif | Otherwise if (abbreviation of else if) | |
else | Otherwise branch | |
| Loop control | for | Iteration loop |
while | Conditional loop | |
break | Break out of the loop | |
continue | Skip the rest of the current loop and go to the next iteration | |
| Exception handling | try | Try to execute a code block |
except | Catch an exception | |
finally | Code block that executes whether or not an exception occurs | |
raise | Raise an exception | |
| Function definition | def | Define a function |
return | Return a value from a function | |
lambda | Create an anonymous function | |
| Classes and objects | class | Define a class |
del | Delete an object reference | |
| Module import | import | Import a module |
from | Import a specific part from a module | |
as | Create an alias for an imported module or object | |
| Scope | global | Declare a global variable |
nonlocal | Declare a nonlocal variable (used in nested functions) | |
| Asynchronous programming | async | Declare an async function |
await | Wait for an async operation to complete | |
| Others | assert | Assert, used to test whether a condition is true |
in | Check membership | |
is | Check object identity (whether it is the same object) | |
pass | Empty statement, used as a placeholder | |
with | Context manager, used for resource management | |
yield | Return a value from a generator function |
More Python reserved keyword reference:https://www.example.com/python3/python3-keyword.html。
Comments
In Python, single-line comments start with#and are written as follows:
Example (Python 3.0+)
Executing the above code, the output is:
Hello, Python!
Multi-line comments can use multiple#hash signs, and also'''and""":
Example (Python 3.0+)
Executing the above code, the output is:
Hello, Python!
Lines and Indentation
The most distinctive feature of Python is using indentation to represent code blocks; no curly braces are needed.{} 。
The number of spaces in indentation is variable, but statements in the same code block must contain the same number of indentation spaces. Example:
Example (Python 3.0+)
In the following code, the last line of statements has inconsistent indentation, which will cause a runtime error:
Example
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False") # Inconsistent indentation will cause a runtime error
Due to inconsistent indentation, the above program will produce an error similar to the following after execution:
File "test.py", line 6
print ("False") # 缩进不一致,会导致运行错误
^
IndentationError: unindent does not match any outer indentation level
Multi-line Statements
Python usually writes one statement per line, but if a statement is very long, we can use a backslash\to implement multi-line statements, for example:
total = item_one + \
item_two + \
item_three
Example
item_two = 2
item_three = 3
total = item_one + \
item_two + \
item_three
print(total) # Output is 6
Multi-line statements inside [], {}, or () do not need a backslash\, for example:
total = ['item_one', 'item_two', 'item_three',
'item_four', 'item_five']
Number Types
Python has four types of numbers: integers, booleans, floats, and complex numbers.
- int(Integer), such as 1; there is only one integer type, int, represented as a long integer, without the Long type in Python 2.
- bool(Boolean), such as True.
- float(Float), such as 1.23, 3E-2
- complex(Complex) - Complex numbers consist of a real part and an imaginary part, in the form a + bj, where a is the real part, b is the imaginary part, and j represents the imaginary unit. For example, 1 + 2j, 1.1 + 2.2j
String
- In Python, single quotes'and double quotes"are used exactly the same.
- Using triple quotes ('''or""") can specify a multi-line string.
- Escape Character\。
- Backslashes can be used for escaping; usingrcan prevent the backslash from escaping. For example,r"this is a line with \n"Then\nwill be displayed, not a line break.
- Concatenate strings literally, such as"this " "is " "string"will be automatically converted tothis is string。
- Strings can be concatenated using the+operator, and repeated using the*operator.
- Strings in Python have two indexing methods: from left to right starting at0, and from right to left starting at-1.
- Strings in Python cannot be changed.
- Python has no separate character type; a character is just a string of length 1.
- String Slicingstr[start:end], where start (inclusive) is the index where the slice begins, and end (exclusive) is the index where the slice ends.
- String slicing can include a step parameter, step, with the following syntax:str[start:end:step]
word = '字符串' sentence = "这是一个句子。" paragraph = """这是一个段落, 可以由多行组成"""
Example (Python 3.0+)
Here r stands for raw, i.e., raw string, which will automatically escape backslashes, for example:
>>> print('\n') # 输出空行
>>> print(r'\n') # 输出 \n
\n
>>>
The output of the above example is:
123456789 12345678 1 345 3456789 24 123456789123456789 123456789你好 ------------------------------ hello example hello\nexample
Blank Lines
Use blank lines between functions or between class methods to indicate the start of a new block of code. Also use a blank line between the class and function entries to highlight the start of the function entry.
Blank lines are different from code indentation. Blank lines are not part of Python syntax. If you do not insert blank lines, the Python interpreter will still run without errors. However, the purpose of blank lines is to separate two pieces of code with different functions or meanings, making future code maintenance or refactoring easier.
Remember:Blank lines are also part of the program code.
Waiting for User Input
After executing the following program and pressing the Enter key, it will wait for user input:
Example (Python 3.0+)
In the above code,\n\ntwo new blank lines will be output before the result is output. Once the user presses theenterkey, the program will exit.
Multiple Statements on the Same Line
Python can use multiple statements on the same line, with semicolons between statements;as separators. The following is a simple example:
Example (Python 3.0+)
Using a script to execute the above code, the output is:
example
Using the interactive command line to execute, the output is:
>>> import sys; x = 'example'; sys.stdout.write(x + '\n') example 7
Here 7 indicates the number of characters,examplethere are 6 characters,\nrepresenting one character, adding up to7characters.
>>> import sys
>>> sys.stdout.write(" hi ") # hi 前后各有 1 个空格
hi 4
Multiple Statements Form a Code Group
A group of statements with the same indentation constitutes a code block, which we call a code group.
Compound statements like if, while, def, and class start with a keyword on the first line and end with a colon ( : ). One or more lines of code after that line form a code group.
We call the first line and the following code group a clause.
The following is an example:
if expression : suite elif expression : suite else : suite
print Output
printBy default, output is line-broken. To achieve no line break, you need to add at the end of the variableend="":
Example (Python 3.0+)
The execution result of the above example is:
a b --------- a b
For more information, see:Python2 and Python3 print without newline
import and from...import
In Python, useimportorfrom...importto import the corresponding module.
Import the entire module (somemodule), the format is:import somemodule
Import a function from a module, the format is:from somemodule import somefunction
Import multiple functions from a module, the format is:from somemodule import firstfunc, secondfunc, thirdfunc
Import all functions from a module, the format is:from somemodule import *
Import the sys module
Import the argv, path members of the sys module
For more information, refer to:The main difference between Python import and from … import
Command-line Arguments
Many programs can perform some operations to view basic information. Python can use the -h parameter to view help information for each parameter:
$ python -h usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -c cmd : program passed in as string (terminates option list) -d : debug output from parser (also PYTHONDEBUG=x) -E : ignore environment variables (such as PYTHONPATH) -h : print this help message and exit [ etc. ]
When executing Python in script form, you can receive command line input parameters. For specific usage, refer toPython 3 Command Line Arguments。
Other Extensions