Basic grammar of python

Python syntax features

note

single line comment

Use '#' as a comment symbol in python, starting from the line '#', this line is the content of the comment, and is ignored by the python compiler, that is, it is not executed

# 这是注释的内容
# 注释可以出现在行开头,或代码之后,下面这种情况不行
a = 5
print(#a)
# "#' 不能在字符串里面,字符串中的"#"号就是"#"号
print('#12')
# 结果 #12

multiline comment

To use multi-line comments in a Python program, you can use a pair of consecutive three quotation marks (both single and double quotation marks in English)

# 单引号
'''
注释内容1
注释内容2
'''

# 双引号
"""
注释内容1
注释内容2
"""

The more comments, the better. The purpose of writing comments is to understand the code, improve the maintainability and readability of the code. After all, after a few months, it is normal for your own code to not understand. So be sure to write a good note! ! ! It is convenient for you, me and him.

File Encoding Declaration Comments

In python3, utf-8 encoding is used by default. This encoding supports most languages ​​in the world, and also supports Chinese. If you don't want to use the default encoding, you need to declare the encoding of the file in the first line of the file.
The syntax is as follows

# -*- coding:编码 -*- 

# 下面的两种也可以
# coding=编码
# coding:编码

# 编码注释要带 # 号

code indentation

In python, code indentation and colon ':' are used to distinguish the levels between codes.
Indentation can be achieved with spaces or Tab keys. Generally, 4 spaces are used as an indentation amount. When using the Tab key, a Tab key is used as an indentation amount. Generally, a Tab key == 4 spaces, It is recommended to use 4 spaces as an indentation amount here, because the code specification recommends using 4 spaces, do not use tab keys, and do not mix tab keys and spaces.

In function definitions, flow control statements, etc., the colon at the end of the line and the indentation of the next line indicate the beginning of a code block, and the end of the indentation indicates the end of the code block.

# 函数
def run():
	pass

# 流程控制
a = 5
if a < 2:
	pass

Coding Standards

PEP8 is used as the coding specification in python, so I won’t say much here, you can check it directly on the official website
URL: https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/

Coding standards are very important! ! !
1. It is convenient for you to troubleshoot errors
2. It is convenient for you to read the code
3. It is conducive to teamwork
4. The code is beautiful and ornamental

Good coding habits are inseparable from a lot of practice. You can't just rely on words, dare to think, dare to do, and dare to practice.
You can try typing these two lines of code to see

import this
print(this)

Basic output and input

output

Use the built-in function print() in python to output to the console, the syntax of print() is as follows

print(*objects, sep=' ', end='\n', file=None)

'''
*objects: 表示要输出的一个或多个参数,将多个输出值作为参数时,用逗号 “,” 将各个值分隔开即可。‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬
如 print('a','2','s')

sep=' ':用于分隔多个输出之间的分隔符,默认用空格分隔输出的多个参数。‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬
print('a','2','s',sep='|')
结果 a|2|s

end='\n':输出语句的结束符号,默认每个输出语句结束时都用换行符 '\n' 结尾,使光标换到下一行。
print()输出完就会换行

# file:可以指定文件名保存要打印的数据。
'''

Sometimes the content we want to output is very long and it is inconvenient to read, we can use the continuation character " \ "

print('adfafa\
adfafasdf')
# 结果 adfafaadfafasdf 
# 字符都同在一行

# 我们可以用三个连续的英文引号(单双都行)来换行输出内容
print('''adfafa
adfafasdf
adaf''')
# 结果
# adfafa
# adfafasdf
# adaf


Sometimes we encounter the need to output single and double English quotation marks, so what should we do at this time?
The inside and outside are the opposite, output as usual, what do you say? If the outermost is a single quote, then the inner must be a double quote, and vice versa, as follows

print('"adaf"')
print("'asas'")
# 结果
# "adaf"
# 'asas'

# 也可以用三个连续的英文引
print('''"adaf"''')
# 结果
# "adaf"

enter

In python, use the built-in function input() to receive user input. The syntax of input() is as follows

tip = input('提示语')
# 记住无论输入什么内容,默认是字符串类型,如果你想要接收别的数据类型就要转换,比如数字
tip = int(input('提示语')) # 转化为整数类型

Reserved Words and Identifiers

reserved word

Reserved words are words that have been endowed with specific meanings in the python language. When writing code, you must not use these reserved words as names of variables, functions, classes, etc., or an error will be reported. The reserved words in the python language are as follows

and as assert break class continue
def of the elif else except finally
for from False global if import
in is lambda nonlocal not None
or pass raise return try True
while with yield

Python reserved words are case-sensitive, for example, if is a reserved word, but if is not

You can also view it through these two lines of code

import keyword
print(keyword.kwlist)
# 结果如下
# ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']

identifier

An identifier can simply be understood as a name, such as the name of a variable, function, class, module, or other object.
The python identifier naming rules are as follows
1. It consists of letters, numbers and underscore "_". The first letter cannot be a number! ! !

# 合法命名
data
date2
age_max

2. Python reserved words cannot be used.

# 错误命名
as
in

3. Identifiers in python cannot contain special characters, such as spaces, @, %, etc. 4. The letters of identifiers in python are two identical words that are
case-sensitive . If the upper and lower case formats are different, then the represented
have completely different meanings, such as

age = 10  # 小写
Age = 20  # 首字母大写
AGE = 30  # 全部大写

Note: Although python allows the use of Chinese characters as identifiers, it is not recommended to use them.

我的年纪 = 18

print(我的年纪)

# 结果
# 18


variable

What is a variable? For example, we assign "life is short, I learn python" to name, then name is the variable name, and "life is short, I learn python" is the value, we can call its value through name, in python, the variable is Used to store data, call data through variables. After the variable is defined, it can be called.

# 定义变量
name = '人生苦短,我学python'
# 通过变量名调用
print(name)
# '人生苦短,我学python'

# 我们可以多次赋值,以最后的一个值为标准
name = 'python123'
print(name)
# 'python123'

The naming rules of variables and identifiers are similar.
The naming rules of variables

  1. The first character cannot be a number
  2. Variable names are alphanumeric and underscore
  3. Reserved words (keywords) cannot be used as variable names
  4. Cannot contain special characters, such as @, ¥, %, etc.
# 错误变量名
@name = 1 # (特殊字符)
12python = 1 # (数字开头)
if = 1 # (保留字)

# 正确变量名
name = 1
student = '小明'
come = 1

Here is a reminder that the variable name must be in line with the context, so that others can understand what the variable does at a glance, otherwise it will be painful for others to maintain, and it will be painful to maintain it yourself.

basic data type

A variety of data types can be stored in python, such as the number type for age, the string type for name, etc. The basic data types are described in detail below.

number type

Number types can be roughly divided into three types: integer, floating point, and complex.

  • Integers
    Integers have no fractional part, including positive integers, negative integers, and zero. In python we can use the built-in function type() to check the data type.
num = 12
print(type(num))
# <class 'int'>

  • Floating point
    numbers Floating point numbers are numbers with a fractional part
num = 12.5
print(type(num))
# <class 'float'>

Explain the following situation here

num = 0.1+0.2
print(num)
# 0.30000000000000004

This is because the computer calculates the value not directly adding the two numbers as we think, but first converts the two numbers into binary addition, and then converts them into decimal, so this happens, you can If you want to get 0.3, you can keep one decimal place.

  • The complex number
    in python is the same as the complex number in mathematics. It consists of real part + imaginary part, and the imaginary part is represented by j or J. For example, the real part is 5 and the imaginary part is 6j, then the complex number is 5+6j , plurals are rarely used, and everyone can understand them.

string type

Strings are the most commonly used data type in Python. We can use quotes to create strings, even triple quotes. Strings are immutable sequences, which will be introduced in detail in future articles.

name = 'come on' # 单引号
name1 = "加油" # 双引号
name2 = '''me''' # 三对单引号
name3 = """wo""" # 三对双引号
print(type(name),type(name1),type(name2),type(name3))
# <class 'str'> <class 'str'> <class 'str'> <class 'str'>

In python, "\" is often used to escape some special characters. The following are commonly used escape characters.
insert image description here

Boolean type

The Boolean type is mainly used to represent the true and false of the value. In python, False and True represent Boolean values, which are false and true respectively. In addition, Boolean values ​​can be converted into numerical values. False represents the value 0, True represents the value 1, and numerical operations can also be performed , such as False + 1 is equal to 1, it is generally not recommended to use Boolean values ​​for operations.

# 在数字类型中除了零以外布尔值都是True
print(bool(1))  # True
print(bool(-1))  # True
print(bool(0))  # False

# 在字符串类型中除了空字符以外布尔值都是True
print(bool('a'))  # True
print(bool(''))  # False


data type conversion

insert image description here
Integers and floating-point numbers must be converted into strings, but strings may not be converted into integers and floating-point numbers.

num = 123
print(type(num)) # <class 'int'>

print(type(str(num))) # <class 'str'>

string = 'a'
print(type(string)) # <class 'str'>

print(type(int(string))) # 会报错


operator

Operators are special symbols that are mainly used for mathematical calculations, comparisons, and logical operations.

arithmetic operator

Arithmetic operators are used for mathematical calculations.
insert image description here

assignment operator

insert image description here

comparison operator

insert image description here

Logical Operators

insert image description here

Summarize

This article mainly talks about some basic python syntax, including comments, indentation, code specifications and basic input and output. Then it introduces the definition and usage rules of reserved words, identifiers and variables in python. Then talk about the data types in python in detail, integer type, string type, Boolean type. Finally, the usage of operators in python is introduced. This article is about the basic content of python, which needs to be mastered by everyone to lay a solid foundation for future python learning.
Finally, if there is an error in the article, please correct me, and finally thank you everyone!

Guess you like

Origin blog.csdn.net/qq_65898266/article/details/125044395