Python3 Basic Syntax
Encoding
By default, Python3 source files are encoded in UTF-8 , and all strings are unicode strings.
You can of course specify a different encoding for the source file:
# -*- coding: cp-1252 -*-
The definition above allows the source file to use characters from the Windows-1252 character set, suitable for languages such as Bulgarian, Belarusian, Macedonian, Russian, and Serbian.
Identifiers
- The first character must be a letter (a-z, A-Z) or an underscore _ .
- The rest of the identifier consists of letters, digits, and underscores.
- Identifiers are case-sensitive; count and Count are different identifiers.
- There is no hard limit on identifier length, but keeping them short is recommended (generally no more than 20 characters).
- Reserved keywords such as 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 in identifiers, so Chinese characters can be used as variable names; non-ASCII identifiers are permitted.
姓名 = "张三" # 合法
π = 3.14159 # 合法
Test whether an identifier is valid:
Example
def
is_valid_identifier
(
name
)
:
try
:
exec
(
f
"{name} = None"
)
return
True
except
:
return
False
(
is_valid_identifier
(
"2var"
)
)
False
(
is_valid_identifier
(
"var2"
)
)
True
Python reserved keywords
Reserved words are keywords and cannot be used 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 | The keyword | Description |
|---|---|---|
| Logical values | True |
Boolean true value |
False |
Boolean false value | |
None |
Represents an empty or absent value | |
| Logical operations | and |
Logical AND operation |
or |
Logical OR operation | |
not |
Logical NOT operation | |
| Conditional control | if |
Conditional statement |
elif |
Else if (abbreviation of else if) | |
else |
Else branch | |
| Loop control | for |
Iteration loop |
while |
Conditional loop | |
break |
Break out of loop | |
continue |
Skip the rest of the current loop and move to the next iteration | |
| Exception handling | try |
Try to execute a block of code |
except |
Catching an Exception | |
finally |
A block of code that executes whether or not an exception occurs | |
raise |
Throwing an Exception | |
| Function definition | def |
Defining 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 the module |
from |
Import specific parts from a module | |
as |
Create an alias for an imported module or object | |
| Scope | global |
Declare a global variable |
nonlocal |
Declare a nonlocal variable (for nested functions) | |
| Asynchronous programming | async |
Declare an asynchronous function |
await |
Wait for an asynchronous operation to complete | |
| Others | assert |
Assertion, 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 for resource management | |
yield |
Return a value from a generator function |
For more Python reserved keywords, see:https://www.runoob.com/python3/python3-keyword.html。
Notes
Single-line comments in Python start with # , as shown below:
Example (Python 3.0+)
#!/usr/bin/python3
The first comment
(
"
Hello, Python!
"
)
The second comment
The output of the code above is:
Hello, Python!
Multi-line comments can use multiple # signs, as well as ''' and """:
Example (Python 3.0+)
#!/usr/bin/python3
The first comment
The second comment
'''
Third comment Fourth comment
'''
"""
Fifth comment Sixth comment
"""
(
"
Hello, Python!
"
)
The output of the code above is:
Hello, Python!
Lines and indentation
Python's most distinctive feature is using indentation to represent code blocks instead of braces {} .
The number of indentation spaces is variable, but statements in the same code block must have the same number of indentation spaces. Example:
Example (Python 3.0+)
if
True
:
(
"
True
"
)
else
:
(
"
False
"
)
The following code has an inconsistent number of indentation spaces on the last line, which causes a runtime error:
Example
if
True
:
(
"Answer"
)
(
"True"
)
else
:
(
"Answer"
)
(
"False"
)
Inconsistent indentation causes a runtime error
The program above, due to inconsistent indentation, produces an error similar to the following when executed:
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 split it across multiple lines, for example:
total = item_one + \
item_two + \
item_three
Example
item_one
=
1
item_two
=
2
item_three
=
3
total
=
item_one + \
item_two + \
item_three
(
total
)
The output is 6
For multi-line statements inside [], {}, or (), no backslash is needed, for example:
total = ['item_one', 'item_two', 'item_three',
'item_four', 'item_five']
Number types
Python has four numeric types: integer, boolean, float, and complex.
- int (integer), such as 1; there is only one integer type int, represented as a long integer; there is no Long as in Python 2.
- bool (boolean), such as True.
- float (float), such as 1.23 and 3E-2
- complex (complex) - a complex number consists 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 denotes the imaginary unit. Examples: 1 + 2j, 1.1 + 2.2j
Strings
- In Python, single quotes ' and double quotes " are used exactly the same way.
- Triple quotes (''' or """) can specify a multi-line string.
- The backslash is the escape character.
- A backslash can be used for escaping; using r prevents the backslash from escaping. For example r"this is a line with \n" then the backslash-n sequence is displayed rather than producing a line break.
- Concatenate string literals as-is, for example "this " "is " "string" is automatically converted to this is string。
- Strings can be concatenated with the + operator and repeated with the * operator.
- Strings in Python have two indexing directions: from left to right starting at 0, and from right to left starting at -1.
- Strings in Python cannot be changed.
- Python has no separate character type; a character is simply a string of length 1.
- String slicing str[start:end], where start (inclusive) is the starting index and end (exclusive) is the ending index.
- String slices can take a step parameter with the syntax str[start:end:step]
word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,
可以由多行组成"""
Example (Python 3.0+)
#!/usr/bin/python3
str
=
'
123456789
'
(
str
)
Output the string
(
str
[
0
:-
1
]
)
Output all characters from the first to the second-to-last
(
str
[
0
]
)
Output the first character of the string
(
str
[
2
:
5
]
)
Output characters from the third up to but not including the sixth
(
str
[
2
:
]
)
Output all characters starting from the third
(
str
[
1
:
5
:
2
]
)
Output every other character from the second to the fifth (step 2)
(
str
2
)
Output the string twice
(
str
'
Hello
'
)
Concatenating Strings
(
'
'
)
(
'
hello
\n
runoob
'
)
Use a backslash followed by n to escape special characters
(
r
'
hello
\n
runoob
'
)
Prefixing a string with r makes it a raw string, so no escaping occurs
Here r stands for raw, i.e. a raw string, which escapes backslashes automatically, for example:
>>> print('\n') # 输出空行
>>> print(r'\n') # 输出 \n
\n
>>>
The example above produces the following output:
123456789
12345678
1
345
3456789
24
123456789123456789
123456789你好
------------------------------
hello
runoob
hello\nrunoob
Blank lines
Blank lines separate functions or methods of a class, marking the start of a new section of code. A single blank line also separates the class and function entry to highlight the start of the function entry.
Blank lines differ from indentation: they are not part of Python's syntax. Omitting them will not cause the interpreter to fail. However, blank lines serve to separate two sections of code with different functions or meanings, making later maintenance or refactoring easier.
**Remember:** blank lines are also part of the program code.
Waiting for user input
Running the program below will wait for user input after the Enter key is pressed:
Example (Python 3.0+)
#!/usr/bin/python3
input
(
"
\n
\n
Press the enter key to exit.
"
)
In the code above, \n\n outputs two new blank lines before the result. Once the user presses the enter key, the program exits.
Multiple statements on one line
Python can place multiple statements on the same line, separated by semicolons ; , as shown in this simple example:
Example (Python 3.0+)
#!/usr/bin/python3
import
sys
;
x
=
'
runoob
'
;
sys
.
stdout
.
write
(
x
'
\n
'
)
Running the code above as a script produces:
runoob
Running it in the interactive shell produces:
>>> import sys; x = 'runoob'; sys.stdout.write(x + '\n')
runoob
7
Here 7 is the number of characters,runoob has 6 characters,\n represents one character, adding up to 7 characters.
>>> import sys
>>> sys.stdout.write(" hi ") # hi 前后各有 1 个空格
hi 4
Multiple statements form a code group
A group of statements with the same indentation forms a code block, which we call a code group.
For compound statements such as if, while, def, and class, the first line starts with a keyword and ends with a colon ( : ); one or more following lines form the code group.
We call the header line together with the following code group a clause.
The following example:
if expression :
suite
elif expression :
suite
else :
suite
print output
print Output ends with a newline by default; to avoid the newline, add end="" at the end of the variable:
Example (Python 3.0+)
#!/usr/bin/python3
x
=
"
a
"
y
=
"
b
"
Output with a newline
(
x
)
(
y
)
(
'
'
)
Output without a newline
(
x
,
end
=
"
"
)
(
y
,
end
=
"
"
)
(
)
The example above produces:
a
b
---------
a b
For more information, refer to:print without a newline in Python2 and Python3
import and from...import
In Python, use import or from...import to import the corresponding module.
To import the whole module (somemodule), use: import somemodule
To import a function from a module, use: from somemodule import somefunction
To import several functions from a module, use: from somemodule import firstfunc, secondfunc, thirdfunc
To import all functions from a module, use: from somemodule import *
Import the sys module
import
sys
(
'
================Python import mode==========================
'
)
(
'
The command-line arguments are:
'
)
for
i
in
sys
.
argv
:
(
i
)
(
'
\n
The python path is
'
,
sys
.
path
)
Import the argv and path members of the sys module
from
sys
import
argv
,
path
Import specific members
(
'
================python from import===================================
'
)
(
'
path:
'
,
path
)
Since the path member has already been imported, there is no need to write sys.path when referencing it here
For more information, refer to:The main difference between Python import and from ... import
Command-Line Arguments
Many programs can perform operations to view basic information; Python can use the -h parameter to view help 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 running Python in script form, we can receive arguments entered on the command line; see Python 3 command-line arguments。