Common Data Types of Python Based on Python Development

Keywords: Python Mobile Programming xml

Bowen syllabus

  • Introduction to Python
  • Variables of Python
  • 3. Data types commonly used in Python
    1, figures
    2. Strings
    3, tuple
    4, list
    5, dictionary

Introduction to Python

Python is a dynamic interpretative programming language. Python is easy to learn, powerful, supports object-oriented and functional programming. It can be used in Windows, Linux and other operating systems. At the same time, Python can be used in Java, net and other development platforms. Therefore, it is also called "glue language".

Python is developed in c language, but there are no more complex data types such as pointers in c language. Python's simplicity greatly reduces the software code and further simplifies the development tasks.

Python is rich in libraries, and its standard library is huge. It can help deal with various tasks, including regular expressions, document generation, unit testing, threads, databases, web browsers, CGI, FTP, e-mail, XML, XML-RPC, HTML, WAV files, cryptosystem, GUI (graphical user interface), TK and others. System-related operations.

Python's popularity as a programming language is closely related to its wide range of application scenarios. It can be applied in the following scenarios:

  • System Programming: It is convenient for system maintenance and management. It is an ideal programming tool for many Linux system operators.
  • Graphics processing: PIL, Tkinter and other graphics library support, can easily carry out graphics processing.
  • Mathematical processing: NumPy extensions provide a large number of interfaces with standard math libraries.
  • Text processing: The re module provided by Python supports regular expressions, and also provides SGML and XML analysis modules.
  • Database programming: Python can operate SQL server, oracle, MySQL and other databases.
  • Network programming: Provide rich modules, support sockets programming, can facilitate the rapid development of distributed applications.
  • Web programming: can be used as a web application development language.
  • Multimedia applications: Python's PyOpenGL module encapsulates the OpenGL application programming interface, which can perform two-dimensional and three-dimensional image processing. PyGame module can be used to write game software.

At present, there are two versions of Python, version 2 and version 3, which are incompatible and have different grammar. For beginners, don't bother about which version to use, use a certain version to learn, wait until you're almost done, and then study the differences between different versions (I use version 3 here).

Can be in Python's official website Download the version on the corresponding platform, Python installation under Windows is relatively simple, basically no brain next step, here is just more about it.

Python uses IDLE development tools. To learn Python language, first of all, we need to master IDLE, which can run code and debug related conveniently, and realize the functions of grammar highlighting, code prompting and code completion.

When using the IDLE tool, you can open it by clicking on the following:

Python statements can be executed immediately by pressing enter key code for each input line using the open initial interface shell mode. The following interface:

Or press the "Ctrl+N" shortcut key to open the editing mode of IDLE, which is more commonly used. After pressing the "Ctrl+N" shortcut key, the following interface will appear (the code to be executed can be saved after writing, and then run, or directly press the "F5" key to run):

Variables of Python

The concept of variables, like other languages, is an area of computer memory where variables can store any value and the value can be changed. Variable names are composed of letters, numbers and underscores. It is important to note that Python keywords cannot be used. English upper and lower case letters are sensitive. The first character must be a letter or underscore, not a number.

As follows:

A correct example of defining variables:

>>> var_1 = 1      #Define variable 1
>>> var_2 = 2     #Define variable 2
>>> >>> print var_1    #Output Defined Variable 1
1
>>> print var_2       #Output Defined Variable 2
2
>>> print (var_1,var_2)   #Output variables 1 and 2 at the same time
(1, 2)
#Three variables can also be defined at the same time, as follows:
>>> a,b,c = 1,2,3
>>> print a
1
>>> print b
2
>>> print c
3
>>> print (a,b,c)
(1, 2, 3)

3. Data types commonly used in Python

Python's built-in data types are numbers, strings, tuples, lists, and dictionaries.

1, figures

Number types include integer, floating-point, Boolean, etc. Variables are managed by Python's built-in basic data types when declaring, and numerical and type associations and transformations are implemented in the background of the program. According to the value of the variable, we can automatically judge the type of the variable. We don't need to care about the type of variable space. As long as we know that a number is stored in the created variable, the program only operates on the value.

(1) Integer and floating-point type

Integers are represented by integers and decimal digits are represented by floating-point numbers. The code is as follows:

>>> x = 123
>>> print x
>>> print (x)
123
>>> x=1.98
>>> print (x)
1.98

The above code first defines the variable x=123, where x is an integer and X is an integer variable. When x=1.98, x becomes a floating-point variable. It can be seen that the type of variable can be changed, because when Python assigns the existing variable again, it actually creates a new variable, even if it does. The variable names are the same, but the identifiers are not the same. The identifiers of the variables can be output using the id function.

>>> x = 123
>>> print (id(x))
140714328191632
>>> x = 1.98
>>> print (id(x))
2151782266320

All the above codes print the label of variable x, and the label before and after assignment is different.

(2) Boolean type
1) Boolean type is used for logic operation, which has two values, True and False, to represent truth and falsehood.

>>> f = True
>>> print (f)
True
>>> if(f):
    print (1)

1

The variable "f = True" is defined in the code. If it is a judgment statement, if it is true, print statement is executed. The final output is 1, indicating that the statement is executed successfully.

2) The result returned by the comparison operator is a Boolean value.

>>> 3>4
False     #false
>>> 4.115>2.1
True     #really

(3) Python operators,
The arithmetic operators used in Python are basically the same as the symbols used in mathematical operations. They are composed of +, -,*, /(addition, subtraction, multiplication and division) and parentheses. The order of operation is first multiplication and division, then addition and subtraction, parentheses first, and two operators are% and **. They are modular operation (residual) and exponential operation (square).
Code example:

>>> x,y = 10,2     #Define two variables
>>> print (x+y,x*y,x/y)     #Calculate the multiplication and division of these two variables.
12 20 5.0
>>> print (5 + 8 * 3)
29
>>> print (5 + 8 * 3 / 4)
11.0
#The following are modular and power operations respectively:
>>> 8%5
3
>>> 8%4
0
>>> 2**5
32
>>> 2**3
8

Note: Python does not support the self-increasing operator + + and the self-decreasing operator.

2. Strings

The string type in Python is a set of numbers, letters, and symbols that are used as a whole.

1. String usage

There are three ways to represent strings in Python, single quotation mark, double quotation mark and three quotation mark. Examples are as follows:

"> name = Lv Jianzhao'# single quotation mark demonstration
 "> motto = Make a little progress every day" # Double quotation mark demonstration
 Content ='''Destiny gives you a lower starting point than others, #3 quotation mark demonstration
 It's for you to fight a Jedi counterattack story all your life. ''
>>> print (name)
Lu Jian Zhao
>>> print (motto)
Make a little progress every day
>>> print (content)
Fate gives you a lower starting point than others.
It's for you to fight a Jedi counterattack story all your life.

Variable name uses single quotation marks, variable motto uses double quotation marks, variable content uses three quotation marks. They are all legal Python string types. It should be noted that single quotation marks and double quotation marks work the same way and can be used customarily, but when defining multiple lines of text, three quotation marks must be used.

2. Cautions for using strings
Strings are defined in single quotation marks, double quotation marks and triple quotation marks. In most cases, the functions are the same, but the usage of strings is different in special cases. Here are the points needing attention.

(1) Single quotation marks, double quotation marks and three quotation marks appear in pairs. If they begin with single quotation marks, they must end with single quotation marks, so that they cannot be mixed to represent strings. The following code will report an error:

>>> name = "Lu Jian Zhao'         #It starts with double quotation marks and ends with single quotation marks, which results in an error.
SyntaxError: EOL while scanning string literal
>>> name = "Lu Jian Zhao'''     #Double quotation marks at the beginning and three quotation marks at the end will also cause errors.
SyntaxError: EOL while scanning string literal

(2) If single or double quotation marks appear separately in a string, another definition of quotation marks can be used, as follows:

>>> title ="let's Go"        #Double quotation mark definition
>>> print (title)
let's Go
>>> title2 = 'let"s Go '         #Single quotation mark definition
>>> print (title2)
let"s Go 
>>> title3= '''let"s Go! let 's Go'''             #Definition of three quotation marks
>>> print (title3)
let"s Go! let 's Go

The single quotation mark appears in the above string variable title, which needs to be defined by double quotation mark. The double quotation mark appears in the string variable Title 2, which needs to be defined by single quotation mark. When single quotation marks and double quotation marks appear in a string, three quotation marks are needed to define them.
(3) When special characters such as single quotation mark and double quotation mark appear in the string, escape character definition can also be used. The transfer character in Python is "" and can be output as it is by adding "" before the special character, regardless of whether the single quotation mark or double quotation mark is used to define the string. The code is as follows:

>>> title = 'let\'s go!'       #Transfer single quotation mark
>>> print (title)
let's go!
>>> title = "let\"s go!"      #Escape double quotation marks
>>> print (title)
let"s go!

Common escape characters are as follows:

3. Other uses of strings

Python strings can be multiplied by an integer number, such as the number 3 multiplied by the string "a", resulting in the string "aaa", which is connected three times as the string "a". As follows:

>>> print (3 * 'a')          #3 times a
aaa
#Here is a Python script file
space = " "
print ("Study python")
print ( 2 * space + "Study python")
print (3 * space + "Study python")
#The results are as follows:
//Learning python
  //Learning python
   //Learning python

The script file above defines a space string variable, and uses string multiplication to decide the format of output when output. It is easy to realize the space in front of the file. And it's very concise.

3, list

Lists are very important data types in Python and are usually used as return values of functions. It is composed of a group of elements. Lists can be added, deleted and looked up. Element values can be modified.
(1) Define lists and their values

>>> num = ['001','002','003']            #Define a list
>>> print (num)               #Print out all the elements in the list
['001', '002', '003']
>>> print (num[1])              #Elements at position 1 in the print list
002
>>> print (num[0])              #Elements at position 0 in the print list          
001
>>> print (num[2])             #Elements at position 2 in the print list
003
#Here are the range values for the list
>>> print (num[0:2])               #List the elements before position 0 to position 2
['001', '002']
>>> print (num[0:-1])  #Negative numbers can also be used, - 1 for the position of the last element, and - 2 for the penultimate position, and so on.
['001', '002']
>>> print (num[0:-2])      #List elements from position 0 to the penultimate position
['001']
>>> print (num[0:5])          #List elements in positions 0 to 5. Since there are only three elements in the list, only three are listed.
['001', '002', '003']

As can be seen from the above, when the list values are taken, the list names are parenthesed, and the numbers represent the index positions. It is important to note that the positions are incremental in turn from 0.

(2) Modify list element values

>>> print (num)           #Look at the elements of the list first
['001', '002', '003']
>>> num[0] = '004'       #Change the element at position 0 to 004
>>> print (num)          #Confirm the result of the change
['004', '002', '003']

(3) Add the elements in the list

>>> print (num)              #Output List View
['004', '002', '003']
>>> num.append ('005')            #Add an element with a value of "005"
>>> print (num)             #Confirm that the addition was successful
['004', '002', '003', '005']              
>>> num.insert(0,'001')                #Insert an element at position 0 with a value of "001"
>>> print (num)            #Confirm successful insertion
['001', '004', '002', '003', '005']

(4) Delete list elements

>>> print (num)                 #View List Contents
['001', '004', '002', '003', '005']
>>> del num[4]              #Delete position 4 in the list, which is the last element
>>> print (num)                #View confirmation
['001', '004', '002', '003']
>>> del num               #Delete the entire list
>>> print (num)               #Looking again will result in an error "No list found"
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    print (num)
NameError: name 'num' is not defined

(5) Find list elements

>>> num = ['001','002','003']            #Redefine a list
>>> '002' in num               #Find "002", exist, return true
True
>>> '005' in num               #Find "005", no, return false
False

(6) Merge List

>>> num1 =['001','002']                  #Define list num1
>>> num2 =['003','004']                 #Define list num2
>>> num = num1 + num2                #Define list num with elements num1 and num2
>>> print (num)                  #Output list num, resulting in element integration of list num1 and num2
['001', '002', '003', '004']
>>> print (num2 + num1)             #It can also be combined in this way.
['003', '004', '001', '002']

(7) Duplicate list

>>> print (num)           #Output list num
['001', '002', '003', '004']     
>>> print (num * 3)              #Multiply list num by 3 and output
['001', '002', '003', '004', '001', '002', '003', '004', '001', '002', '003', '004']

(8) List Common Questions
1) Index crossing is a common mistake in the use of lists. For example, there are four elements in the list. Because the location of the index is calculated from 0, the maximum index value is 3. If the index value is greater than 3, it means that the program cannot execute when the index crosses the boundaries. The following is true:

>>> print (num)           #View the elements in the list
['001', '002', '003', '004']
>>> print (num[5])                #Looking at the element in position 5, the index is out of bounds, so an error will be reported.
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    print (num[5])
IndexError: list index out of range

2) When obtaining a set of elements within the specified range of a list, there is no problem of list index crossing the boundary. The code is as follows:

>>> print (num)          #view list
['001', '002', '003', '004']
>>> print (num[0:5])               #Element values from position 0 to position 5 are output.
['001', '002', '003', '004']

3) List elements can also be lists, coded as follows:

>>> num = [['001','002'],['003','004'],['005','006']]          #Define list elements as lists
>>> print (num)             #Output View Results
[['001', '002'], ['003', '004'], ['005', '006']]
>>> print (num[0])       #View the elements of num location 0 in the list
['001', '002']
>>> print (num[0][0])     #Look at the elements of position 0 in num position 0 in the list, a little bit around!
001
>>> print (num[2][1])        #View the element at position 1 in num position 2 in the list
006

4, tuple

(1) Introduction to tuples
Tuples are similar to lists, and they are also a data structure in Python. They are composed of different elements. Each element can store different types of data, such as strings, numbers, and even tuples, but tuples are not modifiable. That is to say, no modification can be done after tuples are created. Tuples usually represent one row of data, while elements in tuples represent different data items.

The differences between tuples and lists are as follows:

The difference between using tuples and lists is not very big, mainly because tuples are immutable, operating faster than list blocks, and because it can not be modified, data is more secure, so it is necessary to decide whether to use tuples or lists according to the actual situation, so as to make the program more efficient.

(2) tuple operation

>>> print (num)               #Define a tuple
('001', '002', '003')
>>> num[3] = '004'             #Trying to change elements in a tuple will result in an error!
Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    num[3] = '004'
TypeError: 'tuple' object does not support item assignment
>>> print (num[0])            #Value-taking operations are exactly the same as lists

001
>>> print (num[2])           #Value-taking operations are exactly the same as lists

003
>>> del num[0]              #Tuples do not allow deletion of an element

Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    del num[0]
TypeError: 'tuple' object doesn't support item deletion
>>> del num                #But you can delete the whole tuple

>>> print (num)         #If you look again, you will report that the tuple name does not exist.

Traceback (most recent call last):
  File "<pyshell#55>", line 1, in <module>
    print (num)
NameError: name 'num' is not defined

(3) Conversion between tuples and lists

Tuples and lists can be converted to each other. The code is as follows:

>>> num = ('001','002','003')          #Define a tuple
>>> print (type(num))             #View the type of num

<class 'tuple'>               #"Tuple" means tuple
>>> numlist = ['004','005','006']        #Define a list
>>> print (type(numlist))       #Confirmation type is list

<class 'list'>        #"List" means list
#The following is to convert a list to a tuple and a tuple to a list
>>> NUM = list(num)    #The grammar for converting tuples to lists is "list ()". Here, the tuple num is converted to list NUM.

>>> print (type(NUM))               #View the converted type

<class 'list'>     #Type is list, no problem.
>>> NumList = tuple(numlist)     #The grammar for converting lists to tuples is "tuple ()". Here, numlist is converted to tuple NumList.

>>> print (type(NumList))          #View the converted type

<class 'tuple'>    #Type is tuple, no problem.

5, dictionary

Dictionary (dict) is an important data type in Python. Dictionary is a collection of "key-value" pairs. The values in dictionary are referenced by keys.

(1) Dictionary Creation and Value Selection

>>> mobile = {'zhangsan':'123456','lisi':'234567','wangwu':'345678'}    #Create a dictionary with the name "mobile"

>>> print (mobile)     #Output Dictionary Content

{'zhangsan': '123456', 'lisi': '234567', 'wangwu': '345678'}
#Dictionary values are different from list and tuple values. Tuple and list values are obtained by digital index, while dictionary values are obtained by keys. As follows:
>>> print (mobile["zhangsan"])        #Query zhangsan's corresponding values

123456
>>> print (mobile["wangwu"])       #Query the corresponding value of wangwu

345678

It should be noted that the keys in the dictionary must be unique, but the values of different keys can be the same. When multiple keys are defined the same, only the last definition takes effect. That is to say, the later definition will override the existing key-value pairs.

(2) Addition, modification and deletion of dictionaries

#Add data to a dictionary
>>> print (mobile)    #List the values in the current dictionary

{'zhangsan': '123456', 'lisi': '234567', 'wangwu': '345678'}
>>> mobile['zhaosi'] = '6666666'      #Add a new key-value pair

>>> print (mobile)       #Check whether to add

{'zhangsan': '123456', 'lisi': '234567', 'wangwu': '345678', 'zhaosi': '6666666'}
#Modifying key-value pairs in dictionaries
>>> mobile['zhangsan'] = '2222222'     #Modify the existing key-value pairs and cover them directly.

>>> print (mobile)      #Check to see if the modification was successful

{'zhangsan': '2222222', 'lisi': '234567', 'wangwu': '345678', 'zhaosi': '6666666'}
#Delete key-value pairs in dictionaries
>>> del mobile['zhangsan']       #Delete zhangsan's key-value pairs

>>> print (mobile)     #Check to see if deletion occurs

{'lisi': '234567', 'wangwu': '345678', 'zhaosi': '6666666'}

Note that dictionaries cannot perform join operations using the "+" operator.

(3) Examples of dictionary application

kgc = {}
name = '--please input user:'
user = input("name:")
pwd = input("password:")
kgc [user] = pwd
print (kgc)
name = '--user searched:'
key = input(name)
print (kgc[key])

The above code defines an empty dictionary to store the "key-value" pairs of usernames and passwords, then uses the input () function to accept the keyboard input usernames and passwords, saves them in the dictionary kgc, and finally uses the keyboard to enter a username and find its corresponding keys in the dictionary.

The results are as follows:

name:lv jian zhao
password:123456
{'lv jian zhao': '123456'}
--user searched:lv jian zhao
123456

Note: The above script is based on Python version 3. If you use Python version 2, you need to replace the input () function with raw_input () in order to execute normally.

———————— This is the end of the article. Thank you for reading.————————

Posted by ashwood on Mon, 16 Sep 2019 22:12:57 -0700