Python 1-02 basic syntax

One, Python3 interpreter

1. Python interactive mode

Command line mode

Select "Command Prompt" in the Windows Start menu to enter the command line mode.

Interactive mode

When typing python or py in command line mode and executing instructions, the interpreter is running in interactive mode. The main prompt defaults to three greater than signs (>>>); when entering lines continuously, a secondary prompt appears, and the default is three dots (...).

Multi-line instructions need to be entered in multiple consecutive lines. For example, take if as an example:
Insert picture description here
enter exit() in the Python interactive mode and press Enter to exit the Python interactive mode and return to the command line mode. (Shortcut: Ctrl+z)

Scripted programming

In the command line mode, you can also execute python hello.py to run a .py file.
Executing a .py file can only be executed in command line mode. If you type a command python lx.py, you see the following error: The Insert picture description here
error prompt No such file or directory means that this lx.py cannot be found in the current directory, you must first switch the current directory to the directory where lx.py is located, to be normal carried out.
In addition, there is a difference between running .py files in command line mode and running Python code directly in the Python interactive environment. The Python interactive environment will automatically print the results of each line of Python code, but it will not be possible to run the Python code directly.
If you want to output the result, you must print it out with print().
The code in the Python interactive mode is to input one line and execute one line, while running the .py file directly in the command line mode executes all the codes in the file at once. The Python interactive mode is mainly for debugging Python code.
Note, do not use the Notepad that comes with Windows. What Word saves is not a plain text file, but Notepad will add a few special characters (UTF-8 BOM) at the beginning of the file smartly, which will cause inexplicable errors when the program runs.

Two, Python3 basic syntax

1. Coding

By default, Python 3 source code files are encoded in UTF-8, and all strings are unicode strings. Of course, you can also specify a different encoding for the source file:

# -*- coding: GB2312 -*-

2. Identifier

• The first character must be a letter or an underscore _ in the alphabet;
• The other parts of the identifier consist of letters, numbers and underscores;
• The identifier is case sensitive.

In Python 3, Chinese can be used as variable names, and non-ASCII identifiers are also allowed.

3. Python reserved words

Reserved words are keywords, and we cannot use them as any identifier names. Python's standard library provides a keyword module that can output all keywords of the current version:

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

4. Notes

Make sure to use the correct style for modules, functions, methods, and inline comments. Comments in
Python include single-line comments and multi-line comments:
Single-line comments in Python start with #, for example:

# 这是一个注释 
print("Hello, World!") 

For multi-line comments, use three single quotation marks''' or three double quotation marks """ to enclose the comment, for example:
1) Single quotation mark (''')

'''
这是多行注释,用三个单引号 
这是多行注释,用三个单引号 
这是多行注释,用三个单引号 
''' 
print("Hello, World!")

2) Double quotes (""")

""" 
这是多行注释,用三个双引号 
这是多行注释,用三个双引号 
这是多行注释,用三个双引号 
""" 
print("Hello, World!")

5. Statements and indentation

The most distinctive feature of Python is the use of indentation to represent code blocks, without the need to use curly braces {}.
The number of indented spaces is variable, but statements in the same code block must contain the same number of indented spaces.
Instance

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

The number of spaces in the indentation number of the last line of the following code is inconsistent, which will cause a runtime error:

if True:
    print ("Answer")
    print ("True")
else:
    print ("Answer")
  print ("False")    # 缩进不一致,会导致运行错误

Due to the inconsistency of the above program, an error similar to the following will appear after execution:

 File "test.py", line 6
    print ("False")    # 缩进不一致,会导致运行错误
IndentationError: unindent does not match any outer indentation level

6, multi-line statements

Python usually writes a statement in one line, but if the statement is very long, we can use backslash () to implement a multi-line statement, for example:

total = item_one + \
        item_two + \
        item_three

For multi-line statements in [], {}, or (), there is no need to use backslashes (), for example:

total = ['item_one', 'item_two', 'item_three',
        'item_four', 'item_five']

7, blank line

Use blank lines to separate functions or methods of a class to indicate the beginning of a new piece of code. The class and function entry 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 part of Python syntax. No blank lines are inserted when writing, and the Python interpreter runs without error. But the function of the blank line is to separate two sections of code with different functions or meanings to facilitate future code maintenance or reconstruction.

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

8. Display multiple statements on the same line

Python can use multiple statements in the same line, separated by semicolons (;), for example, the file name demo.py has the following content:

import sys; x = 'Python'; sys.stdout.write(x + '\n')

Use the script to execute the above code, enter python demo.py at the command prompt, the output result is:

Python

Use the interactive command line to execute, the output result is:

>>> import sys; x = 'Python'; sys.stdout.write(x + '\n')
Python
6

Here, 6 represents the number of characters.


9. Multiple statements form a code group

A group of statements with the same indentation constitutes 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 constitute a code group.
We call the first line and the following code group a clause.
The following example:

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

10、import 与 from…import

Use import or from...import to import the corresponding module in python.
Import the entire module (somemodule) in the format:

import somemodule

Import a function from a module, the format is:

from somemodule import somefunction

Import multiple functions from a module, the format is:

from somemodule import firstfunc, secondfunc, thirdfunc

Import all the content in a module, the format is:

from somemodule import *

Import the entire module (somemodule), add the alias as s, the format is:

import somemodule as s

Import the sys module

import sys 
print('======== Python import mode ========') 
print ('命令行参数为:') 
for i in sys.argv: 
	print (i) 
print ('\n python 路径为',sys.path)

Import the argv and path members of the sys module

from sys import argv,path  # 导入特定的成员 
print('======== python from import ========') 
print('path:',path)  # 因为已经导入path成员,所以此处引用时不需要加sys.path

demo.py

x=1 # 全局变量
def f(): # 函数
    print('This is a function.')

class A: # 类
    y=2 # 类变量
    def g(self): # 实例方法
        print('This is a method.')	

if __name__ == "__main__":
    f()	
    a=A()
    a.g()

test
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43955170/article/details/112465785