current position：Home>[Python from introduction to mastery] (IV) what are the builtin data types of Python? Figure out
[Python from introduction to mastery] (IV) what are the builtin data types of Python? Figure out
20220130 16:05:06 【Mainong Feige】
Hello! , I'm Manon Feige , Thank you for reading this article , Welcome to three links with one button . My life depend on myself not the fate , Today is still a day of study . This article is about 【Python From entry to mastery 】 The fourth in the series , Its main introduction Python The number in the builtin data type of
Dry cargo is full. , Recommended collection , I need to use it. I need to look at it from time to time . If you have any questions and need , Welcome to leave a message ~ ~ ~.
Preface
This article mainly introduces Python Numbers in builtin data types （Number）, Include integers （int）, decimal （float）, The plural （Complex）, Boolean type （bool） These data types . This article is all about Python3.x Data types in .
Variable
Before talking about data types , Please think about the following questions ：
 How is the data stored ？
 What is the use of data types ？
 What are the differences between various data types ？
To answer these questions , First of all, we should understand the concept of variables . So what is a variable ？ Variable （Variable） It can be regarded as a box for storing data , Each variable has a specified name , The data stored in the variable can be found through the variable name . From the bottom logic , Variable is to open up an area in computer memory , The stored data is then placed in this area . The corresponding variable is a constant （Constant）, They are all used to store data , The difference is that constants cannot be modified once the data is saved , The data saved by variables can be modified many times .
In programming language , The process of putting data into variables is called assignment （Assignment）,Python Use the equal sign in = As an assignment operator , Variable is a kind of identifier , Therefore, the naming of variables also needs to be observed Python Naming conventions for identifiers .
name=value
Copy code
there name It's the variable name , and value That is, to the data in the variable . A variable can hold only one value , When a variable is assigned a value , If assigned again, the original value will be overwritten . Take a chestnut ：
a=100
Copy code
It's about putting numbers 100 Assign a value to a variable a. After explaining the concept of variables , The first problem is solved , That's it Data is stored in memory through variables , Of course, you can also persist the data to the hard disk .
Overview of data types
After clarifying the concept of variables , Next, let's give a general introduction to Python Various builtin data types in , As shown in the mind map below , There are many types of data , This article will mainly introduce several data types belonging to numbers . The rest of the data types will be introduced in subsequent articles .
data type  effect  data format  give an example 

int（ Integers ）  Used to store integers  100  100 
float（ decimal ）  Used to store decimals  Writing must include a decimal point  100.1 
complex（ The plural ）  Used to store binary ordered real number pairs  a+bj  
bool( Boolean type )  Used to store Boolean values True perhaps False  True  
## Python It's a weak type of language  
Unlike other strongly typed programming languages （ such as Java,C Language, etc. ）,Python It's a weak type of language , It is mainly reflected in 
 When defining a variable, you do not need to specify the data type of the variable . Variables can be assigned directly without declaration , Assigning a value to a nonexistent variable is equivalent to defining a new variable .
 The data type of the variable can be changed at any time , such as , The same variable can be assigned to an integer , It will be assigned as a string .
It's still an illustration ： For example, define a variable a, And will 100 Assign to it ,Java The way of writing in is ：
int a=100
Copy code
Python The way of writing in is ：
a=100
Copy code
It can be seen that Java Variables must be declared in a Data type of int, After declaration, you can only add to the variable a Assign an integer in , You cannot assign other types of data such as strings . and Python There are no such restrictions . Weak data type does not mean no data type , This is to write without deliberately declaring data types , But there are data types inside the programming language , Can pass type() Method to view its data type .
>>> type(100)
<class 'int'>
>>> type(100.1)
<class 'float'>
>>> type(True)
<class 'bool'>
>>> type(2+10j)
<class 'complex'>
Copy code
Detailed description of each data type
Integers （int）
Python3 Integers in are of no type , That is, there is no long integer type （Long） Or short integer type （short） Points , Its value range is infinite , That is, no matter how big or small the number is ,Python Can easily deal with . Here are two maximal or minimal integers .
>>> 1000000000000000000000000000000000000000000000
1000000000000000000000000000000000000000000000
>>> print(1000000000000000000000000000000000000000000000)
1000000000000000000000000000000000000000000000
Copy code
It can be seen that no matter how large or small the number is, there will be no overflow , This illustrates the Python The ability to handle integers is very strong .
Different base numbers of integers
Python You can use a variety of hexadecimal to represent integers .
 Decimal form
We usually use decimal form for integers , It consists of 09 A total of ten numbers are arranged and combined . Be careful , Integers in decimal form cannot be expressed in 0 As the beginning , Unless the value itself is 0. 2) Binary form from 0 and 1 Two numbers make up , Write with 0b or 0B start . for example ,1001 The corresponding decimal number is 9. 3) Octal form Octal integer consists of 07 There are eight numbers in total , With 0o or 0O start . Be careful , The first symbol is a number 0, The second symbol is a capital or lowercase letter O. 4) Hexadecimal form from 09 Ten numbers and AF（ or a~f） Six letters , Write with 0x or 0X start .
# Binary system
a=0b1001
print('a=',a)
# octal
b=0o207
print('b=',b)
# Hexadecimal
c=0x45
print('c=',c)
Copy code
The result of the operation is ：
a= 9
b= 135
c= 69
Copy code
Python 3.x Underscores are allowed _ As a number （ Including integers and decimals ） The delimiter , Usually add an underscore every three numbers , such as ：click = 1_301_547
Floating point numbers / decimal （float）
In programming languages , Decimals are usually stored as floating point numbers , Floating point numbers and fixedpoint numbers are relative ; Decimal in the stored procedure, if the decimal point moves , It's called a floating point number ; If the decimal point doesn't move , It's called a fixedpoint number .
The written form of decimals
Python There are two writing forms of decimal in ：
 Decimal form
This is the decimal form we often see , such as 101.1;234.5;0.23 2. Exponential form Python The decimal point exponential form is written as ：aEn or aen
a Is the mantissa , It's a decimal ,n For the exponential part , It's a decimal ,E perhaps e Is a fixed character , Used to split the mantissa part and the exponential part , The real expression is a×10n. Take a chestnut ： 2.3E5=2.3x10 Of 5 Power Still a chestnut ：
x=10.01
print('x=',x)
y=0.031
print('y=',y)
z=2.3E10
print('z=',z)
w=0.00000001
print('w=',w)
Copy code
The result of the operation is ：
x= 10.01
y= 0.031
z= 23000000000.0
w= 1e08
Copy code
How many decimal places are reserved
In actual development, we often keep the specified mantissa after the decimal point , For example, keep two decimal places after .Python There are three ways to keep the number of digits after the decimal point
 Use the builtin round function , The syntax is ：
round([data],[num])
, among data Is the data ,num Is the number of digits reserved after the decimal point  Use float function , The syntax is ：
float('%.[num]f' % [data])
, among data Is the data ,num Is the number of digits reserved after the decimal point  Use Decimal class , The syntax is ：
Decimal([data]).quantize(Decimal('0.00'))
, among data Is the data ,'0.00' Indicates that two digits are reserved , If you keep three, it's '0.000'
a = 100.01125
print(a)
print('round After decimal point 3 position ', round(a, 3))
print('float Processing keeps the decimal point after 2 position ', float('%.2f' % a))
from decimal import Decimal
print('Decimal Processing keeps the decimal point after 4 position ', Decimal(a).quantize(Decimal('0.0000')))
Copy code
The result of the operation is ：
100.01125
round After decimal point 3 position 100.011
float Processing keeps the decimal point after 2 position 100.01
Decimal Processing keeps the decimal point after 4 position 100.0113
Copy code
The plural （complex）
The plural （complex） It is the real part （real） Deficiency part of harmony （imag） constitute , stay Python in , The imaginary part of a complex number is represented by j perhaps J As a suffix , The specific format is ：
a+bj
Copy code
among a Represents the real part ,b The empty part
c1=100+2j
print("c1 The value of is :",c1)
c2=200+3J
print('C2 The value of is :',c2)
Copy code
The result of the operation is ：
c1 The value of is (100+2j)
C2 The value of is (200+3j)
Copy code
Boolean type （bool）
Boolean types are used to represent true （ Yes ） Or false （ wrong ）, For example, the common 3>2 Comparison formula , This is right ,Python Use in True To represent the ; Another example 2>3 Comparison formula , This is wrong , use False To represent the .
print(3>2)
print(2>3)
print('True==1 The result is :',True==1)
print('False==0 The result is :',False==0)
Copy code
The result of the operation is ：
True
False
True==1 The result is : True
False==0 The result is : True
Copy code
As can be seen from the above code ,bool Type of True Value corresponds to an integer value 1, and False Value corresponds to an integer value 0.
summary
This paper mainly introduces Python Numbers in builtin data types , Content comparison basis , I hope it can help readers .
I'm Manon Feige , Thank you again for reading this article .
The whole network has the same name 【 Manon Feige 】. Short step , A thousand miles , Enjoy sharing I'm Manon Feige , Thank you again for reading this article .
copyright notice
author[Mainong Feige],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301605037505.html
The sidebar is recommended
 Python notes (6): definition and use of lists
 Python notes (V): string operation
 Python notes (IV): use of functions and modules
 Python notes (3): conditional statements and circular statements
 Python notes (II): lexical structure
 Notes on python (I): getting to know Python
 [Python data structure series]  tree and binary tree  basic knowledge  knowledge point explanation + code implementation
 [Python daily homework] Day7: how to combine two dictionaries in an expression?
 How to implement a custom list or dictionary in Python
 15 advanced Python tips for experienced programmers
guess what you like

Python string method tutorial  how to use the find() and replace() functions on Python strings

Python computer network basics

Python crawler series: crawling global airport information

Python crawler series: crawling global port information

How to calculate unique values using pandas groupby

Application of builtin distribution of Monte Carlo simulation SciPy with Python

Gradient lifting method and its implementation in Python

Pandas: how to group and calculate by index

Can you create an empty pandas data frame and fill it in?

Python basic exercises teaching! can't? (practice makes perfect)
Random recommended
 Exploratory data analysis (EDA) in Python using SQL and Seaborn (SNS).
 Turn audio into shareable video with Python and ffmpeg
 Using rbind in python (equivalent to R)
 Pandas: how to create an empty data frame with column names
 Talk about quantifying investment using Python
 Python, image restoration in opencv  CV2 inpaint
 Python notes (14): advanced technologies such as objectoriented programming
 Python notes (13): operations such as objectoriented programming
 Python notes (12): inheritance such as objectoriented programming
 Chapter 2: Fundamentals of python5 Boolean
 Python notes (11): encapsulation such as objectoriented programming
 Python notes (10): concepts such as objectoriented programming
 Gradient lifting method and its implementation in Python
 Van * Python  simple crawling of a site course
 Chapter 1 preliminary knowledge of pandas (list derivation and conditional assignment, anonymous function and map method, zip object and enumerate method, NP basis)
 Nanny tutorial! Build VIM into an IDE (Python)
 Fourier transform of Python OpenCV image processing, lesson 52
 Introduction to python (III) network request and analysis
 China Merchants Bank credit card number recognition project (Part I), python OpenCV image processing journey, Part 53
 Introduction to python (IV) dynamic web page analysis and capture
 Python practice  capture 58 rental information and store it in MySQL database
 leetcode 119. Pascal's Triangle II（python）
 leetcode 31. Next Permutation（python）
 [algorithm learning] 807 Maintain the city skyline (Java / C / C + + / Python / go / trust)
 The rich woman's best friend asked me to write her a Taobao double 11 rush purchase script in Python, which can only be arranged
 Glom module of Python data analysis module (1)
 Python crawler actual combat, requests module, python realizes the full set of skin to capture the glory of the king
 Summarize some common mistakes of novices in Python development
 Python libraries you may not know
 [Python crawler] detailed explanation of selenium from introduction to actual combat [2]
 This is what you should do to quickly create a list in Python
 On the 55th day of the journey, python opencv perspective transformation front knowledge contour coordinate points
 Python OpenCV image area contour mark, which can be used to frame various small notes
 How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04
 Initial Python tuple
 Introduction to Python urllib module
 Advanced Python Basics: from functions to advanced magic methods
 Python Foundation: data structure summary
 Python Basics: from variables to exception handling
 Python notes (22): time module and calendar module