Python3 Basic Syntax
Encoding
By default, Python 3 source code files are encoded in UTF-8, and all strings are unicode strings. You can also specify a different encoding for source code files:
# -*- coding: cp-1252 -*-
This definition allows the use of character encoding 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 from the alphabet or an underscore
_
. - The rest of the identifier consists of letters, digits, and underscores.
- Identifiers are case-sensitive.
In Python 3, you can use Chinese as variable names, and non-ASCII identifiers are also allowed.
Python Reserved Words
Reserved words, or keywords, are words that we cannot use as any identifier names. Python's standard library provides a keyword module that can output all keywords for 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
In Python, single-line comments start with a #, as shown below:
Example (Python 3.0+)
#!/usr/bin/python3
# First comment
print("Hello, Python!") # Second comment
Executing the above code will produce the following output:
Hello, Python!
Multi-line comments can use multiple #
symbols, as well as '''
and """
:
Example (Python 3.0+)
#!/usr/bin/python3
# First comment
# Second comment
'''
Third comment
Fourth comment
'''
"""
Fifth comment
Sixth comment
"""
print("Hello, Python!")
Executing the above code will produce the following output:
Hello, Python!
Lines and Indentation
Python's distinctive feature is the use of indentation to denote code blocks, rather than braces {}
.
The number of spaces for indentation is variable, but all statements within the same code block must have the same indentation. Here is an example:
Example (Python 3.0+)
if True:
print("True")
else:
print("False")
The following code will cause a runtime error due to inconsistent indentation in the last statement:
Example
if True:
print("Answer")
print("True")
else:
print("Answer")
print("False") # Inconsistent indentation will cause a runtime error
The above program, due to inconsistent indentation, will produce an error similar to:
File "test.py", line 6
print("False") # Inconsistent indentation will cause a runtime error
^
IndentationError: unindent does not match any outer indentation level
Multiline Statements
Python usually writes one statement per line, but if a statement is long, we can use a backslash \
to achieve a multiline statement, for example:
total = item_one + \
item_two + \
item_three
For multiline statements within []
, {}
, or ()
, no backslash \
is needed, for example:
total = ['item_one', 'item_two', 'item_three',
'item_four', 'item_five']
Number Types
Python has four types of numbers: integer, boolean, floating-point, and complex.
- int (integer), such as 1, there is only one integer type, int, which represents a long integer, unlike the Long type in Python 2.
- bool (boolean), such as True.
- float (floating-point), such as 1.23, 3E-2
- complex (complex), such as 1 + 2j, 1.1 + 2.2j
Strings in Python
Single quotes
'
and double quotes"
are used identically in Python.Triple quotes (
'''
or"""
) can be used to specify a multi-line string.The escape character
\
.Backslashes can be used to escape characters, and using
r
before the string can prevent backslashes from escaping. For example, r"this is a line with \n" will display\n
instead of causing a newline.Concatenating strings literally, such as "this " "is " "string" will be automatically converted to this is string.
Strings can be concatenated using the
+
operator and repeated using the*
operator.Python strings have two indexing methods: from left to right starting at
0
, and from right to left starting at-1
.Strings in Python are immutable.
Python does not have a separate character type; a character is simply a string of length 1.
The syntax for slicing a string is as follows:
variable[start_index:end_index:step]
word = '字符串' sentence = "这是一个句子。" paragraph = """这是一个段落, 可以由多行组成"""
Example (Python 3.0+)
#!/usr/bin/python3
str = '123456789'
print(str) # Output the string
print(str[0:-1]) # Output all characters from the first to the second-to-last
print(str[0]) # Output the first character
print(str[2:5]) # Output characters from the third to the fifth
print(str[2:]) # Output all characters from the third onwards
print(str[1:5:2]) # Output characters from the second to the fifth with a step of 2
print(str * 2) # Output the string twice
print(str + '你好') # Concatenate the string
print('------------------------------')
print('hello\ntutorialpro') # Use backslash (\) + n to escape special characters
print(r'hello\ntutorialpro') # Adding an r before the string indicates a raw string, preventing escape
Here, r
stands for raw, meaning a raw string that automatically escapes backslashes. For example:
>>> print('\n') # Outputs a blank line
>>> print(r'\n') # Outputs \n
\n
>>>
Output of the above example:
123456789
12345678
1
345
3456789
24
123456789123456789
123456789你好
------------------------------
hello
tutorialpro
hello\ntutorialpro
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 entry of a class and a function to highlight the start of the function.
Blank lines are not part of Python syntax. Omitting them will not cause errors in the Python interpreter. However, their purpose is to separate different functionalities or meanings of code, facilitating future maintenance or refactoring.
Remember: Blank lines are part of the program code.
Waiting for User Input
Running the following program will wait for user input after pressing Enter:
Example (Python 3.0+)
#!/usr/bin/python3
input("\n\nPress enter to exit.")
In the above code, \n\n
will output two new blank lines before the result. Once the user presses enter, the program will exit.
Displaying 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+)
#!/usr/bin/python3
import sys; x = 'tutorialpro'; sys.stdout.write(x + '\n')
Executing the above code as a script will output:
tutorialpro
Executing in an interactive command line will output:
>>> import sys; x = 'tutorialpro'; sys.stdout.write(x + '\n')
tutorialpro
7
The number 7 here represents the number of characters, where tutorialpro has 6 characters and \n represents one character, totaling 7 characters.
>>> import sys
This is a Chinese to English translation, please provide the English translation for this text. Do not provide any explanations or text apart from the translation. Chinese: >>> sys.stdout.write(" hi ") # hi has 1 space before and after hi 4
---
## Code Blocks Composed of Multiple Statements
A group of statements with the same indentation level forms a code block, which we call a code group.
Compound statements like if, while, def, and class start with a keyword and end with a colon (:), followed by one or more lines of code that form the code group.
We refer to the first line and the subsequent code group as a clause.
Here is an example:
if expression : suite elif expression : suite else : suite
---
## print Output
**print** by default outputs a newline. To achieve no newline, you need to add `end=""` at the end of the variable:
## Example (Python 3.0+)
!/usr/bin/python3
x="a" y="b"
Newline output
print( x ) print( y )
print('---------')
No newline output
print( x, end=" " ) print( y, end=" " ) print()
The execution result of the above example is:
a
b
a b
>
**For more content, refer to:** [Python2 vs Python3 print without newline](../w3cnote/python-print-without-newline.html)
---
## import and from...import
In Python, use `import` or `from...import` to import modules.
Import the entire module, format: `import somemodule`
Import a specific function from a module, format: `from somemodule import somefunction`
Import multiple functions from a module, format: `from somemodule import firstfunc, secondfunc, thirdfunc`
Import all functions from a module, format: `from somemodule import *`
## Import the sys Module
import sys print('================Python import mode==========================') print ('Command line arguments are:') for i in sys.argv: print (i) print ('\n Python path is',sys.path)
## Import argv, path Members from the sys Module
from sys import argv,path # Import specific members
print('================python from import===================================') print('path:',path) # Path member is already imported, no need to add sys.path
---
## Command Line Arguments
Many programs can perform operations to view basic information. Python can use the -h parameter to view help information for various parameters:
$ 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 using the script form to execute Python, it can receive parameters input from the command line. For specific usage, refer to Python 3 Command Line Arguments.