Python Python development foundation of common data types

Bowen Outline

  • A, Python Introduction
  • Two, Python variables
  • Three, Python common data type
    1, number
    2, string
    3, tuples
    4, list
    5, Dictionary

A, Python Introduction

Python is a dynamic programming language interpreted. Python it easy to learn, powerful, supporting object-oriented, functional programming, can be used on Windows, Linux and other operating systems, while Python can be used on Java, .net and other development platforms, and therefore, it is also known as " glue language. "

C using the Python language development, but no more complex data type c language pointer or the like. The simplicity of Python code that makes the software considerably reduced, to further simplify development tasks.

Python has a rich library, its standard library is very large, and can help with a variety of work, including regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, FTP, email, XML, XML- RPC, HTML, WAV files, cryptography, GUI (graphical user interface), TK and relating to other operating systems.

Python's becoming a popular programming language, and its wide range of application scenarios are inextricably linked. It can be applied in the following scenarios:

  • System Programming: to facilitate system maintenance and management, a lot of Linux systems operation and maintenance personnel of the ideal programming tool.
  • Graphics: There PIL, Tkinter and other graphics library support, can easily handle the graphics.
  • Mathematical treatment: NumPy extensions provide a large number of interfaces and standard math libraries.
  • Text processing: Python re module provides regular expression support, it also provides SGML, XML analysis module.
  • Database Programming: Python can manipulate SQL server, oracle, MySQL and other databases.
  • Network Programming: Provides rich set of modules, support for sockets programming, can quickly and easily develop distributed applications.
  • web programming: can be used as a web application development language.
  • Multimedia applications: Python PyOpenGL the module encapsulates "the OpenGL Application Programming Interface", capable of processing two-dimensional and three-dimensional image. PyGame module can be used to write game software.

Currently Python version 2 and version 3 has two versions, they are not compatible, there are differences in syntax. For starters, do not tangle which version you want to use a version of learning, such as learning about, come to study the difference between different versions (I used here is version 3).

May Python's official website to download the appropriate version of the platform, Python installation under Windows is relatively simple, the next step is basically no brain, but introduce more here.

Python is IDLE use development tools, learn Python language, one must master the development tools IDLE, it can easily run code and to make related debugging, code-syntax highlighting, code completion and code hinting compared congruent intelligent function.

When using IDLE tool, you can open by clicking on the following:
Python Python development foundation of common data types

Python statement can be used after the initial mode of the interface shell is opened, each input line of code is executed immediately press enter. The following interface:
Python Python development foundation of common data types

Or press "Ctrl + N" shortcut key, you can open IDLE's Edit mode, this approach more commonly used, the code following screen (to be performed will appear after press "Ctrl + N" shortcut key, you can save after writing, then run, you can also press "F5" key to run):

Python Python development foundation of common data types

Two, Python variables

About variables concept, and other similar language, are an area of ​​computer memory, variables can store any value, and the value can be changed. Variable names consist of letters, digits, and underscores the need to note that you can not use Python keywords, English case-sensitive letters, first character must be a letter or an underscore, not a number.

as follows:

Examples of the correct definition of variables:

>>> var_1 = 1      #定义变量1
>>> var_2 = 2     #定义变量2
>>> >>> print var_1    #输出定义的变量1
1
>>> print var_2       #输出定义的变量2
2
>>> print (var_1,var_2)   #将变量1和变量2同时输出
(1, 2)
#也可以同时定义三个变量,如下:
>>> a,b,c = 1,2,3
>>> print a
1
>>> print b
2
>>> print c
3
>>> print (a,b,c)
(1, 2, 3)

Three, Python commonly used data types

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

1, Digital

Numeric types include integer, floating point, boolean, and so, when a statement by the Python built basic data types to manage variables for values ​​associated with the type, and the conversion program in the background. Depending on the value of variables automatically determine the type of a variable, we do not care what type of variable space, just know that the variables created to store a number, but this value program operation.

(1) integer and floating point

It represents an integer of using integer with decimal floating-point represented using the following code:

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

上面代码首先定义了变量x=123,此时的x值是整数,x就是整型变量,当x=1.98时,x又成为了浮点型变量,由此可以看出,变量的类型是能改变的,这是因为当Python给已经存在的变量再次赋值时,实际上时创建了一个新的变量,即使变量名相同,但标识并不相同,变量的标识可以使用id函数输出。

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

以上代码都是对变量x的标识进行打印,赋值前后的标识并不相同。

(2)布尔型
1)布尔型用于逻辑运算,有两个值True、False,表示真和假。

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

1

代码中定义了变量“f = True”,if是判断语句,为真则执行print语句,最后输出的是1,说明语句执行成功。

2)使用比较运算符返回的结果是布尔值,

>>> 3>4
False     #假
>>> 4.115>2.1
True     #真

(3)Python运算符
Python中使用的算术运算符和数学运算中使用的符号基本相同,由+、-、*、/(加减乘除)和小括号组成,运算顺序也是先乘除后加减,小括号优先,还有两个运算符是%和**,分别是求模运算(取余数),求幂运算(求平方)。
代码示例:

>>> x,y = 10,2     #定义两个变量
>>> print (x+y,x*y,x/y)     #计算这两个变量的加乘除。
12 20 5.0
>>> print (5 + 8 * 3)
29
>>> print (5 + 8 * 3 / 4)
11.0
#以下分别是求模运算和求幂运算:
>>> 8%5
3
>>> 8%4
0
>>> 2**5
32
>>> 2**3
8

注意:Python不支持自增运算符++和自减运算符--。

2、字符串

Python中的字符串类型是一组包含数字、字母和符号的集合,作为一个整体使用。

1、字符串使用

在Python中有三种表示字符串的方式,单引号、双引号、三引号,示例如下:

>>> name = '吕建钊'              #单引号示范
>>> motto = "每天进步一点点"          #双引号示范
>>> content = '''命运给你一个比别人低的起点,                     #三引号示范
是为了让你用一生去奋斗一个绝地反击的故事。'''
>>> print (name)
吕建钊
>>> print (motto)
每天进步一点点
>>> print (content)
命运给你一个比别人低的起点,
是为了让你用一生去奋斗一个绝地反击的故事。

变量name使用单引号,变量motto使用双引号,变量content使用三引号,他们都是合法的Python字符串类型,需要注意的是,单引号和双引号的作用是一样的,可以根据习惯使用,但是定义多行文字时,必须要使用三引号。

2、使用字符串注意事项
字符串的定义方式单引号、双引号、三引号大部分情况下作用是相同的,但在特殊情况下使用也有所区别,下面是需要注意的地方。

(1)单引号、双引号、三引号它们是成对出现的,如以单引号开头就要以单引号结尾,不能混合使用表示字符串。如下代码就会报错:

>>> name = "吕建钊'         #开头是双引号,结尾是单引号,结果报错。
SyntaxError: EOL while scanning string literal
>>> name = "吕建钊'''     #开头是双引号,结尾是三引号,也会报错。
SyntaxError: EOL while scanning string literal

(2)如果字符串中单独出现单引号或双引号,可以使用另一种引号定义,如下:

>>> title ="let's Go"        #双引号定义
>>> print (title)
let's Go
>>> title2 = 'let"s Go '         #单引号定义
>>> print (title2)
let"s Go 
>>> title3= '''let"s Go! let 's Go'''             #三引号定义
>>> print (title3)
let"s Go! let 's Go

以上字符串变量title中出现了单引号,需要使用双引号定义,字符串变量title2中出现了双引号,需要使用单引号定义。当字符串中同时出现单引号和双引号,就需要使用三引号进行定义。
(3)当字符串中出现单引号、双引号等特殊字符时,还可以使用转义字符定义。Python中的转移字符是“\”,只要在特殊字符前面加上“\”,就可以原样输出,而不用去管定义字符串使用的是单引号还是双引号,代码如下:

>>> title = 'let\'s go!'       #转移符单引号
>>> print (title)
let's go!
>>> title = "let\"s go!"      #转义符双引号
>>> print (title)
let"s go!

常用的转义符如下所示:
Python Python development foundation of common data types

3、字符串的其他使用方法

Python的字符串可以进行乘法的操作,可以用一个整型数字和字符串相乘,如用数字3乘以字符串“a”,结果是字符串“aaa”,相同于字符串“a”连接了3遍。如下:

>>> print (3 * 'a')          #3乘以a
aaa
#以下是一个Python脚本文件
space = " "
print ("学习python")
print ( 2 * space + "学习python")
print (3 * space + "学习python")
#执行结果如下:
学习python
  学习python
   学习python

以上脚本文件是定义了一个空格字符串变量space,在输出时使用字符串乘法决定输出的格式,很容易地实现了文件前面的空格。并且十分简洁。

3、列表

列表是Python中非常重要的数据类型,通常作为函数的返回值。由一组元素组成,列表可以实现添加、删除和查找操作,元素值可以被修改。
(1)定义列表及列表的取值

>>> num = ['001','002','003']            #定义一个列表
>>> print (num)               #将列表中的元素全部打印出来
['001', '002', '003']
>>> print (num[1])              #打印列表中位置1的元素
002
>>> print (num[0])              #打印列表中位置0的元素          
001
>>> print (num[2])             #打印列表中位置2的元素
003
#以下是列表的范围取值
>>> print (num[0:2])               #列出位置0到位置2之前的元素
['001', '002']
>>> print (num[0:-1])  #也可以用负数,-1表示最后一个元素的位置,-2表示倒数第二个位置,以此类推。
['001', '002']
>>> print (num[0:-2])      #列出从位置0到倒数第2个位置的元素
['001']
>>> print (num[0:5])          #列出位置0到位置5的元素,由于列表中的元素只有三个,所以只列出了三个
['001', '002', '003']

从上面可以看出,列表取值时用列表名加上中括号,数字表示索引位置,需要注意位置是由0开始依次递增的。

(2)修改列表元素值

>>> print (num)           #先查看列表的元素
['001', '002', '003']
>>> num[0] = '004'       #将位置0的元素改为004
>>> print (num)          #确认更改结果
['004', '002', '003']

(3)添加列表中的元素

>>> print (num)              #输出列表查看
['004', '002', '003']
>>> num.append ('005')            #添加一个元素,值为“005”
>>> print (num)             #确认添加成功
['004', '002', '003', '005']              
>>> num.insert(0,'001')                #在位置0插入一个元素,值为“001”
>>> print (num)            #确认插入成功
['001', '004', '002', '003', '005']

(4)删除列表元素

>>> print (num)                 #查看列表内容
['001', '004', '002', '003', '005']
>>> del num[4]              #删除列表中位置4,也就是最后一个元素
>>> print (num)                #查看确认
['001', '004', '002', '003']
>>> del num               #删除整个列表
>>> print (num)               #再次查看会报错“没有找到该列表”
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    print (num)
NameError: name 'num' is not defined

(5)查找列表元素

>>> num = ['001','002','003']            #重新定义一个列表
>>> '002' in num               #查找“002”,存在,返回true
True
>>> '005' in num               #查找“005”,不存在,返回false
False

(6)合并列表

>>> num1 =['001','002']                  #定义列表num1
>>> num2 =['003','004']                 #定义列表num2
>>> num = num1 + num2                #定义列表num,元素为列表num1和num2
>>> print (num)                  #输出列表num,结果是列表num1和num2的元素整合
['001', '002', '003', '004']
>>> print (num2 + num1)             #也可以这样合并显示
['003', '004', '001', '002']

(7)重复列表

>>> print (num)           #输出列表num
['001', '002', '003', '004']     
>>> print (num * 3)              #将列表num乘以3后输出
['001', '002', '003', '004', '001', '002', '003', '004', '001', '002', '003', '004']

(8)列表常见问题
1)索引越界是使用列表时常犯的一个错误,如列表中有4个元素,因为索引的位置是从0开始计算的,所以最大的索引值是3,如果索引值大于3,表示索引时越界的,程序无法执行,如下:

>>> print (num)           #查看列表中的元素
['001', '002', '003', '004']
>>> print (num[5])                #查看位置5的元素,索引越界了,所以会报错。
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    print (num[5])
IndexError: list index out of range

2)当获取列表指定范围的一组元素时,不存在列表索引越界的问题,代码如下:

>>> print (num)          #查看列表
['001', '002', '003', '004']
>>> print (num[0:5])               #输出位置0到位置5之内的元素值。
['001', '002', '003', '004']

3) a list may be a list of elements, as follows:

>>> num = [['001','002'],['003','004'],['005','006']]          #将列表元素定义为列表
>>> print (num)             #输出查看结果
[['001', '002'], ['003', '004'], ['005', '006']]
>>> print (num[0])       #查看列表num位置0的元素
['001', '002']
>>> print (num[0][0])     #查看列表num位置0中的位置0的元素,有点绕哈!
001
>>> print (num[2][1])        #查看列表num位置2中的位置1的元素
006

4, tuples

(1) Introduction tuple
similar tuples and lists, but also a data structure in Python, by different elements, each element may store different types of data, such as strings, numbers, or even tuples, tuples but can not be modified. That does not make any changes after the operation to create a tuple, tuple usually represents a row of data, and tuple elements represent different data items.

The difference between tuples and lists as follows:
Python Python development foundation of common data types
in the list of differences and the tuple is not large, mainly because tuples are immutable, the operation speed ratio block list, and because it can not be modified, the data is more secure, so the actual the case decided to use a tuple or list, make the program more efficient.

(2) Operation tuple

>>> print (num)               #定义一个元组
('001', '002', '003')
>>> num[3] = '004'             #试着更改一个元组中的元素,结果肯定是报错咯!
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])            #取值操作和列表完全一样

001
>>> print (num[2])           #取值操作和列表完全一样

003
>>> del num[0]              #元组不允许删除某个元素

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                #但可以删除整个元组

>>> print (num)         #再次查看,就会报错元组名不存在了

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

(3) a list of tuples and mutual conversion

Tuples and lists each conversion operation can be done, as follows:

>>> num = ('001','002','003')          #定义一个元组
>>> print (type(num))             #查看num的类型

<class 'tuple'>               #“tuple”的意思为元组
>>> numlist = ['004','005','006']        #定义一个列表
>>> print (type(numlist))       #确认类型为列表

<class 'list'>        #“list”就是列表的意思
#以下操作是将列表转换为元组,将元组转换为列表
>>> NUM = list(num)    #将元组转为list的语法就是“list()”,这里是将元组num转换为列表NUM

>>> print (type(NUM))               #查看转换后的类型

<class 'list'>     #类型是列表,没问题
>>> NumList = tuple(numlist)     #将列表转换为元组的语法就是“tuple()”,这里是将列表numlist转换为元组NumList

>>> print (type(NumList))          #查看转换后的类型

<class 'tuple'>    #类型是元组,没问题

5, dictionaries

Dictionary (dict) Python is an important type of data, a dictionary is - composed set of "key values", the value of the dictionary referenced by the key.

(1) dictionary and value creation

>>> mobile = {'zhangsan':'123456','lisi':'234567','wangwu':'345678'}    #创建一个字典,名称为“mobile”

>>> print (mobile)     #输出字典中的内容

{'zhangsan': '123456', 'lisi': '234567', 'wangwu': '345678'}
#字典的取值和列表及元组不同,元组和列表都是通过数字索引取值的,而字典是通过键获取相对应的值。如下:
>>> print (mobile["zhangsan"])        #查询zhangsan对应的值

123456
>>> print (mobile["wangwu"])       #查询wangwu对应的值

345678

Note that, the dictionary keys must be unique, but with different values ​​but the key may be the same as the definition of multiple keys are the same, only the last defined entry into force, that is to say, the latter will be chosen over previously existing key-value pairs.

(2) the dictionary to add, modify, delete operations

#向字典中添加数据
>>> print (mobile)    #列出当前字典中的值

{'zhangsan': '123456', 'lisi': '234567', 'wangwu': '345678'}
>>> mobile['zhaosi'] = '6666666'      #添加新的键值对

>>> print (mobile)       #查看是否添加

{'zhangsan': '123456', 'lisi': '234567', 'wangwu': '345678', 'zhaosi': '6666666'}
#修改字典中的键值对
>>> mobile['zhangsan'] = '2222222'     #修改已存在的键值对,直接覆盖即可

>>> print (mobile)      #查看是否修改成功

{'zhangsan': '2222222', 'lisi': '234567', 'wangwu': '345678', 'zhaosi': '6666666'}
#删除字典中的键值对
>>> del mobile['zhangsan']       #删除zhangsan的键值对

>>> print (mobile)     #查看是否删除

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

Note that the application does not use the "+" operator performs the connection operation.

(3) Application examples dictionaries

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 first defines an empty dictionary, used to store user name and password "key - value" pairs, then input () function accepts keyboard input of user name and password stored in the dictionary kgc, the last using keyboard to enter a user name to find its corresponding key in the dictionary.

Execution results are as follows:

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

Note: The above is based on a script written in Python version 3, if using Python version 2, you will need one of the input () function, and replaced with raw_input () should perform normally.

-------- end of this article so far, thanks for reading --------

Guess you like

Origin blog.51cto.com/14154700/2438518