【Python】Python Basic Grammar

【Python】Python Basic Grammar

Procrastinating, why refuse something that can make work convenient and efficient, and make a record—【Su Xiaomu】

1. Experimental environment

By default, Python 3 source files are encoded in UTF-8 , and all strings are unicode strings.

Specify other encodings for source files:

# -*- coding: cp-1252 -*-
# 允许在源文件中使用 Windows-1252 字符集中的字符编码,对应适合语言为保加利亚语、白俄罗斯语、马其顿语、俄语、塞尔维亚语。
system Version
Windows 11 Pro for Workstations 22H2(22621.2134);
VS Code 1.81.0;
Python3 3.11.4;

1. Identifier

  • The first character must be a letter of the alphabet or an underscore _ . Identifiers are case sensitive .
  • The rest of the identifier consists of letters, numbers, and underscores.

In Python 3, Chinese, non-ASCII identifiers are allowed as variable names .

2. Python reserved words (keywords: cannot be used as any identifier name)

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

3. Notes

Single-line comments start with # .

Multi-line comments can be represented by multiple # signs respectively, or by paired inclusion of ''' and """ .

1) The function of the first line of the script [#!]: specify the parser to execute the script (note: it must be specified on the first line to take effect)

[#! Only applicable to /Linux/Unix users, Windows users do not need to add this line, adding this line will help the portability of script programs]

Usage 1 [#!/usr/bin/python3 (without spaces)] :

#!/usr/bin/python3

/usr/bin/python3 is the default installation path of the python3 interpreter under Linux/Unix users, and the first line is prefixed with #! to specify that Linux/Unix users use the interpreter under this path to execute this script . Paths are different in different systems. If there is another interpreter that interprets python code, you can also replace the path where it is located.

After adding, Linux/Unix users can directly use ./ to execute Python scripts, otherwise an error will occur because the Python parser cannot be found.

Usage 2 [recommended this way of writing] :

#!/usr/bin/env python3

This usage is to prevent Linux/Unix operating system users from not installing python in the default /usr/bin path. When the system sees this line, it will first search for the installation path of python3 in the env settings, and then call the interpreter program under the corresponding path to complete the operation. (This way of writing is recommended to enhance the portability of the code)

Windows parser path:

For example, under Windows, using python3 installed in the Microsoft App Store, the default parser path is:

C:/Users/[电脑用户名]/AppData/Local/Microsoft/WindowsApps/python3.11.exe

We can also use VS Code to execute the program to display.

insert image description here

#!/usr/bin/env python3
# 第1个注释
# 第2个注释

'''
第3个注释
第4个注释
'''
"""
第5个注释
第6个注释
"""
print ("蘇小沐, Python从入门到入土!")

4. Lines and indentation

The most distinctive feature of python is to use indentation to represent code blocks, without using curly braces {} .

The number of indented spaces is variable, but statements in the same code block must contain the same number of indented spaces.

1) Multi-line statement

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

total = item_one + \
        item_two + \
        item_three

Multi-line statements in [], {}, or () do not need to use backslash \, for example:

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

2) Empty line [belongs to a part of the program code]

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. No blank lines are inserted when writing, and the Python interpreter will run without error. 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.

3) Waiting for user input【\n\n】

Execute the following program and wait for user input after pressing the Enter key:

#!/usr/bin/env python3  
input("\n\n按下 enter 键后退出。")

In the above code, \n\n will output two new blank lines before the output of the result. Once the user presses the enter key, the program will exit.

4) Display multiple statements on the same line【;】

Python can use multiple statements on the same line, separated by English semicolons;

#!/usr/bin/env python3  
import sys; x = 'runoob'; sys.stdout.write(x + '\n')

Using the script to execute the above code, the output is:

runoob

insert image description here

Execute using the interactive command line, the output is:

runoob
7

Here 7 means the number of characters, runoob has 6 characters, \n means one character, adding up to 7 characters.

>>>import sys; sys.stdout.write(" hi ")    # hi 前后各有 1 个空格

insert image description here

5) 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).

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

5. Number type

There are four types of numbers in python: integers, booleans, floating point numbers, and complex numbers.

number type illustrate
int (integer) Such as 1, there is only one integer type int, expressed as a long integer, there is no Long in python2.
bool _ Such as True.
float (floating point number) Such as 1.23, 3E-2.
complex (plural) Such as 1 + 2j, 1.1 + 2.2j.

6. String (String)

The symbols are English symbols.

string illustrate
' or" Single quotes ' and double quotes " are used exactly the same in Python.
''' or""" Use triple quotes (''' or """) to specify a multi-line string.
\ Escape character to implement multi-line statements.
r r refers to raw, that is, raw string. Use r to make the backslash unescaped. For example, if r "this is a line with \n" , \n will be displayed instead of a newline.
[], {}, or() For multi-line statements within [], {}, or (), no backslash \ is required.
  • Concatenate strings literally, such as "this " "is " "string" will be automatically converted to this is string .
  • Strings can be concatenated with the + operator and repeated with the ***** operator.

1) Index method [starts from 0]

Strings in Python have two indexing methods, starting with 0 from left to right, and starting with -1 from right to left .

  • Strings in Python cannot be changed.
  • Python does not have a separate character type, a character is a string of length 1 .
  • The grammatical format of string interception is as follows: variable [head subscript: tail subscript: step size]
word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,
可以由多行组成"""
#!/usr/bin/env python3
 
str='123456789'
 
print(str)                 # 输出字符串
print(str[0:-1])           # 输出第一个到倒数第二个的所有字符
print(str[0])              # 输出字符串第一个字符
print(str[2:5])            # 输出从第三个开始到第六个的字符(不包含)
print(str[2:])             # 输出从第三个开始后的所有字符
print(str[1:5:2])          # 输出从第二个开始到第五个且每隔一个的字符(步长为2)
print(str * 2)             # 输出字符串两次
print(str + '你好')        # 连接字符串
print('------------------------------')
print('hello\nrunoob')     # 使用反斜杠(\)+n转义特殊字符
print(r'hello\nrunoob')    # 在字符串前面添加一个 r,表示原始字符串,不会发生转义

result

Order Remark output result
print(str) # output string 123456789
print(str[0:-1]) # Output all characters from the first to the second last 12345678
print(str[0]) # output the first character of the string 1
print(str[2:5]) #Output the characters from the third to the fifth 345
print(str[2:]) # Output all characters starting from the third 3456789
print(str[1:5:2]) #Output every other character from the second to the fifth (step size is 2) 24
print(str * 2) # output the string twice 123456789123456789
print(str + 'Hello') # connection string 123456789 hello
print(‘------------------------------’) # Output characters ------------------------------ ------------------------------
print(‘hello\nYYDS’) # Use backslash ()+n to escape special characters hello
YYDS
print(r’hello\nYYDS’) # Add an r in front of the string to indicate the original string, no escaping will occur hello\nYYDS

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-NMcFtKWC-1691640393190)(image-20230809220101958.png)]

insert image description here

7. print output

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

#!/usr/bin/env python3
 
x="a"
y="b"
# 换行输出
print( x )
print( y )
 
print('---------')
# 不换行输出
print( x, end=" " )
print( y, end=" " )
print()

Results of the:

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

insert image description here

8. import and from...import

Use import or from...import in python to import the corresponding module.

grammatical format illustrate
import somemodule Import the entire module (somemodule)
from somemodule import somefunction Import a function from a module
from somemodule import firstfunc, secondfunc, thirdfunc Import multiple functions from a module
from somemodule import Import all functions in a module

1) Import the sys module

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

2) 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

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

Summarize

This article is just a record of learning from the [Cainiao Tutorial] website. The Cainiao Tutorial records are very detailed. Self-study/research information is highly recommended!
The writing is one-sided, and it is purely a record. If there are any mistakes or omissions, please correct me.

References

Python3 Basic Grammar | Rookie Tutorial (runoob.com)

name time
Start editing date August 9, 2023
last edit date August 10, 2023

Guess you like

Origin blog.csdn.net/NDASH/article/details/132206720