Python学习之旅 —— 基础篇(二)数据类型、运算、while循环
本篇要点:
常量定义
数据类型(重点是字符串的各种操作、列表和字典)
各种运算
while 循环
一、常量定义
虽然叫做常量,但是python中的常量是可修改的。(c语言中的常量不可修改。)常量的定义知识通过所有字母大写来提示看代码的人,这个是个常量,不要尝试去修改它。
>>> MYSQL_CONNECTION = '10.x.x.x.x’ # 所有字母大写
二、数据类型
包括:数字、布尔值、字符串、列表、元组、字典(无序),通过type()可以查看数据类型。
1、数字
包括:
整型 int
在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
长整型 long
python3的版本中(python2.2之后的版本),python会在需要的时候自动将整数数据转换为长整型,所以,不用在长整型数据后面加L也不会导致严重后果。
浮点型 float
就是带小数点的数,实数。
复数 complex (用不到,不管了)
>>> a = 100 >>> b = 100.1 >>> type(a) <class 'int'> >>> type(b) <class 'float'> >>>
2、布尔值
True 和 False (1和0),做判断时经常使用。
>>> 0 == False True >>> 1 == True True >>>
3、字符串
第一篇中提到了的字符串,字符串的格式化输出等。今天主要整理字符串的常用操作。
# 定义字符串 msg = 'Pesen is a good man' print(msg) # 查看字符串长度 len_of_str = len(msg) print(len_of_str) # 字符类型 print(type(msg)) # strip() 移除空白 msg = msg.strip() print(msg) # 分割 split() & 合并 join() str1 = 'id,Name,ps' list1 = str1.split(',') # 字符串,逗号分隔,输出结果是一个列表 print(list1) str2 = '|'.join(list1) # 用'|' 重新合并字符串 print(str2) # 判断字符串有没有空格 print('' in msg) # 另外一种形式的变量赋值 _msg = 'My name is {name},{age} years old.' msg = _msg.format(name = 'Pesen', age = 18) print(msg) _msg = 'My name is {0},{1} years old.' msg = _msg.format('Pesen', 19) print(msg) # 字符串切片 msg = 'Pesen is a good man' print(msg[4:10:2]) # 输出第4/6/8个字符,最后面的2表示步长,就是隔多少取一个字符 # 输出的格式填充 print(msg.center(40, '+')) # 判断字符串中有没有某些内容 if msg.find('man'): print(msg) # isdigit表示判断age的值是不是数字类型: age = '18' if age.isdigit(): print('True') else: print('False') # 规定用户必须输入数字类型时,可使用isdigit age = input('年龄: ') if age.isdigit(): age = int(age) else: print('输入有误,必须是数字,请重新输入.') # 判断是否有特殊字符 name = 'Pesen@Xie' print(name.isalnum()) # 有特殊字符返回False. # startswith endswith 判断是以什么字符或者字符组开头 msg = 'Pesen is a good man.' print(msg.startswith('Pe')) # 匹配到返回True print(msg.endswith('man')) # 匹配不到返回False # 字符转成全大写或者全小写 msg = 'Pesen is a good man.' print(msg.upper()) # 转全大写 print(msg.lower()) # 转全小写
4、列表
主要说明如何定义列表,以及列表的常用操作
# 创建一个列表,把逗号分隔的不同的数据项使用方括号括起来即可 list1 = ['Pesen', 18, [1,2,3,4,5]] # 可以存储任意类型的数据 print(list1) # 获取列表中的值 list1 = ['Pesen', 18, [1,2,3,4,5]] print(list1[0]) print(list1[2][2:5:2]) # 与字符串一样,列表也支持切片和步长 # 更新列表中的元素 list1 = ['Pesen', 18, [1,2,3,4,5]] list1[1] = 20 print(list1) # 删除列表元素,使用del list1 = ['Pesen', 18, [1,2,3,4,5]] del list1[2][3] # 删除小列表中的4 print(list1) # 列表操作的方法 # list.append(obj):在列表末尾添加新的对象 list1 = ['Pesen', 18, [1,2,3,4,5]] dict1 = {'name': 'Pesen', 'age': 20, 'job': 'engineer'} list1.append(dict1) # 把字典dict1作为元素追加到list1中 print(list1) # list.count(obj):统计某个元素在列表中出现的次数 list1 = [123, 54, 456, 23, 7, 35, 45, 34, 9, 'lalalal', 9, 234, 74356, 234, 67, 124, 5, 23, 9, 34, 9, 344, 223, 34, 9] num_of_ele = list1.count(9) # 统计9在列表中的个数 print(num_of_ele) # list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) list1 = [1,2,3] list2 = [4,5,6] list1.extend(list2) # 把列表2中的元素都追加到list1的末尾 print(list1) # list.index(obj):从列表中找出某个值第一个匹配项的索引位置 list1 = [123, 54, 456, 23, 7, 35, 45, 34, 9, 'lalalal', 9, 234, 74356, 234, 67, 124, 5, 23, 9, 34, 9, 344, 223, 34, 9] position = list1.index(9) # 第一个9元素的下标 print(position) # 修改所有9元素为999 for i in range(list1.count(9)): position_of_ele = list1.index(9) list1[position_of_ele] = 999 print(list1) # 删除所有34元素 for x in range(list1.count(34)): del list1[list1.index(34)] # 等同于list1.remove(34) print(list1) # list.insert(index, obj) 给列表插入对象 list1 = [1,2,3,4,5,6] list1.insert(2,'Pesen') # 把字符串Pesen插入到第三个位置 print(list1) # list.pop(obj) 移除列表中的一个元素(默认最后一个元素) list1 = [1,2,3,4,5,6] list1.pop() # 删除元素6 list1.pop(2) # 删除第二个位置的元素,3 print(list1) # list.reverse():反转列表中元素 list1 = [1,2,3,4,5,6] list1.reverse() print(list1) # list.sort(obj):对原列表进行排序 list1 = [7,2,3,14,6,6,2,76,88,12,543,76,85] list1.sort() # python3无法对多种类型的数据排序 print(list1) # list.copy copy一个列表 浅copy list1 = ['Pesen', 18, [1,2,3,4,5]] #list2 = list1.copy() import copy list2 = copy.deepcopy(list1) # 用copy模块的deepcopy() 实现深层次的copy list1[1] = 20 # 更新list1中的元素18为20,list2中的元素18未改变 list1[2][0] = 10 # 更新list1中的小列表里的元素1为10,两个列表中都变化了, list.copy() 是浅copy print(list1,list2) # 操作列表的函数 list1 = [1,2,3,4,5,6] print(len(list1)) # 打印列表的长度 print(max(list1)) # 打印列表中最大的值 print(min(list1)) # 打印列表中最小的值 # 元组转换成列表 tuple1 = (0,1,2,3) # 定义个一个元组 list1 = list(tuple1) print(list1)
5、字典(无序)
# 创建字典 dict = { 0: { 'name': 'Pesen', 'age': 18 }, 1: { 'name': 'Jack', 'age': 19 } } # 查询 print(dict[0]) # 修改 dict[0]['age'] = 20 print(dict) # 新增 dict[0]['job'] = 'IT' print(dict) # 删除 dict[0].pop('job') print(dict) # 获取key对应的value print(dict[0].get('name')) # update,key不重复添加,key重复把新的value赋给原key dict2 = { 1: 'BALABALA', 2: 'lalala', 3: 'hehe' } dict.update(dict2) print(dict) # items 转换成列表 数据量大时不要这么做,太消耗内存资源 print(dict.items()) # keys 获取所有的key print(dict.keys()) # value 获取key对应的value print(dict.values()) # 判断某个数据是否在字典的key中 print(3 in dict) # setdefault 取一个key的value,如果不存在,就添加 print(dict.setdefault(3,'haha')) # fromkeys dict3 = {} print(dict3.fromkeys([5,6,7,8], 'gagaga')) # 列表中的元素作为key,gagaga作为value # 循环取值 for key in dict2: #高效率的循环方式 print(key,dict2[key]) for key,value in dict2.items(): # 先把字典转换成列表,再取值,效率低,耗资源,不推荐 print(key,value)
三、while 循环
示例程序:打印1到100,50~60之间不打印(包括50和60)
count = 0 while True: # 格式 while + 循环条件,成立时才循环 ,本例子中是死循环,少写为妙. count += 1 if count >= 50 and count <= 60: # 满足这个条件是跳出本次循环 continue continue if count == 100: # 满足这个条件,用break跳出整个循环 print("Byebye") break print("Loop: ", count)