Basic Python Tutorial - Syntax

foreword

The Python language has many similarities to languages ​​such as Perl, C, and Java. However, there are also some differences.

This time we will learn the basic syntax of Python in the future, so that you can quickly learn Python programming.

first python program

interactive programming

Interactive programming does not require the creation of script files, and codes are written through the interactive mode of the Python interpreter.

On linux, you only need to enter the Python command in the command line to start interactive programming, and 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 interactive programming client has been installed when installing Python on Windows, and the prompt window is as follows:

Enter the following text information at the python prompt, and press Enter to see the effect:

>>> print ("Hello, Python!")

In the Python 2.7.6 version, the output of the above example is as follows:

Hello,  Python!</pre>

scripting

Call the interpreter with the script parameter to start executing the script until the script finishes executing. When the script execution is complete, the interpreter is no longer active.

Let's write a simple Python script. All Python files will have a .py extension. Copy the following source code into the test.py file.

print  ("Hello, Python!")

Here, it is assumed that you have set the Python interpreter PATH variable. Run the program with 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:

example

!/usr/bin/python

print ("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!

Use the print function of Python3.x in Python2.x

If the Python2.x version wants to use the print function of Python3.x, you can import the future package, which disables the print statement of Python2.x and uses the print function of Python3.x:

example

>>> list =["a", "b", "c"]
>>> print list    # python2.x 的 print 语句
['a', 'b', 'c']
>>> from __future__ import print_function  # 导入 __future__ 包
>>> print list     # Python2.x 的 print 语句被禁用,使用报错
  File "<stdin>", line 1
    print list
             ^
SyntaxError: invalid syntax
>>> print (list)   # 使用 Python3.x 的 print 函数
['a', 'b', 'c']
>>>

Many functions designed for compatibility between Python3.x and Python2.x can be imported through the future package.

Python identifier

In Python, identifiers consist of letters, numbers, and underscores.

In Python, all identifiers can include letters, numbers, and underscores (_), but cannot start with a number.

Identifiers in Python are case sensitive.

Identifiers starting with an underscore have special meaning. _foo at the beginning of a single underscore represents class attributes that cannot be directly accessed, and must be accessed through the interface provided by the class, and cannot be imported with from xxx import *.

__foo starting with a double underscore represents a private member of the class, and foo starting and ending with a double underscore represents a special identifier for a special method in Python, such as init () representing a constructor of a class.

Python can display multiple statements on the same line by separating them with semicolons; such as:

>>>  print  ('hello');print  ('runoob'); hello
runoob

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.

line and indentation

The biggest difference between learning Python and other languages ​​is that Python code blocks do not use braces {} to control classes, functions and other logical judgments. The most distinctive feature of python is to use indentation to write modules.

The amount of indentation is variable, but all code block statements must contain the same amount of indentation, which must be strictly enforced.

The following examples are indented with four spaces:

example

if True:
    print ("True")
else:
    print ("False")

The following code will execute incorrectly:

example

#!/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 message will appear:

 File "test.py", line 11
    print ("False")
                  ^
IndentationError: unindent does not match any outer indentation level

IndentationError: unindent does not match any outer indentation level error indicates that the indentation methods you use are inconsistent, some are indented with tab keys, and some are indented with spaces, just change them to be consistent.

If it is an IndentationError: unexpected indent error, the python compiler is telling you "Hi, buddy, the format in your file is wrong, it may be a problem of misalignment of tabs and spaces", all pythons have very strict requirements on the format.

Therefore, you must use the same number of spaces for indentation at the beginning of a line in a Python code block.

It is recommended that you use a single tab or two spaces or four spaces at each indentation level , remember not to mix them

multi-line statement

In a Python statement, a newline is generally used as the terminator of the statement.

But we can use slashes (\) to divide the statements of one line into multiple lines, as shown below:

total = item_one + \
        item_two + \
        item_three

Statements containing [], {} or () brackets do not need to use multi-line connectors. Examples are as follows:

days =  ['Monday',  'Tuesday',  'Wednesday',  'Thursday',  'Friday']

Python quotes

Python can use quotation marks ( ' ), double quotation marks ( " ), triple quotation marks ( ''' or """ ) to represent strings, and the start and end of the quotation marks must be of the same type.

Among them, triple quotation marks can be composed of multiple lines, which is a shortcut syntax for writing multi-line text, which is often used in document strings, and is used as comments in specific places in the file.

word =  'word' sentence =  "这是一个句子。" paragraph =  """这是一个段落。
包含了多个语句"""

Python comments

Single-line comments in python start with #.

example

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py

first note

print ("Hello, Python!")  # 第二个注释

Output result:

Hello,  Python!

Comments can be at the end of a statement or expression line

name =  "Madisetti"  # 这是一个注释

Multi-line comments in python use three single quotes (''') or three double quotes (""").

example

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py

'''
这是多行注释,使用单引号。
这是多行注释,使用单引号。
这是多行注释,使用单引号。
'''

"""
这是多行注释,使用双引号。
这是多行注释,使用双引号。
这是多行注释,使用双引号。
"""

Python empty line

Functions or class methods are separated by a blank line, indicating the beginning of a new code. The class and function entries are also separated by a blank line to highlight the beginning of the function entry.

Blank lines are not the same as code indentation, and blank lines are not part of Python syntax. Do not insert blank lines when writing, and the Python interpreter will run without errors. But the function of the blank line is to separate two pieces of code with different functions or meanings, which is convenient for future code maintenance or refactoring.

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 after pressing the Enter key:

#!/usr/bin/python  # -*- coding: UTF-8 -*- raw_input("按下 enter 键退出,其他任意键显示...\n")

In the above code, \n implements newline. Once the user presses the enter key to exit, the other keys are displayed.

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 =  'runoob'; sys.stdout.write(x +  '\n')

Execute the above code, the input result is:

$ python test.py
runoob

print output

The default output of print is a newline. If you want to achieve no newline, you need to add a comma at the end of the variable.

example

#!/usr/bin/python
# -*- coding: UTF-8 -*-

x="a"
y="b"
# 换行输出
print x
print y

print '---------'
# 不换行输出
print x,
print y,

# 不换行输出
print x,y

The execution result of the above example is:

a
b --------- a b a b

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 like if, while, def, and class, the first line starts with a keyword and ends with a colon (:), and one or more lines of code after this line form a code group.

We refer to the first line and the following group of codes as a clause (clause).

Examples are as follows:

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 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. ] 

When we execute Python in the form of a script, we can receive parameters input from the command line. For specific usage, please refer to [Python command line parameters].

Guess you like

Origin blog.csdn.net/weixin_69333592/article/details/128326355