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 so that you can quickly learn Python programming.
The first Python program
Interactive programming
Interactive programming does not require the creation of script files. Code is written through the interactive mode of the Python interpreter.
On Linux, you only need to enter the Python command on 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.
>>>
The default interactive programming client has been installed on Window when installing Python. The prompt window is as follows:
Enter the following text information in the python prompt, and then press the Enter key to see the running effect:
>> > print "Hello, Python!";
In Python 2.7.6 version, the output result of the above example is as follows:
Scripted Programming
Call the interpreter through script parameters to start executing the script until the script is executed. When the script execution is complete, the interpreter is no longer available.
Let us write a simple Python script program. All Python files will have a .py extension. Copy the following source code to the test.py file.
Here, it is assumed that you have set the Python interpreter PATH variable. Run the program using the following command:
Output result:
Let's try another way to execute the Python script. Modify the test.py file as follows:
#!/usr/bin/python
print "Hello, Python!";
Here, assuming that your Python interpreter is in the /usr/bin directory, use the following command to execute the script:
$ chmod +x test.py # Add executable permissions to the script file
$. /test.py
Output result:
Python identifier
In Python, identifiers are composed of letters, numbers, and underscores.
In python, all identifiers can include English, numbers, and underscores (_), but cannot start with numbers.
Identifiers in Python are case-sensitive.
Identifiers starting with an underscore have special meaning. Class attributes starting with a single underscore (_foo) represent class attributes that cannot be accessed directly. They need to be accessed through the interface provided by the class and cannot be imported using "from xxx import *";
Start with a double underscore (__foo) Represents the private members of the class; (__foo__) starting and ending with double underscores represents the identification of special methods in python, such as __init__() representing the constructor of the class.
Python reserved characters
The following list shows the reserved words in Python. These reserved words cannot be used as constants or variables, or any other identifier names.
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 | in | while |
else | is | with |
except | lambda | yield |
Line and indentation
The biggest difference between learning Python and other languages is that Python code blocks do not use curly brackets ({}) 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 indented whitespace is variable, but all code block statements must contain the same number of indented whitespace, and this must be strictly enforced. As shown below:
if True:
print "True"
else:
print "False"
The following code will execute incorrectly :
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# File name: test.py
if True:
print "Answer"
print "True"
else:
print "Answer"
# No strict indentation, maintain
during execution print "False"
When you execute the above code, the following error reminder will appear:
$ python test.py
File "test.py", line 5
if True:
^
IndentationError: unexpected indent
IndentationError: unexpected indent The error is that the python compiler is telling you "Hi, man, the format in your file is wrong. , it may be a problem of misalignment of tabs and spaces." All Python has very strict format requirements.
If IndentationError: unindent does not match any outer indentation levelThe error indicates that the indentation methods you use are inconsistent, some are tab key indentation, and some are space indentation, change it to consistent Can.
Therefore, the same number of leading spaces must be used in Python code blocks.
It is recommended that you use a single tab character or two spaces or four spaces at each indentation level. Remember not to mix them
Multi-line statements
In Python statements, a new line is generally used as the terminator of the statement.
But we can use slashes (\) to divide one line of statements into multiple lines for display, as shown below:
total = item_one + \
item_two + \
item_three
If the statement contains [], {} or () brackets, there is no need to use multi-line connectors. The following example:
total = item_one + \
item_two + \
item_three
Python quotation marks
Python accepts single quotation marks (' ), double quotation marks (" ), and triple quotation marks (''' """) to represent strings. The beginning and end of the quotation marks are necessary Same type.
Three quotation marks can be composed of multiple lines, which is a shortcut syntax for writing multi-line text. Commonly used document strings are used as comments at specific locations in the file.
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph.
Contains multiple sentences"""
Python comments
Single-line comments in python start with #.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# File name: test.py
# One comment
print "Hello, Python!"; # The second comment
Output result:
Comments can be at the end of a statement or expression line:
name = "Madisetti" # This is a comment
Multi-line comments in python use three single quotes (''') or three double quotes (""").
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# File name: test.py
'''
This is a multi-line comment, use single quotes.
This is a multi-line comment, use single quotes.
This. This is a multi-line comment, use single quotes.
'''
"""
This is a multi-line comment, use double quotes.
This is a multi-line comment, use double quotes.
This is a multi-line comment, use double quotes.
"""
Python Blank Line
Use a blank line to separate functions or class methods to indicate the beginning of a new piece of code. Classes and Function entries are also separated by a blank line to highlight the beginning of the function entry.
Blank lines are different from code indentation. Blank lines are not inserted when writing, Python explains. There will be no error when running the program. However, the function of a blank line is to separate two pieces of code with different functions or meanings to facilitate future code maintenance or reconstruction.
Remember: blank lines are also part of the program code #.
##Waiting for user inputThe following program will wait for user input after pressing the Enter key: #!/usr/bin/python
raw_input("\n\nPress the enter key to exit.")
In the above code, "\n\n" will output two new blank lines before the result is output. Once the user presses the key, the program will exit.
Display multiple statements on the same 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 = 'php'; sys.stdout.write(x + '\n')
Execute the above code, the input result is:
Multiple statements constitute the 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 (:). The one or more lines of code after this line constitute a code group.
We call the first line and the following code group a clause.
The following examples:
if expression :
suite
elif expression :
suite
else :
suite
Command line parameters
Many programs can perform some operations to view some 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 we execute Python in script form, we can receive parameters input from the command line. For specific usage, please refer to Python command line parameters.