目录
数字(小数字池:-5 ~ 257)
>>> a, b, c, d = 20, 5.5, True, 4+3j >>> print(type(a), type(b), type(c), type(d))
(1)int整型:
在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
注意:在Python3中已经没有long长整型这一数据类型了,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,受机器内存限制。
(2)float浮点型
(3)complex复数
(4)bool布尔值:True和False(空、0、None)
数值运算:
>>> 5 + 4 # 加法 9 >>> 4.3 - 2 # 减法 2.3 >>> 3 * 7 # 乘法 21 >>> 2 / 4 # 除法,得到一个浮点数 0.5 >>> 2 // 4 # 除法,得到一个整数 0 >>> 17 % 3 # 取余 2 >>> 2 ** 5 # 乘方 32
进制转换:
C:WINDOWSsystem32>python3 Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x=12 >>> y=hex(x) >>> print(y) 0xc >>> z=oct(12) >>> print(z) 0o14 >>> s=bin(x) >>> print(s) 0b1100
字符串
(1)字符串拼接
1 name='egon' 2 age='18' 3 print(name+'is'+age) 4 #egonis18字符串可以做级联运算(级联是设计一对多的关系),但是没空格,是字符串之间做,不能与其他类型 5 print(name,'is',age) 6 #egon is 18逗号能转成空格 7 print('_'.join(['my','name','is','kara'])) 8 #用'_'拼接起列表,列表的元素必须都是字符串类型。
(2)重复运算
1 apple='red '*4 2 print(apple) 3 #red red red red
(3)strip
1 name='* egon**_*' 2 print(name.strip("*_ ")) 3 #egon 4 print(name.lstrip('*')) 5 # egon**_* 6 print(name.rstrip('*_ ')) 7 #* egon
(4)format
1 res1='{} {} {}'.format('egon',18,'male') 2 #egon 18 male 3 res2='{1} {0} {1}'.format('egon',18,'male') 4 #18 egon 18 5 res3='{name} {age} {sex}'.format(sex='male',name='egon',age=18) 6 #egon 18 male 7 print(res1,res2,res3) 8 9 name=input('name>>') 10 x='my name is {y}'.format(y=name)#format的传递格式类似于key=value 11 print(x)#想要实现将用户输入的值传递给format就要将赋值给它
(5)split
1 name='root:x:0:0::/root:/bin/bash' 2 print(name.split(':')) 3 #默认分隔符为空格 4 name='C:/a/b/c/d.txt' #只想拿到顶级目录 5 print(name.split('/',1)) 6 #['root:x:0:0::', 'root:/bin/bash'] 7 8 name='a|b|c' 9 print(name.rsplit('|',1)) #['a|b', 'c']从右开始切分
(6)join
tag=' '#有一个空格能让join的个字符串间隔开,不然就是连在一起的 print(tag.join(['egon','say','hello','world'])) #可迭代对象必须都是字符串
(7)replace
name='alex say :i have one tesla,my name is alex' print(name.replace('alex','ss',1))
(8)其他方法
1 name='the fIRST program IS hello WOrld' 2 print(name.capitalize()) 3 #The first program is hello world首字母大写 4 5 print(name.casefold()) 6 #the first program is hello world把大写变小写 7 8 print(name.lower()) 9 #全小写the first program is hello world 10 11 print(name.upper()) 12 #全大写THE FIRST PROGRAM IS HELLO WORLD 13 14 print(name.swapcase()) 15 #THE First PROGRAM is HELLO woRLD翻转大小写 16 17 print(name.endswith('female')) 18 #判断结束位,输出布尔值 19 20 print(name.startswith('Karla')) 21 #判断起始位,输出布尔值 22 23 print('there has three little cats.they are black and white.'.title()) 24 #There Has Three Little Cats.They Are Black And White 25 26 print(name.center(50,'*')) 27 #*********************aBccdDEfg********************** 28 29 print(name.rjust(25,'*')) 30 #****************aBccdDEfg 31 32 print(name.ljust(25,'*')) 33 #aBccdDEfg**************** 34 35 print(name.zfill(25)) 36 #0000000000000000aBccdDEfg 37 38 print(name.count('c')) 39 #结果是2,区分大小的 40 41 print(name.encode()) 42 #b'aBccdDEfg'将字符串编码成bytes格式 43 44 print('hello world'.expandtabs(10)) 45 #hello world将 转成多长的空格 46 47 (name.find('a',3,5)) 48 #find( self, sub, start, end)返回找到的第一个匹配的字符的索引位置,如果没有找到则返回-1 49 50 age=input('>>: ') 51 print(age.isdigit()) 52 #判断输入的是不是数字 53 54 name='egon123' 55 print(name.isalnum()) 56 #字符串由字母或数字组成 57 print(name.isalpha()) 58 #字符串只由字母组成 59 60 print(name.isidentifier()) 61 #检测是否包含python关键字 62 print(name.islower()) 63 #检测是否全小写 64 print(name.isupper()) 65 #检测是否全大写 66 print(' -'.isspace()) 67 #检测是否全空格 68 print(name.istitle()) 69 #检测是否是标题 70 71 print(int(' 12')) 72 #转换中有空格能被自动删掉 73 print(type(str({'a':'b',1:2}))) 74 #str
列表(值可以是任意类型)
(1)定义列表
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x=['aa','bb',123] >>> y=list(['ac','bc',234]) >>> print(x,y) ['aa', 'bb', 123] ['ac', 'bc', 234] fruit=['apple','banana','pear','peach','watermelon']
(2)访问列表元素
fruit=['apple','banana','pear','peach','watermelon'] print(fruit[-1]) #watermelon print(fruit[1:3]) #区间前闭后开['banana', 'pear'] print(fruit[1:-1]) #['banana', 'pear', 'peach'] print(fruit[:3]) #['apple', 'banana', 'pear'] print(fruit[::2]) #['apple', 'pear', 'watermelon']代表每隔一个元素就取一个 print(fruit[::-1]) #['watermelon', 'peach', 'pear', 'banana', 'apple']反向输出 print(fruit[::-2]) #['watermelon', 'pear', 'apple']反向间隔取值
(3)增
fruit=['apple','banana','pear','peach','watermelon'] fruit.append('新增加')#增加至列表末尾 print(fruit) fruit.insert(1,'放在banana前')#想放入的位置和新增内容 print(fruit) num=[1,2,3,4] fruit.extend(num)#一次性往后面加多个列表元素 print(fruit) fruits=fruit.copy()#复制列表 print(fruits) #['apple', '放在banana前', 'banana', 'pear', 'peach', 'watermelon', '新增加', 1, 2, 3, 4]
(4)删
#删除del del fruit[-1] print(fruit) #['apple', 'banana', 'pear', 'peach'] del fruit print(fruit) NameError: name 'fruit' is not defined将列表全部删除 #删除remove fruit.remove('apple') #remove只用于精确的删除,不用于删除整个列表 print(fruit) #['banana', 'pear', 'peach', 'watermelon'] #pop fruit.pop() #取走列表最后一个元素,pop可以将取走的元素返回显示 print(fruit) #['apple', 'banana', 'pear', 'peach']
(5)改
fruit[0]='123' print(fruit) #['123', 'banana', 'pear', 'peach', 'watermelon']
(6)查
#统计count name=[1,2,3,1,1,1] print(name.count(1))#4 #获取下标 print(name.index(1)) #0,只返回找到的第一个相应值的下标,从左至右查找
(7)排序
name.sort() #不同数据类型不能放在一起排序 print(name) #[1, 1, 1, 1, 2, 3] name.reverse() #反序排列 print(name) #[3, 2, 1, 1, 1, 1]
字典(字典的键必须是不可变类型,值可以是任意类型)
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x={'name':'张三','agge':18} >>> print(x) {'name': '张三', 'agge': 18} >>> y={1:23} >>> print(y) {1: 23} >>> z={None:12} >>> print(z) {None: 12} >>> h={0:0} >>> print(h) {0: 0} >>> a={False:0} >>> print(a) {False: 0} >>> c={[1,2,'a']:['b','c']} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'
可变类型和不可变类型的区别是当id不变的情况下,值可不可以变。可变类型有字典和列表,不可变类型有数字、字符串。
info={ None:123, True:[123,456], 'name':'egon', 'age':18, 'gender':'male', 0: {12: 34, 'gender': 'male'}, False: {'bool': False, 123: 567} } print(info) ''' 输出结果是: {'name': 'egon', 'age': 18, 'gender': 'male', 0: 'bool'} 键要求是不可变类型,值可以是任意类型 ''' print(info[None])#123 print(info[True][1])#456 print(info[False]['bool'])#bool print(info[0][12])#bool而不是输出{12: 34, 'gender': 'male'} print(info[0][12])#KeyError: 12 info={ None:123, True:[123,456], 'name':'egon', 'age':18, 'gender':'male', False: {'bool': False, 123: 567}, 0: {12: 34, 'gender': 'male'} } print(info)#输出{None: 123, True: [123, 456], 'name': 'egon', 'age': 18, 'gender': 'male', False: {12: 34, 'gender': 'male'}} print(info[0])#输出{12: 34, 'gender': 'male'} print(info[0][12])#输出34 print(info[False])#输出{12: 34, 'gender': 'male'} print(info[False][12])#输出34 print(info[False][123])#KeyError: 123
字典的操作+内置方法:
employee={ 'a':{ 'age':28, 'gender':'male', 'salary':'15k' }, 'b':{ 'age':34, 'gender':'male', 'salary':'30k' } } #增加 employee['c']={'age':23,'gender':'female'} print(employee)#{'a': {'age': 28, 'gender': 'male', 'salary': '15k'}, 'b': {'age': 34, 'gender': 'male', 'salary': '30k'}, 'c': {'age': 23, 'gender': 'female'}} #修改 employee['b']['gender']='female' print(employee)#{'a': {'age': 28, 'gender': 'male', 'salary': '15k'}, 'b': {'age': 34, 'gender': 'female', 'salary': '30k'}, 'c': {'age': 23, 'gender': 'female'}} #删除pop employee.pop('c') print(employee)#{'a': {'age': 28, 'gender': 'male', 'salary': '15k'}, 'b': {'age': 34, 'gender': 'female', 'salary': '30k'}} #删除del del employee#写del employee('c')是删除'c' print(employee)#NameError: name 'employee' is not defined #删除popitem employee.popitem()#随机删除一个键值对 print(employee) #查找 print('c' in employee)#True,判断键是否存在 print(employee['a'].get('age'))#28
集合
s=set([3,5,2,'a',6,8])#自动排序、去重 print(s)#{2, 3, 'a', 5, 6, 8} x=set('hello world,pretty world') print(x)#{'d', 'o', 'e', 'h', 'p', 't', ' ', 'l', 'w', 'y', ',', 'r'} print(s|x)#合集{2, 3, 'w', 5, 6, 'd', 8, 'r', 'p', 'o', ',', ' ', 'l', 'e', 'y', 'h', 'a', 't'} print(s&x)#交集set() print(s-x)#差集,在s中,但是不在x中{2, 3, 5, 6, 8, 'a'} print(s^x)#对称差集 # x.add('a') print(x)#添加一个元素{'p', 'l', 'e', ' ', 'o', 'r', 'w', 'd', 'y', 'a', 't', ',', 'h'} s.update(['h','e','l','o']) print(s)#添加多个元素{2, 3, 5, 6, 8, 'e', 'o', 'a', 'h', 'l'} x.remove('h') print(x)#删除一个元素{',', 'p', 'e', 'w', 'l', ' ', 'r', 'o', 't', 'd', 'y'} print(len(x))#11
if条件语句
#!/usr/bin/env python #coding:utf-8 name=input('name>>>') pwd=input('password>>>') if name == 'aa' and pwd == '123': print('welcome') else: print('sorry')
1.猜年龄游戏
age=input('input your age:') height=input('input your height:') weight=input('input your weight:') is_pretty=True success=False if age>='18' and age<'22' and height>'170' and weight<'100' and is_pretty==True: print('上前打招呼') elif success==True: print('在一起') else: print('大哥,你好')
while循环语句
1.用户验证:
#!/usr/bin/env python #coding:utf-8 name = 'seven' pwd = 123 username = input('please input username:') password = input('please input password:') password = int(password) if username==name and password==pwd: print('you are successful') else: print('input error')
2.用户有三次验证机会
#!/usr/bin/env python #coding:utf-8 name = 'seven' pwd = 123 count=0 while count<3: count+=1 username = input('please input username:') password = input('please input password:') password = int(password) if username==name and password==pwd: print('you are successful') break else: print('failed')
3.多用户验证,每个用户有三次验证机会
#!/usr/bin/env python #coding:utf-8 dic={ 'kara1':{'pwd':'123','count':0}, 'kara2':{'pwd':'123','count':0}, 'kara3':{'pwd':'123','count':0} } while True: username=input('username>>>') if not username in dic: print('用户不存在') continue if dic[username]['count']>2: print('验证次数过多') break dic[username]['count'] += 1 password=input('password>>>') if password==dic[username]['pwd']: print('login in') break else: print('error')
升级版:
#在同目录下创建一个db.txt文件
#!/usr/bin/env python #coding:utf-8 dic={ 'kara1':{'pwd':'123','count':0}, 'kara2':{'pwd':'123','count':0}, 'kara3':{'pwd':'123','count':0} } count=0 while True: username=input('username>>>') if username not in dic: print('用户不存在') continue with open('db.txt','r') as f: lock_users=f.read().split('|') if username in lock_users: print('用户%s已被锁定'%username) break if dic[username]['count']>2: print('验证次数过多,已被锁定') with open('db.txt','a') as f: f.write('%s|'%username) break dic[username]['count'] += 1 password=input('password>>>') if password==dic[username]['pwd']: print('login in') break else: print('error')