前言
初始内容:python初学知识,包含基础数据类型、字符串、条件判断、循环、容器、类定义
博客地址:芒果橙的个人博客 【http://mangocheng.com】
文章目录
- 前言
- 一、基础
- 1. 基础数据类型
- 2. 变量
- 3. 字符串方法
- 4. 条件
- 5. 循环
- 6. 容器
- 6.1 list:列表
- 6.2 tuple:元组
- 6.3 dict:字典
- 6.4 set
- 7.函数
- 二、面向对象
- 1. 类的定义
- 2.类的继承
- 3.类的特殊方法
- 4.模块和包
- 5.输入输出
- 6.网络编程
- 7.函数式编程
一、基础
1. 基础数据类型
- 整数
- 浮点
- 字符串: “ABC”、‘ABC’
- 单字符转义:\
- 单个字符串(行)转义,表示一个raw字符串,里面的字符不用转义:r’ xxxxx ’ (不包括’',“”)
- 多行转义:‘’’ xxxxxx ‘’’
- 多行单个字符串(raw字符串): r’‘’ xxxxxxx ‘’’
- 布尔:True、False
- 空值:None
2. 变量
3. 字符串方法
-
format:{ } 替换输出
template = 'Hello {}'
world = 'World'
result = template.format(world)
print(result)
template = 'Hello {0}, Hello {1}, Hello {2}, Hello {3}.'
result = template.format('World', 'China', 'Beijing', 'imooc')
print(result)
template = 'Hello {3}, Hello {2}, Hello {1}, Hello {0}.'
result = template.format('World', 'China', 'Beijing', 'imooc')
print(result)
template = 'Hello {w}, Hello {c}, Hello {b}, Hello {i}.'
world = 'World'
china = 'China'
beijing = 'Beijing'
imooc = 'imooc'
result = template.format(w = world, c = china, b = beijing, i = imooc)
print(result)
-
分割
s = 'ABC'
a = s[0]
b = s[1]
c = s[2]
print(a)
print(b)
print(c)
a = s[startIndex:endIndex]
[1:]--获取从位置1开始后面的字符(默认首位是0)
[:-1]--删除位置为-1的字符(也就是获取从位置0带位置-1之间的字符)
[-1:]--获取位置-1的字符
[::-1]--从最后一个元素到第一个元素复制一遍。(也就是倒序)
[:]--相当于完整复制一份str
4. 条件
5. 循环
6. 容器
6.1 list:列表
sources = [12,23,34]
list2 = [23,'lebron',44,55]
num = 0
for item in list2:
print(item)
num = num +1
if num % 2 == 0:
print(item)
subList = list2[0:3]
print(list2[-1])
print(list2[-2])
sources.append(44)
index = 0
value = 11
sources.insert(index,value)
sources.pop()
firstValue = sources.pop(0)
sources[1] = 'James'
l1 = [11,22,33]
l2 = [44,55,66]
l = [l1,l2]
print(l[1,0])
for item in l:
a = item[0]
b = item[1]
c = item[2]
print(a*b*c)
6.2 tuple:元组
- 有序
- 基础数据类型(数字、布尔、字符)固定不变,不可添加(性能>>list)
- 组合类型可变,原因为指向同一个地址
- 可与list相互转换
t = ('Alice','Bob','Candy')
print(t[0:2])
l = list(t)
L = ['David','Ellena']
t2 = tuple(L)
one = (1)
print(one)
one2 = (1,)
print(one2)
T = ((1+2), ((1+2),), ('a'+'b'), (1, ), (1,2,3,4,5))
print(T) ==> 3 个tuple (3, (3,), 'ab', (1,), (1, 2, 3, 4, 5))
T = (1, 'CH', [3, 4])
L = T[2]
print(L)
L[1] = 40
print(L)
print(T)
L2 = [3, 40]
T[2] = L2
- 方法
- count:统计元素次数
- index:返回指定元素的下标(注:元素不存在会报错)
6.3 dict:字典
- 键值对映射
- 查找速度快 > list
- 占用内存大 < list
- 无序(3.5版本)、有序(3.6、3.7)
- key不可变(tuple可以作key,list不行)
d = dict()
d = {
'Alice':50,
'Bob':60
}
print(d)
print(d['Bob'])
if 'Alice' in d:
print(d['Alice'])
print(d.get('Ed'))
d1 = dict()
d1['Mini'] = 73
d1['Coco'] = 80
d2 = dict()
d2['Mini'] = [72,73]
d2['Mini'].append(74)
print(d2)
d3 = {
'Alice':60,
'Bob':20
}
alice = d.pop('Alice')
print(alice)
print(d)
d3['Coco'] = 60
keys = d3.keys()
d = dict()
key = (1, 2, 3)
d[key] = True
print(d)
d4 = {
'Alice':20,
'Bob':30,
'Coco':40
}
for key in d4:
value = d4[key]
print(value)
for key,value in d4.items():
print(key,value)
for key in d4.keys():
print(key)
for value in d4.values():
print(value)
- 方法
- keys:返回所有key,list类型
- values:返回所有value,list类型
- items:返回所有值,包含key和value
- clear:清除所有元素
6.4 set
s = set([1,2,3])
print(s)
1 in s
names = ['Alice','Bob']
s1 = set(names)
s1.add('Coco')
names2 = ['David','Linda']
s1.update(names)
s2 = set(['Alice','Bob','Coco'])
s2.remove('Alice')
print(s2)
s2.remove('Tina')
s3 = set(['Alice','Bob'])
s3.discard('Alice')
s3.discard('Coco')
s4 = set(['Alice','Bob'])
s4.clear()
s5 = set(['Alice','Bob'])
s6 = set(['Alice','Bob','Coco'])
s5.issubset(s6)
s6.issuperset(s5)
s5.isdisjoint(s6)
- 方法
- add:添加
- remove:删除(元素不存在报错)
- discard:删除(元素不存在不会报错)
- clear:清除所有元素
- issubset:是否子集
- issuperset:是否超集
- isdisjoint:是否重合,有重合False、无重合True
7.函数
def 函数名(参数):
函数体
def abs(param):
if param < 0:
return -param
else:
return param
def square(side):
perimeter = 4*side
area = side*side
return perimeter,area
p,a = square(5)
result = square(5)
isinstance(100,int)
isinstance('23',str)
def power(x,n):
s = 1
while n >0:
n = n-1
s = s*x
return s
def power(x,n=2):
s = 1
while n > 0:
n = n-1
s = s*x
return s
power(3,4)
power(3)
def averages(*args):
for i in args:
print(i)
print(args)
averages(1,2,3)
def info(**kwargs):
gender = kwargs.get('gender')
name = kwargs.get('name')
info(gender = 'girl', name = 'Coco')
def func(param1, param2, param3 = None, *args, **kwargs):
print(param1)
二、面向对象
1. 类的定义
class Person: pass
class Person(): pass
class Person(object): pass
class Animal(object):
location = 'Asia'
def __init__(self,name,age):
self.name = name
self.age = age
dog = Animal('wang',23)
cat = Animal('miao',12)
print(Animal.location)
Animal.location = 'Africa'
print(Animal.location)
dog.location = 'Cn'
print(dog.location)
print(Animal.location)
class Animal(object):
__location = 'Asia'
def __init__(self):
pass
@classmethod
def set_location(cls,location):
cls.__location = location
mango = Person()
cheng = Person()
mango.age = 23
mango.sex = 'girl'
print(mango.age)
class Person(object):
def __init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
person = Person('mango','girl',23)
class Animal(object):
__location = 'Asia'
print(Animal.__location)
class Animal(object):
def __init__(self,name):
self.__name = name
def get_name(self):
return self.__name
dog = Animal('Alice')
print(dog.__name)
class Person(object):
def __init__(self,name):
self.__name = name
def get_name(self):
return self.__name
p = Person('Alice')
print(p.get_name())
2.类的继承
class Person(object):
def __init__(self,name):
pass
class Student(Person):
def __init__(self,name,gender):
super(Student,self).__init__(name)
self.gender = gender
person = Person('mango')
student = Student('mango','girl')
class children(Teacher,Student):
pass
isinstance(person,Person)
isinstance(person,Student)
isinstance(student,Person)
isinstance(student,Student)
type(person)
getattr(person,'name')
setattr(person,'name','cheng')
class Person(object):
def __init__(self,name,gender,**kwargs):
self.name = name
self.gender = gender
for k,v in kwargs.items():
setattr(self,k,v)
p = Person('mango','girl',age = 23,height = 188)
print(p.name)
print(p.age)
print(p.height)
3.类的特殊方法
num = 23
str(num)
class Student(object):
def __init__(self,name):
self.name = name
def __str__(self):
return('name={}'.format(self.name))
def __repr__(self):
return('repr name={}'.format(self.name))
s = Student('mango')
print(str(s))
print(repr(s))
class Rational(object):
def __init__(self, p, q):
self.p = p
self.q = q
def __add__(self, r):
return Rational(self.p * r.q + self.q * r.p, self.q * r.q)
def __str__(self):
return '{}/{}'.format(self.p, self.q)
class Student(object):
__slots__ = ('name','age')
def __init__(self,name,age):
self.name = name
self.age = age
s = Student('mango',23)
s.gender = 'girl'
class Fib(object):
def __init__(self,num):
self.fib = []
for i in range(num):
self.fib.append(i)
def __call__(self,fib):
return self.fib
f = Fib(5)
print(f(5))
class Fib(object):
def __init__(self):
self.res = []
def __call__(self, num):
a = 0
b = 1
for x in range(num):
self.res.append(a)
a, b = b, a + b
return self.res
f = Fib()
print(f(10))
4.模块和包
import tools
from network import tools
import math
math.pi
math.pow(2,3)
from math import pi
from math import *
pi
from math import pow as mathpow
import sys
print(sys.path)
l = sys.path
l.insert(1,'../')
print(sys.path)
pip install django
pip uninstall django
5.输入输出
num = input('input number:')
num = int(num)
f = open('text.txt','r')
f.close
f2 = open('test.jpg','rb')
s = f.read(5)
s = f.readline(20)
s = f.readlines()
f = open('temp.txt','w')
f.write('hello')
f.close()
lines = ['hello\n','mango\n’,‘cheng\n']
f.writelines(lines)
f.close()
f = open('test.txt','a')
f = open('text.txt','a+')
f.readlines()
f.seek(0)
f.readlines()
with open('test.txt','r') as f:
pass
6.网络编程
服务端:新增Socket、绑定ip和端口、监听连接、接受连接
客户端:新增Socket、连接服务端
import socket
server = socket.socket()
server.bind('127.0.0.1',8080)
server.listen(5)
connect,address = server.accept()
print('connect addr:{}'.format(address))
content = connect.recv(1024)
print(str(content,encoding='utf-8'))
connect.close()
import socket
client = socket.socket()
client.connect('127.0.0.1',8080)
client.send(bytes('hello world',encoding='utf-8'))
client.close()
python -m http.server
python -m http.server 8080 -d D:/
from urllib import request
response = request.urlopen('http://www.baidu.com')
print(response)
import request
response = request.get('http://www.baidu.com')
print(response)
content = str(response.content,encoding = 'utf-8')
content_list = content.split('\n')
for line in content_list:
if 'www' in line:
print(line.strip())
7.函数式编程
编程范式
允许有变量,支持高阶函数(函数可作为变量),支持闭包(可返回函数),支持匿名函数
def add(x,y,f):
return f(x) +f(y)
add(2,3,abs)
map(f,list)
for item in map(abs,[-1,2,-3]):
print(item)
def prod(x,y):
return x*y
print(reduce(prod,[1,3,5,7,9]))
import math
def f(x):
r = int(math.sqrt(x))
if r*r == x:
return True
else:
return False
for item in filter(f,range(1,101)):
print(item)
sorted([23,12,25,66])
score = [('Alice',23),('Coco',12),('Bob',25),('Dog',66)]
sorted(score)
def k(item):
return item[1]
sorted(score,key = k, reverse=True)
def k(item):
return item.lower()
names = ['Bob','Alice','coco']
sorted(names,key = k)
def f():
def sub_f():
print('call sub_f')
return sub_f
def cal_prod(l):
def prod(x,y):
return x*y
def all_prod():
return reduce(prod,l)
return all_prod
l = [1,2,3]
f = cal_prod(l)
print(f())
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
fs.append(f)
return fs
f1, f2, f3 = count()
def count():
fs = []
for i in range(1, 4):
def f(j):
print('j={}'.format(j))
def g():
return j*j
return g
r = f(i)
fs.append(r)
return fs
f1, f2, f3 = count()
print(f1(), f2(), f3())
lambda x:x*x
from functools import reduce
reduce(lambda x, y: x + y, [1,3,5,7,9])
l = ['bob','Alice','Coco']
print(sorted(l,key=lambda x: x.lower()))
f = decorate(f)
@
def int2(x, base=2):
return int(x, base)
import functools
int2 = functools.partial(int, base=2)
sorted_ignore_case = functools.partial(sorted, key=lambda item: item.lower())
sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)