Chapter 2: Variables and Data Types in Python
1. Binary and character encoding
-
Bit storage content is 0 and 1; bit is the smallest storage unit in the computer
-
Data: Each symbol (English, number or symbol, etc.) will occupy a 1Bytes record, and each Chinese will occupy 2Byte
-
Binary conversion: 1B(Byte)=8b(bit) ; 1KB=1024B
-
[Online ASCII Table]( ASCII Table | Rookie Tutorial (runoob.com) )
-
Character Encoding Development
2. Identifiers and reserved words in Python
2.1 Reserved words
- what are reserved words
- There are some words that are assigned specific meanings by Python and these words should not
- View reserved words
import keyword
print(keyword.kwlist)
- what are the reserved words
['False', 'None', 'True', '__peg_parser__', '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']
2.2 Identifiers
- what is an identifier
- Variables, functions, classes, modules, and other objects are named after identifiers
- Identifier Naming Rules
- Contains only letters, numbers, underscores_
- cannot start with a number
- cannot be a reserved word
- Strictly case sensitive
3. Variables and data types in Python
3.1 Variables
-
what is a variable
-
A variable is a labeled box in memory into which you put the data you need
-
name = "Python"
-
Among them: name - variable name; = - assignment operator ; Python - value
-
-
-
components of variables
- Identification: Identify the memory address where the object is stored, use the built-in function id(obj) to obtain
- Type: Indicates the data type of the object, which can be obtained by using the built-in function type(obj)
- Value: Indicates the specific data stored in the object, and the value can be printed out by using the function print(obj)
-
Memory analysis graph
-
code analysis
- code writing
name = '巧克力酸奶' print('标识', id(name)) print('类型', type(name)) print('值', name)
- output result
标识 2830801861584 类型 <class 'str'> 值 巧克力酸奶
3.2 Multiple assignment of variables
- After multiple assignments, the variable will point to the new space
- memory diagram
-
code analysis
- code writing
name = "玛利亚" print(id(name)) name = "楚留香" print(name) print(id(name))
- Result analysis
2151611071440 楚留香 2151611071728
3.3 Data Types
- common data types
type of data | character representation | example |
---|---|---|
integer type | int | 98 |
floating point type | float | 3.1415926 |
Boolean type | bool | TRUE,False |
string type | str | "Life is too short, I use Python" |
- Use the type() function to output the data type
3.3.1 Integer types
- English is integer, abbreviated as int , which can represent positive numbers, negative numbers and zero
- Different base representations of integers
Window platform,
Win+R
after inputcalc
, can quickly dispatch the calculator
hexadecimal | base number | Every few days | Manifestations |
---|---|---|---|
decimal (default) | 0,1,2,3,4,5,6,7,8,9 | 10 | 120 |
binary | 0,1 | 2 | 0b101011 |
Octal | 0,1,2,3,4,5,6,7 | 8 | 0o166 |
hexadecimal | 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F | 16 | 0x76 |
-
code demo
- code writing
# 整数类型,正数,负数,0 n1 = 90 n2 = -90 n3 = 0 print(n1, type(n1)) print(n2, type(n2)) print(n3, type(n3)) # 正数可以表示为二进制,十进制,八进制,十六进制 print("十进制", 118) print("二进制", 0b1010111) print("八进制", 0o176) print("十六进制", 0x78A2)
- Result analysis
90 <class 'int'> -90 <class 'int'> 0 <class 'int'> 十进制 118 二进制 1010111 二进制 87 八进制 126 十六进制 30882 Process finished with exit code 0
3.3.2 Floating point type
-
English is float , and the floating point number is composed of an integer part and a decimal part
-
Floating point storage is non-deterministic
- When using floating-point numbers for calculations, there may be cases where the decimal point is uncertain
- Solution: import module decimal
-
code demo
- code writing
a = 3.14159 print(a, type(a)) # 小数点位不确定 n1 = 1.1 n2 = 2.2 n3 = 2.1 print(n1 + n2) print(n1 + n3) # 解决方案:**导入模块decimal** from decimal import Decimal print(Decimal("1.1")+Decimal("2.2"))
- Result analysis
3.14159 <class 'float'> 3.3000000000000003 3.2 3.3 Process finished with exit code 0
3.3.3 Boolean type
-
The English name boolean, abbreviated as bool , is used to represent true or false values
-
True is true , False is false
-
Boolean values can be converted to positive numbers
- True——>1
- False——>0
-
code demo
- code writing
f1 = True f2 = False print(f1, type(f1)) print(f2, type(f2)) # bool型可以转成整型运算 print(f1 + 1) print(f2 + 1)
- Result analysis
True <class 'bool'> False <class 'bool'> 2 1 Process finished with exit code 0
3.3.4 String type
-
Strings are also known as immutable sequences of characters
-
Can be defined using single quotes
' '
, double quotes" "
, triple quotes''' ''
' or""" """
-
Strings defined by single quotes and double quotes must be on one line
-
The character type defined by triple quotes can be distributed in multiple consecutive lines
-
code demo
- code writing
str1 = '人生苦短,我用Python' str2 = "人生苦短,我用Python" str3 = """人生苦短, 我用Python""" str4 = '''人生苦短, 我用Python''' print(str1, type(str1)) print(str2, type(str2)) print(str3, type(str3)) print(str4, type(str4))
- Result analysis
人生苦短,我用Python <class 'str'> 人生苦短,我用Python <class 'str'> 人生苦短, 我用Python <class 'str'> 人生苦短, 我用Python <class 'str'> Process finished with exit code 0
3.4 Data type conversion
- Why data type conversion is needed
- Needed when splicing data of different data types together
- Functions for data type conversion
Function name | effect | Precautions | example |
---|---|---|---|
str() | Convert other data types to strings | Can also be converted with quotes | str(123) 123’ |
int() | Convert other data types to integers | 1. Text and decimal strings cannot be converted into integers 2. Floating point numbers are converted into integers: erasing and rounding |
int(‘123’) |
float() | Convert other data types to floating-point numbers | 1. The text class cannot be converted into an integer 2. The integer is converted into a floating point number with a tail of .0 |
float(‘9.9’) float(9) |
- Diagram of Data Transformation
-
code demo
- code writing
name = '张三' age = 20 print(type(name), type(age)) # 说明name和age的数据类型不相同 # print('我叫'+name+'今年'+age+'岁') # TypeError: can only concatenate str (not "int") to str print('我叫' + name + ',今年' + str(age) + '岁') print('------------str():将其他类型转换成str类型--------------') a = 10 b = 198.8 c = False print(type(a), type(b), type(c)) print(str(a), str(b), str(c), type(str(a)), type(str(b)), type(str(c))) print('------------int():将其他类型转换成int类型--------------') s1 = '128' f1 = 98.1 s2 = '76.77' ff = True s3 = 'Hell0' print(type(s1), type(f1), type(s2), type(ff), type(s3)) print(int(s1), type(int(s1))) # 将str转换成int类型,字符串为 数字串 print(int(f1), type(int(f1))) # 将float转换成int类型,截取整数部分,舍掉小数部分 # print(int(s2), type(int(s2))) # ValueError: invalid literal for int() with base 10: '76.77'mm,字符串为小数串 print(int(ff), type(int(ff))) # print(int(s3), type(int(s3))) ValueError: invalid literal for int() with base 10: 'Hell0',字符串必须为整数数字串才能转换 print('------------float():将其他类型转换成float类型--------------') ss1 = '128.98' ss2 = '76' fff = True ss3 = 'Hell0' i = 98 print(type(ss1), type(ss2), type(fff), type(ss3), type(i)) print(float(ss1),type(float(ss1))) print(float(ss2),type(float(ss2))) print(float(fff),type(float(fff))) # print(float(ss3),type(float(ss3))) # ValueError: could not convert string to float: 'Hell0' print(float(i),type(float(i)))
- Result analysis
<class 'str'> <class 'int'> 我叫张三,今年20岁 ------------str():将其他类型转换成str类型-------------- <class 'int'> <class 'float'> <class 'bool'> 10 198.8 False <class 'str'> <class 'str'> <class 'str'> ------------int():将其他类型转换成int类型-------------- <class 'str'> <class 'float'> <class 'str'> <class 'bool'> <class 'str'> 128 <class 'int'> 98 <class 'int'> 1 <class 'int'> ------------float():将其他类型转换成float类型-------------- <class 'str'> <class 'str'> <class 'bool'> <class 'str'> <class 'int'> 128.98 <class 'float'> 76.0 <class 'float'> 1.0 <class 'float'> 98.0 <class 'float'> Process finished with exit code 0
4. Comments in Python
-
what is a note
- Annotated text that explains the function of the code in the code can improve the readability of the code
- The content of the comment will be ignored by the Python interpreter
-
Common Annotation Types
- Single-line comments --> start with **#** until the end of a newline
- Multi-line comment --> There is no separate multi-line comment mark, and the code between a pair of triple quotes is called a multi-line comment
- Chinese encoding statement comment --> add Chinese statement comment at the beginning of the file to specify the encoding format of the source code file
- coding:gbk
- coding:UTF-8
-
code demo
- code writing
# 输出功能(单行注释) print('hello') '''嘿嘿, 这里是多行注释 啦啦啦啦啦'''