Python3 Basic Syntax
By default, Python3 source files use UTF-8 encoding, and all strings are Unicode strings.
You can also specify a different encoding for source files:
The above definition allows the use of characters from the Windows-1252 character set in the source file, corresponding to languages such as Bulgarian, Belarusian, Macedonian, Russian, and Serbian.
Identifiers
Section titled “Identifiers”- The first character must be a letter (a-z, A-Z) or an underscore _ .
- The remaining parts of the identifier consist of letters, digits, and underscores.
- Identifiers are case-sensitive.
countandCountare different identifiers. - There is no hard limit on identifier length, but it is recommended to keep them concise (generally no more than 20 characters).
- Reserved keywords are prohibited. Keywords such as
if,for,class, etc., cannot be used as identifiers.
Valid identifiers:
Invalid identifiers:
Python 3 allows Unicode characters as identifiers. You can use Chinese characters as variable names, and non-ASCII identifiers are also permitted.
Testing whether an identifier is valid:
Example
Section titled “Example”Python Reserved Keywords
Section titled “Python Reserved Keywords”Reserved words, also known as keywords, cannot be used as any identifier name. Python’s standard library provides a keyword module that can output all keywords of the current version:
| Category | Keyword | Description |
|---|---|---|
| Logical Values | True |
Boolean true value |
False |
Boolean false value | |
None |
Represents null or no 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 the loop | |
continue |
Skip the remainder of the current loop iteration and proceed to the next | |
| Exception Handling | try |
Attempt to execute a code block |
except |
Catch exceptions | |
finally |
Code block that executes regardless of whether 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) | |
| Async Programming | async |
Declare an asynchronous function |
await |
Wait for an asynchronous operation to complete | |
| Other | assert |
Assertion, used to test whether a condition is true |
in |
Check membership | |
is |
Check object identity (whether they are 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 |
For more Python reserved keywords, see: https://www.runoob.com/python3/python3-keyword.html.
Comments
Section titled “Comments”In Python, single-line comments start with #. Example:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Running the above code produces the following output:
Multi-line comments can use multiple # symbols, or ''' and """:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Running the above code produces the following output:
Lines and Indentation
Section titled “Lines and Indentation”The most distinctive feature of Python is its use of indentation to represent code blocks, without requiring curly braces {}.
The number of indentation spaces is variable, but all statements within the same code block must have the same number of indentation spaces. Example:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”The following code has inconsistent indentation spaces on the last line, which will cause a runtime error:
Example
Section titled “Example”Due to the inconsistent indentation, executing the above program will produce an error similar to:
Multi-line Statements
Section titled “Multi-line Statements”Python usually writes a complete statement on one line, but if a statement is very long, we can use the backslash \\ to implement multi-line statements. For example:
Example
Section titled “Example”Multi-line statements inside [], {}, or () do not require a backslash \\. For example:
Number Types
Section titled “Number Types”Python has four types of numbers: integers, booleans, floating-point numbers, and complex numbers.
- int (integer), such as 1. There is only one integer type
int, represented as long integers, without theLongtype from Python 2. - bool (boolean), such as True.
- float (floating-point number), such as 1.23, 3E-2
- complex (complex number) - Complex numbers consist of a real part and an imaginary part, in the form
a + bj, whereais the real part,bis the imaginary part, andjrepresents the imaginary unit. For example,1 + 2j,1.1 + 2.2j
Strings
Section titled “Strings”- Single quotes
'and double quotes"are used exactly the same way in Python. - Triple quotes (
'''or""") can be used to specify a multi-line string. - Escape character
\\ - Backslash can be used for escaping. Using
rprevents backslash escaping. For example,r"this is a line with \n"will display\nliterally instead of as a newline. - Literal string concatenation:
"this " "is " "string"is automatically converted tothis is string. - Strings can be concatenated with the
+operator and repeated with the*operator. - Python strings have two indexing methods: from left to right starting at 0, and from right to left starting at -1.
- Python strings cannot be changed.
- Python has no separate character type; a single character is simply a string of length 1.
- String slicing:
str[start:end], wherestart(inclusive) is the slice start index andend(exclusive) is the slice end index. - String slicing can include a step parameter:
str[start:end:step]
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Here r stands for raw, i.e., raw string, which automatically prevents backslash escaping. For example:
Output of the above example:
Blank Lines
Section titled “Blank Lines”Blank lines are used to separate functions or methods within a class, indicating the start of a new block of code. A blank line is also used between the class and function entry to highlight the start of the function entry.
Blank lines differ from code indentation. Blank lines are not part of Python’s syntax. Omitting blank lines when writing code will not cause the Python interpreter to produce an error. However, the purpose of blank lines is to separate code blocks 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
Section titled “Waiting for User Input”Executing the following program will wait for user input after pressing Enter:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”In the above code, \n\n will output two new blank lines before the result. Once the user presses the Enter key, the program will exit.
Multiple Statements on the Same Line
Section titled “Multiple Statements on the Same Line”Python allows multiple statements on the same line, separated by semicolons ;. Here is a simple example:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Running the above code as a script produces:
Running in the interactive command line produces:
Here, 7 represents the number of characters. runoob has 6 characters, and \n represents one character, totaling 7 characters.
Code Groups from Multiple Statements
Section titled “Code Groups from Multiple Statements”A group of statements with the same indentation forms a code block, which we call a code group.
For compound statements like if, while, def, and class, the first line starts with a keyword and ends with a colon :. The line or lines of code after this line form the code group.
We call the first line and the subsequent code group a clause.
Example:
print Output
Section titled “print Output”The print function defaults to outputting with a newline. To output without a newline, add end="" at the end of the variable:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”The output of the above example:
More content: Python2 and Python3 print without newline
import and from…import
Section titled “import and from…import”In Python, use import or from...import to import corresponding modules.
Import an entire module (somemodule): import somemodule
Import a specific function from a module: from somemodule import somefunction
Import multiple functions from a module: from somemodule import firstfunc, secondfunc, thirdfunc
Import all functions from a module: from somemodule import *
Importing the sys module
Section titled “Importing the sys module”Importing the argv, path members from the sys module
Section titled “Importing the argv, path members from the sys module”For more content, see: Main differences between Python import and from … import
Command Line Arguments
Section titled “Command Line Arguments”Many programs can perform some operations to view basic information. Python can use the -h parameter to view parameter help information:
When executing Python in script form, we can receive command line input parameters. For specific usage, refer to Python 3 Command Line Arguments.