Basic data types of python

Posted by Ricklord on Sat, 05 Feb 2022 13:23:39 +0100

1, Basic data type

1. Numeric type (int # float bool complex)

(1)int integer (positive integer ﹤ 0 ﹤ negative integer)

Type gets the type of the value

res = =type(invar)
print(res)

id gets the address of the value

res = id(intvar)
print(res)

Binary shaping

intvar = 0b110
print(intvar)
print(type(intvar))
print(id(intvar))

Octal shaping

intvar = 0o127
print(intvar)
print(type(intvar))
print(id(intvar))

hexadecimal

intvar = 0xff
promt(intvar)
print(type(intvar))
print(id(intvar))

 

Summary:

Binary 1 + 1 = 10
Octal 7 + 1 = 10
Hex f+1=10

(2) float float (decimal)

Floating point type simply means data with decimals, and precisely the decimal point can float in different positions of the corresponding binary. It may be defined as floating point type in this way.

# Expression 1
floatvar = 3.6 print(floatvar,type(floatvar))

# Expression 2 scientific counting method
floatvar = 5.7e5 # Shift the decimal point to the right by 5 digits
floatvar = 5.7e-5       # Shift the decimal point to the left by 5 digits

print(floatvar,type(floatvar))
 

(3) bool Boolean (True true, False, False)

boolvar = Ture
print(boolvar,type(boolvar))

(4) complex complex type

'''
3 + 4j
 real number+imaginary number
 Real number: 3
 Imaginary number 4 j
j :  If there is a number, it is equal to square-1,So this number is j,Scientists believe that there is a high-precision type of expression
'''
Expression 1
complexvar1 = 3 + 4j
complexvar2 = -3j   #The imaginary part can be negative or plural
print(complexvar1,type(complexvar1))
print(complexvar2,type(complexvar2))

Expression 2
'''
complex(Real number, narrative) ==> complex
'''
res = complex(3,4)
print(res,type(res))

 

2. String (str) type

'''

Those with quotation marks are strings, single quotation marks, double quotation marks and three quotation marks

#Escape character \ + character

(1) meaningless characters can be made meaningful

(2) meaningful characters can become meaningless

\n: Line feed

\r\n: line feed

\t: Indent (horizontal tab) defaults to four space distances

\r: Drag the string after \ r to the beginning of the selected line

'''

(1) Single quoted string

strvar = 'Life is more than just the present'
print(savar,type(strvar))

(2) Double quoted string

strvar = ''And poetry and distant fields''
print(savar,type(strvar))  
strvar = ''And poetry and\n Distant fields''
print(strvar)

#Meaningless characters can be made meaningful
strvar = ''And poetry and\r\n Distant fields''
print(strvar)
strvar = ''And poetry and\t Distant fields''
print(strvar)
strvar = ''And poetry and\r Distant fields''
print(strvar)
strvar = ''And poetry and\n Distant\r field''
print(strvar)


#You can make meaningful characters meaningless
strvar = ''And poetry\"far\"Fang's field''
print(strvar)

(3) Three quoted string (can support cross line effect) strvar = ''

strvar = '''
Life is like getting drunk Ostensibly say no Physically honest '''
print(strvar)


#It's OK to write so below

stavar = '''


Life is like"drunk"Alcohol


On the surface'no'want


Physically honest


'''

print(strvar)

 

There is no difference between single quotation marks and double quotation marks in python, but there are differences in other languages

For example, php

$a = "123"
"{$a} => "123"
'{$a}' => '($a)'  Single quotation marks as ordinary strings

(4) Meta string r "string" prototyped output string

strvar = 'D:\python32_python\tar02'    #This is a path. Obviously, this string is not preceded by r, which is messy and the output is wrong
print(stavar)

r "string" prototype output string

strvar = r'D:\python32_python\tar02'     
print(strvar)
#That's right this time

(5) Formatting of strings

For example, Xiao Zhang bought three potions, Li Si bought four potions, and Zhang San bought five potions. You will find that on the whole, these words do not change except for the quantity

'''
%d   Integer placeholder
%f   Floating point placeholder
%s   String placeholder
'''
strvar = 'Zhang San bought it yesterday%d A balm, take a bath' %(2)
print(strvar)

Next two, look at this
%2d Occupy two digits (if not enough, take the space) and the original string is on the right
strvar = 'Zhang San bought it yesterday%2d Box balm, bath' %(2)   
print(strvar)

# %-2d Occupy two digits (if not enough, take the space) the original string is on the left

strvar = 'Zhang San bought it yesterday%-2d'Box balm, bath' %(2)
print(strvar)

# %f Floating point placeholder (in case of rounding, 6 decimal places are reserved by default)
strvar = 'The Lord of hell opens in a month%f wages'%(9.9)
print(strvar)
# We will find that the printed result is like this. King of hell 9 a month.900000 The salary has six decimal places after the decimal point
# Here is a way to keep two decimal places after the decimal point

# %. 2f keep two decimal places after the decimal point
strvar = 'The Lord of hell opens in a month%.2f wages'%(9.9178)
print(strvar)

%.xf x = Any number has several decimal places after the decimal point


# %s String placeholder
strvar = "%s I like peeing in the cinema best" %("Li Bai")
print(strvar)


#Comprehensive case
strvar = "%s In the water%s Found and punished%.2f Yuan and did it%d Push ups" ("Zhang San","Shit",500.129,50000)
print(strvar)

# If you forget to use any placeholders, you can use% s mindlessly.
strvar = "%s In the water%s Found and punished%s Yuan and did it%s Push ups" ("Zhang San","Shit",500.129,50000)
print(strvar)

 3. List type (list)

Define an empty list

listvar = []
print(listvar,type(liatvar))

Define common list

listvar = [98,6.9,Tyre,12-90,"Zhang San"]

Gets the element in the list

In python, it is divided into forward index and reverse index

Forward index (starting from 0) 0 1 2 3 4

                         0     1      2        3        4

listvar = [98,6.9,Tyre,12-90,"Zhang San"]

                          -5      -4     -3    -2      -1       

Reverse index (only python can) (starting from - 1) - 1 - 2 - 3 - 4 - 5

 

Get the number of elements of type len() in the container

listvar = [98,6.9,True,12-90j,"Zhang San"]
print(len(listvar))

#python reverse index features, instantly get the last index of the list

listvar = [98,6.9,True,12-90j,"Zhang San"]
print(listvar[-1])

 

# modify elements in the list

listvar = [98,6.9,True,12-90j,"Zhang San"]
l1= listvar[3] = "elephant"
print(l1)

 

4. tuple type

Features: can only be obtained, can not be modified, and in order

Define a tuple

tuplevar = ('Zhang San','Li Si','Xiong Da')
print(tuplevar,type(tuplevar))

Gets the element in the tuple

Forward index

#The next step is to get the big bear
tuplevar = ('Zhang San','Li Si','Xiong Da')
print(tuplevar[2])

Reverse index

Reverse acquisition of Xiong Da
tuplevar = ('Zhang San','Li Si','Xiong Da')
print(tuplevar[-1])

Modify elements in tuples: values in tuples cannot be modified

 

Attention

We found that the following print result is not a tuple type

tuplevar = (1)
print(tuplevar)
print(type(tuplevar))
#Print results

1
<class 'int'>

Next, let's look at the next one

tuplevar = (1,)
print(tuplevar)
print(type(tuplevar))
#Print results  
(1,)
<class 'tuple'>

We found that adding a comma to print the result is a tuple type

Summary: comma is the identifier to distinguish whether it is a tuple or not

 

Define empty tuple

tuplevar = ()
print(type(tuplevar))

The print result is also a tuple, but there is no comma. Why?

Because no value in it is an empty tuple

 

String type (supplementary)

'''

Features: available, non modifiable, orderly

'''

Forward index

strvar = "Big sister, as soon as I look at you, my heart beats faster and I can't breathe"
print(stavar[3])
#Print results:,

We found that both spaces and symbols occupy an index position

5. Set type set (cross and make up)

setvar = {"Amy","Sam","Rumor","Handsome"}
print(setvat,type(setvar))

We find that the results are different every time we print, so the set is disordered

Gets the element in the collection

setvar = {"Amy","Sam","Rumor","Handsome"}
setvar[1]

If we find an error, why?

Just said that the set is out of order, so there is no way to get the elements in the set according to the index

 

Let's look at a few more lines of code

setvar = {"Amy","Sam","Rumor","Handsome","Sam"}
print(setvar)

After printing, we find that there are two SAMs in the original set, but only one Sam is output, which shows that the set has the function of automatic de duplication

 

Let's take a look at the following code to see if we can define an empty set

setvar = {}
print(setvar,type(setvar))

An error is reported in the print result. Obviously, an empty set cannot be defined in this way. Next, let's see how to define an empty set?

setvar = set()
print(setvar,type(setvar))

Print the return set type () to define an empty set, you only need set + () this is the only way to create an empty set

Summary:

6. Dictionary type (dict)

'''

Data stored in key value pairs

dictvar = {key 1: value 1, key 2: value 2,...}

Before version 3.6, it was completely out of order

After version 3.6, the literal order defined in the dictionary is retained during storage, and the data in memory is sorted again according to the literal order, so it looks orderly, but in fact, it is disordered during storage.

'''

Next, we create a dictionary

dictvar = {"top":"the shy","middle":"Broiler","bottom":"jacklove","support":"Full_Grow rice in your mouth"}
print(dictvar,type(dictvar))

Gets the value in the dictionary

 

dictvar = {"top":"the shy","middle":"Broiler","bottom":"jacklove","support":"Full_Grow rice in your mouth"}
res = dictvar["middle"]
print(res)

Modify values in the dictionary

dictvar["top"] = "the boy"
print(dictvar)

Define an empty dictionary

dictvar = {}
print(dictvar,type(dictvar))

 

Important: set and dict #

'''

The key of the dictionary and the value of the set have the above requirements for data types:

(allowed type range) immutable data type: Number str tuple

(type not allowed) variable data type: list # set # dict

The key of the dictionary has the required value, but there is no requirement

The value of the dictionary can be changed arbitrarily, but the key cannot. The key is equivalent to a person's ID number.

The purpose of hash algorithm is to distribute data evenly in memory as much as possible, so as to reduce hash collision and improve the efficiency of storage and allocation; The hash algorithm must be an unordered hash, so the set {and dictionary are unordered

'''

Range of types allowed by dictionary

dictvar = {1:"abc",4.89:111,3+90j:666,False:333,"Wang Wen":"You are so handsome. I like it very much,No problem",(1,2,3,4,5,6):9999}
print(dictvar)

 

Set allowed content

setvar = {1,"a",4.56,9+3j,False,(1,2,3)}
print(setvar)

Topics: Python