Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python basic syntax


May 10, 2021 Python2


Table of contents


Python basic syntax

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

In this chapter we'll learn the basic syntax of Python so that you can quickly learn Python programming.


Use a diagram to profile Python learning

Python basic syntax


The first Python program

Interactive programming

Interactive programming does not require the creation of script files, and 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, and the prompt window is as follows:

$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

The default interactive programming client was installed on Window when Python was installed, and the prompt window is as follows:

Python basic syntax

Enter the following text information in the Python prompt, and then press Enter to see how it works:

>>> print "Hello, Python!";

In Python 2.4.3, the above case output is as follows:

Hello, Python!

If you're running a new version of Python, you'll need to use parentheses in a print statement such as:

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

Scripted programming

Call the interpreter with script parameters to start executing the script until the script is finished. When the script is executed, the interpreter is no longer valid.

Let's write a simple Python script. A ll Python files will be .py as an extension. Copy the following source code to test.py file.

print "Hello, Python!";

Here, let's say you've set the Python interpreter PATH variable. Run the program with the following commands:

$ python test.py

Output:

Hello, Python!

Let's try another way to execute the Python script. Modify test.py file as follows:

#!/usr/bin/python
print "Hello, Python!";

Here, suppose your Python interpreter executes the script using the following command in the /usr/bin directory:

$ chmod +x test.py     # 脚本文件添加可执行权限
$./test.py

Output:

Hello, Python!

The print function of Python 3.x is used in Python2.x

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

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

Python identifier

In Python, identifiers are composed of letters, numbers, and underscores.

In Python, all identifiers can include English, numbers, and underscores, but they cannot begin with numbers.

The identifiers in Python are case sensitive.

The identifier at the beginning of the following dash is of special significance. Class properties that cannot be accessed directly by a representative of a single underscore (_foo) need to be accessed through the interface provided by the class and cannot be imported with "from xxx import";

(__foo), which begins with a double underscore, represents a private member of the class, and __foo__, which begins and ends with a double underscore, represents an identity dedicated to a special method in python, such as __init__() for the class's constructor.

Python can display multiple statements on the same line by using a sign; Separate, e.g.:

>>> print 'hello';print 'Python';
hello
Python

Python retains 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 in while
else is with
except Lambda yield

rows and indentations

The biggest difference between learning Python and other languages is that Python's blocks of code do not use braces to control classes, functions, and other logical judgments. Python's most distinctive feature is writing modules with indentations.

The amount of white space indented is variable, but all block statements must contain the same amount of indented white space, which must be strictly enforced. Here's what it looks like:

if True:
    print "True"
else:
  print "False"

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"

By executing the above code, you will be reminded of the following errors:

$ python test.py  
  File "test.py", line 5
    if True:
    ^
IndentationError: unexpected indent

IndentationError: The unexpected indent error is that the Python compiler is telling you, "Hi, man, your file is not in the right format, maybe tab and spaces are not aligned", and all Pythons are very strict about formatting.

If it's IndentationError: The unindent does not match any outer indentation level error indicates that you're using inconsistent indentation, some tab key indentation, some space indentation, and then consistent.

Therefore, the same number of line-first indented spaces must be used in Python's block of code.

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


A multi-line statement

New lines are generally used as the end character of the statement in Python statements.

But we can use the slash to divide a line of statements into multiple lines, as follows:

 total = item_one + \ 
        item_two + \
        item_three  

You don't need to use a multi-line connector if the statement contains a bracket of . or (). Here's an example:

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

Python quotation marks

Python uses single quotes ('), double quotes ('), and three quotation marks (''"")" to represent strings, and the beginning and end of quotation marks must be of the same type.

Three of these quotation marks can consist of multiple lines, write a quick syntax of multi-line text, often used for document strings, and are used as comments at specific locations in a file.

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

Python comment

A single-line comment in Python begins with a hashtag.

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

# 第一个注释
print "Hello, Python!";  # 第二个注释

Output:

Hello, Python!

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

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

Multiple lines of comments in Python use three single quotes ('') or three double quotes (''')."

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


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

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

Python empty line

The functions are separated by empty lines or between the methods of the class, indicating the beginning of a new piece of code. Classes and function entrances are also separated by a row of empty lines to highlight the beginning of the function entry.

Unlike code indentation, empty lines are not part of the Python syntax. N o empty lines are inserted when writing, and the Python interpreter does not run in error. But the purpose of empty lines is to separate two pieces of code with different functions or meanings for later code maintenance or refactoring.

Remember: empty lines are also part of the program code.


Wait for user input

After the following program is executed, it waits for user input and exits when the enter key is pressed:

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

raw_input("按下 enter 键退出,其他任意键显示...\n")

In the code above, the new line is implemented. O nce the user presses the enter key to exit, the other keys are displayed.


Multiple statements are displayed on the same line

#!/usr/bin/python
import sys; x = 'w3cschool'; sys.stdout.write(x + '\n')

To execute the above code, the input results are:

$ python test.py
w3cschool

Print output

The print default output is a line change, and if you want to implement a line not line change that requires a comma at the end of the variable,

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

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

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

# 不换行输出
print x,y

The above examples perform as follows:

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

Multiple statements make up a code group

Indent the same set of statements to form a block of code, which we call a code group.

Compound statements such as if, while, def, and class, the first line starts with a keyword and ends with a colon (:), after which one or more lines of code form a group of code.

We refer to the first line and subsequent group of code as a clause.

Here's an example:

if expression : 
   suite 
elif expression :  
   suite  
else :  
   suite 

Command-line arguments

Many programs can do something to see some basic information, and Python can use the -h parameter to view the parameter help information:

$ 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 as a script, we can receive parameters entered by the command line, using the Python command line parameters.