Python Basic Syntax
The Python language has many similarities with languages such as Perl,c and Java. However, there are some differences.
In this chapter we will learn the basic syntax of Python and let you quickly learn Python programming. Learn from Python with a picture overview
Interactive programming of the first Python program
Interactive programming does not require the creation of a script file, it is written in 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, prompting the following window:
$ pythonPython 2.4.3 (#1, Nov 11 2010, 13:34:43)[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>>
The default interactive programming client is already installed on window when you install Python, and the prompt window is as follows:
Enter the following text information in the Python prompt, and then press ENTER to see the effect of the operation:
>>> print "Hello, Python!";
In Python version 2.4.3, the above example outputs the following results:
Hello, Python!
If you are running a new version of Python, you will need to use parentheses in the print statement such as:
>>> print ("Hello, Python!");
Script-type programming
Invoking the interpreter from the script parameter begins execution of the script until the script finishes executing. When the script finishes executing, the interpreter is no longer valid.
Let's write a simple Python scripting program. All Python files will be extended with a. py extension. Copy the following source code to the test.py file.
print "Hello, Python!";
Here, suppose you have set up the Python interpreter path variable. Run the program using the following command:
$ python test.py
Output Result:
Hello, Python!
Let's try another way to execute a python script. Modify the test.py file as follows:
#!/usr/bin/pythonprint "Hello, Python!";
Here, assuming that your Python interpreter is in the/usr/bin directory, execute the script using the following command:
$ chmod +x test.py # 脚本文件添加可执行权限$./test.py
Output Result:
Hello, Python!
Python identifiers
In Python, identifiers are composed of letters, numbers, and underscores.
In Python, all identifiers can include English, numeric, and underscore (_), but cannot begin with a number.
Identifiers in Python are case-sensitive.
Identifiers that begin with an underscore are of special significance. A class attribute that begins with a single underscore (_foo) cannot be accessed directly, and is accessed through the interface provided by the class and cannot be imported with "from XXX import *";
A double underscore (__foo) represents a private member of a class; a double underscore (__foo__) represents a special method-specific identifier for Python, such as __init__ (), which represents the constructor of a class. Python reserved characters
The following list shows the reserved words in Python. These reserved words cannot be used as constants or variables, or as any other identifier name.
All Python keywords contain only lowercase letters.
and |
Exec |
Not |
Assert |
Finally |
Or |
Break |
For |
Pass |
Class |
From |
Print |
Continue |
Global |
Raise |
Def |
If |
Return |
Del |
Import |
Try |
Elif |
Inch |
While |
Else |
Is |
With |
Except |
Lambda |
Yield |
Line and indent
The biggest difference between learning Python and other languages is that Python's code block does not use curly braces ({}) to control classes, functions, and other logical judgments. Python's most distinctive feature is the use of indentation to write modules.
The amount of whitespace indented is variable, but all code block statements must contain the same amount of indentation whitespace, which must be strictly enforced. As shown below:
if True: print "True"else:
The following code will execute the error:
#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:test.py if True: print "Answer" print "True"else: print "Answer" # 没有严格缩进,在执行时保持 print "False"
Executing the above code, the following error alert will appear:
$ python test.py File "test.py", line 5 if True: ^IndentationError: unexpected indent
indentationerror:unexpected Indent error is the Python compiler is telling you "Hi, man, your file is not in the wrong format, it may be the tab and the space is not aligned", All Python is very strict in format requirements.
If the indentationerror:unindent does not match any outer indentation level error indicates that you are using an inconsistent indentation, some tab indentation, some space indentation, Change to a consistent.
Therefore, you must use the same number of indent spaces in a Python code block.
It is recommended that you use a single tab or two spaces or four spaces at each indent level, remembering that you cannot mix multiple lines of statements
A new line is generally used as the Terminator for a statement in a Python statement.
But we can use a slash (\) to divide a line of statements into multiple lines of display, as follows:
total = item_one + \ item_two + item_three
The statement contains [], {}, or () parentheses do not need to use a multiline connector. The following example:
days = [‘Monday‘, ‘Tuesday‘, ‘Wednesday‘, ‘Thursday‘, ‘Friday‘]
Python Quotes
Python uses single quotation marks ('), double quotation marks ("), three quotation marks (" ' "" ") to represent strings, and the opening and closing of quotation marks must be of the same type.
Where three quotation marks can be composed of multiple lines, writing the shortcut syntax of multiple lines of text, common language file strings, at a specific location of the file, as a comment.
word = ‘word‘sentence = "这是一个句子"paragraph = """这是一个段落包含了多个语句"""
Python comments
A single-line comment in Python starts with #.
#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:test.py# 第一个注释print "Hello, Python!"; # 第二个注释
Output Result:
Hello, Python!
Annotations can be at the end of a statement or an expression line:
name = "Madisetti" # 这是一个注释
A multiline comment in Python uses three single quotation marks ("') or three double quotation marks (" ").
#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:test.py‘‘‘这是多行注释,使用单引号。这是多行注释,使用单引号。这是多行注释,使用单引号。‘‘‘"""这是多行注释,使用双引号。这是多行注释,使用双引号。这是多行注释,使用双引号。"""
Python Empty Line
A blank line separates between functions or methods of a class, representing the beginning of a new piece of code. The class and function entries are also separated by a line of blank lines to highlight the beginning of the function entry.
Blank lines are different from code indentation, and empty lines are not part of the Python syntax. When you write without inserting a blank line, the Python interpreter runs without errors. However, the purpose of a blank line is to separate the code of two different functions or meanings, which facilitates the maintenance or refactoring of future code.
Remember: Blank lines are also part of your program code. Wait for user input
The following program will wait for user input after hitting enter:
#!/usr/bin/pythonraw_input("\n\nPress the enter key to exit.")
In the above code, "\ n" will output two new blank lines before the result output. Once the user presses the key, the program exits. Show multiple statements on the same line
#!/usr/bin/pythonimport sys; x = ‘w3cschool‘; sys.stdout.write(x + ‘\n‘)
Execute the above code and enter the result:
$ python test.pyw3cschool
Multiple statements form a code group
Indenting the same set of statements constitutes a block of code, which we call the code group.
Compound statements such as if, while, Def, and class, the first line begins with a keyword, ends with a colon (:), and one or more lines of code after that line form the code group.
We refer to the first line and the following code group as a clause (clause).
The following example:
if expression : suite elif expression : suite else :
Command-line arguments
Many programs can perform some operations to see some basic information, and Python can use the-H parameter to view the 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
Python Basic Syntax