Python Basic Syntax
The Python language has many similarities with languages such as Perl, C, and Java. However, there are also some differences.
In this chapter we will learn the basic syntax of Python to help you quickly learn Python programming.
Your First Python Program
Interactive programming
Interactive programming does not require creating a script file; you write code through the interactive mode of the Python interpreter.
On Linux, you only need to enter the Python command at the command line to start interactive programming. The prompt window is as follows:
$ python
Python 2.7.6
(
default
,
Sep
9
2014
,
15
:
04
:
36
)
[
GCC 4.2.1 Compatible Apple LLVM
6.0
(
clang-600.0.39
)
]
on darwin
Type
"help"
,
"copyright"
,
"credits"
or
"license"
for
more information.
On Windows, the interactive programming client is already installed when you install Python. The prompt window is as follows:

Enter the following text at the Python prompt, then press Enter to see the result:
>>> print ("Hello, Python!")
In Python version 2.7.6, the output of the above example is as follows:
Hello, Python!
Script programming
Calling the interpreter with a script argument starts executing the script until it finishes. Once the script execution is complete, the interpreter is no longer valid.
Let's write a simple Python script program. All Python files use the .py extension. Copy the following source code into a file named test.py.
print ("Hello, Python!")
Here, assume you have already set the Python interpreter PATH variable. Use the following command to run the program:
$ python test.py
Output result:
Hello, Python!
Let's try another way to execute a Python script. Modify the test.py file as follows:
Example
#!/usr/bin/python
(
"Hello, Python!"
)
Here, assuming your Python interpreter is in the /usr/bin directory, use the following command to execute the script:
$ chmod +x test.py # 脚本文件添加可执行权限
$ ./test.py
Output result:
Hello, Python!
Using the Python 3.x print function in Python 2.x
If you want to use the Python 3.x print function in Python 2.x, you can import future the package, which disables the Python 2.x print statement and adopts the Python 3.x print function:
Example
list
=
[
"a"
,
"b"
,
"c"
]
list
The print statement in python2.x
[
'a'
,
'b'
,
'c'
]
from
future
import
print_function
Import future package
list
The print statement in Python 2.x is disabled and using it raises an error
File
"
,
line
1
list
^
SyntaxError
: invalid syntax
(
list
)
Use the Python 3.x print function
[
'a'
,
'b'
,
'c'
]
Many compatibility features designed in Python 3.x and Python 2.x can be imported through future this package.
Python Identifiers
In Python, identifiers consist of letters, digits, and underscores.
In Python, all identifiers can include English letters, digits, and underscores (_), but cannot start with a digit.
Identifiers in Python are case-sensitive.
Identifiers starting with an underscore have special meaning. A single leading underscore, as in _foo, represents a class attribute that cannot be accessed directly and must be accessed through the interface provided by the class; it cannot be imported with from xxx import *.
A double leading underscore, as in __foo, represents a private member of a class, while those with double leading and trailing foo underscores represent identifiers reserved for special methods in Python, such as init(), which represents the constructor of a class.
Python can display multiple statements on the same line by separating them with semicolons ; for example:
>>> print ('hello');print ('runoob');
hello
runoob
Python Reserved Words
The following list shows the reserved words in Python. These reserved words cannot be used as constants or variables, or as any other identifier names.
All Python keywords contain only lowercase letters.
| and | exec | not |
|---|---|---|
| assert | finally | or |
| break | for | pass |
| class | from | |
| continue | global | raise |
| def | if | return |
| del | import | try |
| elif | in | while |
| else | is | with |
| except | lambda | yield |
Lines and Indentation
The biggest difference when learning Python compared to other languages is that Python code blocks do not use curly braces {} to control classes, functions, and other logical judgments. The most distinctive feature of Python is the use of indentation to write modules.
The number of indentation spaces is variable, but all statements in a code block must contain the same number of indentation spaces, which must be strictly enforced.
The following example uses four spaces for indentation:
Example
if
True
:
(
"True"
)
else
:
(
"False"
)
The following code will cause an execution error:
Example
#!/usr/bin/python
-- coding: UTF-8 --
Filename: test.py
if
True
:
(
"Answer"
)
(
"True"
)
else
:
(
"Answer"
)
Without strict indentation, an error will be reported at execution time
(
"False"
)
Executing the above code will produce the following error message:
File "test.py", line 11
print ("False")
^
IndentationError: unindent does not match any outer indentation level
IndentationError: unindent does not match any outer indentation levelThe error indicates that your indentation is inconsistent, with some lines using the tab key and others using spaces; just make it consistent.
If it is IndentationError: unexpected indent error, then the Python compiler is telling you "Hi buddy, the formatting in your file is wrong, probably a tab and space alignment issue", so Python is very strict about formatting.
Therefore, the same number of leading indentation spaces must be used within a Python code block.
It is recommended that you use at each indentation level a single tab or two spaces or four spaces , and remember not to mix them
Multi-line statements
In Python statements, a new line is generally used as the statement terminator.
However, we can use a backslash (\) to split a single-line statement across multiple lines, as shown below:
total = item_one + \
item_two + \
item_three
When a statement contains [], {}, or () brackets, there is no need to use a line continuation character. For example:
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Python Quotes
Python can use single quotes ( ' ), double quotes ( " ), and triple quotes ( ''' or """ ) to represent strings, and the opening and closing quotes must be of the same type.
Triple quotes can span multiple lines and are a quick syntax for writing multi-line text, often used for docstrings and treated as comments at specific places in a file.
word = 'word'
sentence = "这是一个句子。"
paragraph = """这是一个段落。
包含了多个语句"""
Python Comments
In Python, single-line comments start with #.
Example
#!/usr/bin/python
-- coding: UTF-8 --
Filename: test.py
The first comment
(
"Hello, Python!"
)
The second comment
Output result:
Hello, Python!
Comments can be placed at the end of a statement or expression line:
name = "Runoob" # 这里的内容是一个注释
In Python, multi-line comments use three single quotes ''' or three double quotes """.
Example
#!/usr/bin/python
-- coding: UTF-8 --
Filename: test.py
'''
This is a multi-line comment using single quotes.
This is a multi-line comment using single quotes.
This is a multi-line comment using single quotes.
'''
"""
This is a multi-line comment using double quotes.
This is a multi-line comment using double quotes.
This is a multi-line comment using double quotes.
"""
Python 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 are different from code indentation; blank lines are not part of Python syntax. Not inserting blank lines when writing code will not cause errors when the Python interpreter runs. However, blank lines serve to separate two sections of code with different functions or meanings, making future maintenance or refactoring easier.
Remember: blank lines are also part of the program code.
Waiting for user input
The following program waits for user input after execution and exits when the Enter key is pressed:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
raw_input("按下 enter 键退出,其他任意键显示...\n")
In the above code, \n implements a line break. Once the user presses the enter (carriage return) key, it exits; other keys are displayed.
Multiple statements on one line
Python can use multiple statements on the same line, separated by semicolons (;). The following is a simple example:
#!/usr/bin/python
import sys; x = 'runoob'; sys.stdout.write(x + '\n')
The output of the code above is:
$ python test.py
runoob
print output
The default output of print is followed by a newline; to avoid a newline, add a comma , at the end of the variable.
Example
#!/usr/bin/python
-- coding: UTF-8 --
x
=
"a"
y
=
"b"
Output with a newline
x
y
'---------'
Output without a newline
x
,
y
,
Output without a newline
x
,
y
The example above produces:
a
b
---------
a b a b
For more information, refer to:print without a newline in Python2 and Python3
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
Command-Line Arguments
Many programs can perform 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 running Python in script form, we can receive arguments entered on the command line; see Python Command-Line Arguments.