Basic Python syntax
Basic Python syntax
Python has many similarities with 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.
The first Python program Interactive Programming
You do not need to create a script file for interactive programming. You can use the interaction mode of the Python interpreter to write code.
In linux, you only need to enter the Python command in the command line to start interactive programming. The Prompt window is as follows:
$ pythonPython 2.7.6 (default, Sep 9 2014, 15:04:36) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwinType "help", "copyright", "credits" or "license" for more information.>>>
Windows has installed the default Interactive Programming client when installing Python. The Prompt Window is as follows:
Enter the following text in the python prompt and press Enter to view the running effect:
>>> print "Hello, Python!";
In Python 2.7.6, the above example output is as follows:
Hello, Python!
If you are running a new version of Python, you need to use parentheses in the print statement, for example:
>>> print ("Hello, Python!");
Script-based programming
Call the interpreter through the script parameters to start executing the script until the script execution is complete. After the script is executed, 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 to the test. py file.
print "Hello, Python!";
Assume that you have set the PATH variable of the Python interpreter. Run the program using the following command:
$ python test.py
Output result:
Hello, Python!
Let's try another way to execute the Python script. Modify the test. py file as follows:
#!/usr/bin/pythonprint "Hello, Python!";
Here, assume that your Python interpreter is in the/usr/bin directory and run the script using the following command:
$ Chmod + x test. py # Add executable permissions to the script file $./test. py
Output result:
Hello, Python!
Python identifier
In python, identifiers consist of letters, numbers, and underscores.
In python, all identifiers can contain English letters, numbers, and underscores (_), but cannot start with a number.
The identifiers in python are case sensitive.
The identifier starting with the following line is of special significance. A class attribute that starts with a single underscore (_ foo) represents a class attribute that cannot be accessed directly. The class must be accessed through the interface provided by the class, and cannot be imported using "from xxx import;
(_ Foo) starting with a double underline represents a private member of the class; (_ foo _) Starting with and ending with a double underline represents a special identifier for special methods in python, for example, _ init _ () indicates the constructor of the class.
Python reserved characters
The following list shows reserved words in Python. These reserved words cannot be used as constants, variables, or any other identifier names.
All Python keywords only contain lowercase letters.
And |
Exec |
Not |
Assert |
Finally |
Or |
Break |
For |
Pass |
Class |
From |
Print |
Continue |
Global |
Raise |
Def |
If |
Return |
Del |
Import |
Try |
Elif |
In |
While |
Else |
Is |
With |
Except |
Lambda |
Yield |
Line and indent
The biggest difference between learning Python and other languages is that the Python code block does not use braces ({}) to control classes, functions, and other logical judgments. Python uses indentation to write modules.
The number of white spaces for indentation is variable, but all code block statements must contain the same number of white spaces for indentation, which must be strictly executed. As follows:
if True: print "True"else: print "False"
The following code will cause an error:
#! /Usr/bin/python #-*-coding: UTF-8-*-# file name: test. py if True: print "Answer" print "True" else: print "Answer" # no strict indentation, print "False" during execution"
$ python test.py File "test.py", line 5 if True: ^IndentationError: unexpected indent
IndentationError: unexpected indentThe error is that the python compiler is telling you, "Hi, dude, the format in your file is incorrect. It may be that tabs and spaces are not aligned." All python have strict format requirements.
If yesIndentationError: unindent does not match any outer indentation levelThe error indicates that the indentation method you use is inconsistent, some are tab key indentation, some are space indentation, and change to consistent.
Therefore, you must use the same number of lines in the Python code block to indent the number of spaces at the beginning.
We recommend that you use a single tab or two spaces or four spaces at each indentation level. Remember not to mix them.
Multi-line statements
In a Python statement, a new line is generally used as the statement Terminator.
However, you can use a slash (\) to split a line of statements into multiple lines for display, as shown below:
total = item_one + \ item_two + \ item_three
If the statement contains [], {}, or () brackets, you do not need to use multiline connectors. Example:
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
Python quotation marks
Python receives single quotation marks ('), double quotation marks ("), and three quotation marks ('''") to indicate strings. the start and end of quotation marks must be of the same type.
The three quotation marks can be composed of multiple lines. They can be used to compile the quick syntax for multiple lines of text. common syntax document strings are used as comments in specific locations of files.
Word = 'word' sentence = "this is a sentence. "Paragraph =" is a paragraph. Contains multiple statements """
Python Annotation
In python, single-line annotations start.
#! /Usr/bin/python #-*-coding: UTF-8-*-# file name: test. py # The first comment print "Hello, Python! "; # Second comment
Output result:
Hello, Python!
The comment can be at the end of a statement or expression line:
Name = "Madisetti" # This is a comment
In python, multiple line comments use three single quotes (''') or three single quotes (""").
#! /Usr/bin/python #-*-coding: UTF-8-*-# file name: test. py ''' this is a multiline comment that uses single quotes. This is a multi-line comment, using single quotes. This is a multi-line comment, using single quotes. ''' "Is a multi-line comment with double quotation marks. This is a multi-line comment with double quotation marks. This is a multi-line comment with double quotation marks. """
Empty Python lines
Functions or methods of classes are separated by blank lines, indicating the beginning of a new code. The class and function entry are also separated by a blank line to highlight the beginning of the function entry.
Unlike code indentation, empty lines are not part of Python syntax. No blank lines are inserted during writing, and the Python interpreter runs without errors. However, empty lines are used to separate two sections of code with different functions or meanings to facilitate code maintenance or reconstruction in the future.
Remember: Empty lines are part of the program code.
Waiting for user input
The following program waits for user input after pressing the Enter key:
#!/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 is output. Once you press the key, the program will exit.
Multiple statements can be displayed in the same line. You can use multiple statements in the same line and use semicolons (;) to separate the statements. The following is a simple example:
import sys; x = 'foo'; sys.stdout.write(x + '\n')
Multiple statements form a code group
A group of statements with the same indentation constitute a code block, which we call a code group.
For a composite statement such as if, while, def, and class, the first line starts with a keyword and ends with a colon (:). One or more lines of code after the row form a code group.
We call the first line and the subsequent code group a clause ).
Example:
if expression : suite elif expression : suite else : suite
Command Line Parameters
Many programs can execute some operations to view some basic information. Python can use the-h parameter to view the help information of 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. ]