python 从入门到实战(基础知识复习和回顾)

原创:叫我詹躲躲 来源:掘金 连接:juejin.im/post/5f05e1…python

1编写第一个程序(python 3)

print('hello world!')
复制代码

2.查看python 版本号

python -v
复制代码

3.使用变量

message = 'hello world!'
 print(message) 复制代码

4.字符串

name = 'jetty'
print(name.title()) #Jetty 首字母大写 print(name) jetty name.upper() #JEETY 转大写 name.lower() #jetty 转小写 复制代码

5.合并拼接字符串

first_name = 'hongzhu'
last_name = 'zhan' full_name = last_name +" "+ first_name print(full_name) zhan hongzhu 复制代码

6.使用制表来添加空白

language = 'python\nJavascript\nC\nRust'
print(language)   打印 python Javascript C Rust  复制代码

7.删除空白

_blank = ' python '
print(_blank.rstrip()) #去除右侧空白 print(_blank.strip()) #去除两侧空白 print(_blank.lstrip()) #去除左侧空白  复制代码

8.变量类型

num = 2.340
print(int(num)) #整型 2 print(float(num)) #浮点型 2.34 复制代码

9.列表

color = ['red','green','yellow','pink']
 #访问元素 print(color[0]) ##red  #修改 color[0] = 'black'  #添加元素 color.append('orange')  #插入元素  color.insert(0,'blue') #插到第一位 print(color)  #删除元素 del color[0] #删除当前元素  color.pop() #删除数组最后一个元素  color.remove('red') #删除红色  复制代码

10 组织列表

10.1排序列表

num_list = [1,2,3,4,2,1,3,1,2]
num_list.sort() print(num_list) [1, 1, 1, 2, 2, 2, 3, 3, 4] 复制代码

10.2临时排序

num_list = [1,2,3,4,2,1,3,1,2]
print(sorted(num_list)) [1, 1, 1, 2, 2, 2, 3, 3, 4] 复制代码

10.3reverse 反序

num_list = [1,2,3,4,2,1,3,1,2]
num_list.reverse() print(num_list) [2, 1, 3, 1, 2, 4, 3, 2, 1] 复制代码

10.4列表的长度

num_list = [1,2,3,4,2,1,3,1,2]
print(len(num_list)) 9 复制代码

11 遍历列表

num_list = [1,2,3,4,2,1,3,1,2]
for i in num_list:  print(i,end=" ") #一行显示 复制代码

12.使用函数遍历

num_list = [1,2,3,4,2,1,3,1,2]
for i in range(len(num_list)):  print(num_list[i],end=" ")  复制代码

13.乘方运算

squares = []
for i in range(1,6):  squares.append(i**2) print(squares) [1, 4, 9, 16, 25]  复制代码

14.内置函数

num_list = [1,2,3,4,2,1,3,1,2]
print(max(num_list)) 4 print(min(num_list)) 1 print(sum(num_list)) 19  复制代码

15.列表解析

squeres = [value**2 for value in range(1,11)]
print(squeres) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 复制代码

16.练习示例

16.1 1-50奇数的和

odd_number =[]
for i in range(1,11,2):  odd_number.append(i) print(sum(odd_number)) 复制代码

16.2 3-90 3的倍数

three_nmu = []
for i in range(3, 91):  if (i % 3==0):  three_nmu.append(i) print(three_nmu) 复制代码

16.3 1-10 的立方

squares = []
for i in range(3,11):  squares.append(i**3) print(squares) 复制代码

16.4 1-10 的立方列表解析

squares = [i**3 for i in range(3,11)]
print(squares) 复制代码

17 列表切片

num_list = [1,2,3,4,2,1,3,1,2]
 print(num_list[0:5]) [1, 2, 3, 4, 2] #从第一个开始取值到第五位 print(num_list[:5]) [1, 2, 3, 4, 2] #默认会从第一个开始取值 print(num_list[5:]) [1, 3, 1, 2] #取后面的4位  复制代码

18 元组

dimensions = (100,300)
print(dimensions[0]) 100  for i in dimensions:  print(i) 100 300 复制代码

19 if 语句

num_list = [1, 2, 3, 4, 2, 1, 3, 1, 2]
for i in num_list:  if i == 2:  print(i) 复制代码

20 !=

num_list = [1, 2, 3, 4, 2, 1, 3, 1, 2]
for i in num_list:  if i != 2:  print(i) 复制代码

21 and

num_list = [1, 2, 3, 4, 2, 1, 3, 1, 2]
for i in num_list:  if i >=1 and i <=2:  print(i) 复制代码

22 字典

alien  = {'color':0,'points':1}
print(alien['color']) ##color 复制代码

23 修改字典

alien  = {'color':0,'points':1}
alien['color'] = 'red' print(alien) {'color': 'red', 'points': 1} 复制代码

24 删除字典

alien  = {'color':0,'points':1}
del alien['color'] print(alien) 复制代码

25 案例练习

25.1建立两我的的字典,存储在列表,遍历列表,输出列表

people_nums1 = {'name':'jetty','name1':'jack'}
people_nums2 ={'name':'kitty','name1':'james'} peoples = [people_nums1,people_nums2] for i in peoples:  print(i) 复制代码

26.用户输入和while循环

ipt = input('你是小黄么?1(true) or 2(false)?')
if ipt =='1':  print('是本人') else:  print('不是本人')  复制代码

27 % //运算符

print(4 % 2)   0
print(4 // 2) 2 复制代码

28 while运算符

count = 0
arr = [] while count < 20:  for j in range(1, 100):  if j % 11 == 0:  count = count+1  arr.append(j) print(arr) 复制代码

29 函数

#简单求和
def num_sum(arr):  result =0  for i in arr:  result =result+i  return result  print(num_sum([1,2,3,4])) 10 复制代码

30 函数默认值

def num_sum(arr=[1,2,3]):
 result =0  for i in arr:  result =result+i  return result  print(num_sum()) 6 复制代码

31 传递任意数量的实参

def make_prize(*top):
 return top  print(make_prize(1)) print(make_prize(1,2,3)) print(make_prize(1,3,4,5)) print(make_prize(1,1,1,1,1))  #返回 (1,) (1, 2, 3) (1, 3, 4, 5) (1, 1, 1, 1, 1) 复制代码

32 导入函数

# 随机数
import random print(random.randint(1,19)) 复制代码

33 类

class Dog():
 def __init__(self,name,age):  self.name =name  self.age = age   def sit(self):  print(self.name+''+self.age)  dog = Dog('jeety',24) print(dog.name)  复制代码

34 类 汽车里程表

class Car():
 def __init__(self,make,model,year):  self.make = make  self.model = model  self.year = year   def getCarName(self):  print(self.model)  car = Car('audi','ad4',2016) print(car.make) 复制代码

35 子类方法 init()

class Car():
 def __init__(self,name):  self.name = name  class Elastic(Car):  def __init__(self, name):  super().__init__(name)  myTesla = Elastic('tesla') print(myTesla.name)  复制代码

36 class实例

class Car():
 def __init__(self,make,name,color):  self.make = make  self.name = name  self.color = color   def getCarName(self):  print('获取车的名字为'+self.name+'获取汽车的颜色'+self.color)  class Batery():  def __init__(self,batery='60'):  self.batery = batery   def discribe_batery(self):  print('This car has'+str(self.batery)+'batery')  class Elatrity(Batery):  def __init__(self, batery):  super().__init__(batery)  self.batery = Batery()  elatrity = Elatrity('100') print(elatrity.discribe_batery()) 复制代码

37 文件和异常

f = open('file.txt',mode="w",encoding='utf-8')
print(f) f.write('叫我詹躲躲\n') f.write('叫我詹躲躲1\n') f.close()  复制代码

38 将数据存入json文件

import json
numbers = [1,2,23,3,4,5,6,7,87]  filename = 'numbers.json' with open(filename,'w') as f_obj:  json.dump(numbers,f_obj)  复制代码

39 保存和读取用户生成的数据

import json
username = input('存储输入的数据')  filename = 'numbers.json' with open(filename,'w') as f_obj:  json.dump(username,f_obj)  复制代码

40 读取用户输入的信息

import json
filename = 'numbers.json' with open(filename) as f_obj:  username = json.load(f_obj)  print('Welcome back',username)  复制代码

41 输入和合并数据

import json
filename = 'numbers.json' try:  with open(filename) as f_obj:  username = json.load(f_obj) except FileNotFoundError:  username = input('存储输入的数据')  with open(filename,'w') as f_obj:  json.dump(username,f_obj) else:  print('Welcome back',username)  复制代码

42 封装成为一个函数

import json
def get_username():  filename = 'numbers.json'  try:  with open(filename) as f_obj:  username = json.load(f_obj)  except FileNotFoundError:  return None  else:  return username def get_greeting():  username = get_username()  if username:  print('Welcome back',username)  else:  username = input('存储输入的数据')  filename = 'numbers.json'  with open(filename,'w') as f_obj:  json.dump(username,f_obj)  print('Welcome back',username)  get_greeting() 复制代码

43 文件读取

f = open('index.txt',encoding='utf-8')
s = f.read() print(s) f.close() 复制代码

44 文件写入

f = open('index.txt',mode="w",encoding='utf-8')
f.write('叫我詹躲躲n') f.write('叫我詹躲躲1n') f.close() 复制代码

43 第三方库安装和使用

import random
random.randint() #随机数 import jieba #结巴 import wordcloud #词云  jieba.lcut('分割中文词语的序列') #分割中文词语的序列 word_cloud = wordCloud(font_path='msyh.ttc').generate('分割中文词语') #生成词云对象 word_cloud.to_file('123.png') #保存到图片 复制代码

44 python 里面的类和对象

#面向对象编程
class Person:  def __init__(self,name,sex,birthday):  self.name = name  self.sex = sex  self.birthday = birthday  def say(self,word):  print(f'{self.name}说:"{word}"')  zhang_san = Person('张三','男','2020202') zhang_san.say('12121') 复制代码

45.输出 %占位符

lastname = 'hello'
firstname = 'world' print('个人名字是%s %s' %(lastname,firstname)) 复制代码

46.经常使用的格式化字符

%c #字符
%s #经过str来格式化 %i #有符号十进制整数 %d #有符号十进制整数 %u #无符号十进制整数 %o #八进制整数 %x #十六进制整数(小写字母) %e #索引符号(小写e) %E #索引符号(大写E) %f #浮点实数 %g #%f和%e的简写 %G #%f和%E的简写 复制代码

47 格式化的其余方式 format

name = '老夫子'
age = 28 print('姓名:{},年龄{}'.format(name,age)) #姓名:老夫子,年龄28  复制代码

48 .匿名函数

48.1lambda 参数1,参数2,参数3:表达式

#特色:
#1.使用lambda关键字建立函数 #2.没有名字的函数 #3.匿名函数冒号后面的表达式有且只有一个,是表达式不是语句 #4.自带return  复制代码

48.2.lambda 示例1

def computer(x,y):
 #计算两数和  return x+y  M = lambda x,y:x+y print(M(1,2)) 复制代码

48.3.lambda 示例1

result = lambda a,b,c:a*b*c
print(result(12,121,1)) 复制代码

48.4 lambda 三元表达式模拟

age = 15
print('能够参军' if age>18 else '继续上学')  #直接调用 result = (lambda x,y:x if x>y else y)(2,5) 复制代码

49.递归函数

#阶乘函数
def factorial(n):  if n==1:  return 1  else:  return n*factorial(n-1)  pass  print(factorial(3)) 复制代码

49.1 递归案例 模拟实现 树形结构的遍历

import os 文件操做模块
def findFile(file_path):  listRs = os.listdir(file_path) 获得该路径全部的文件夹  for fileItem in listRs:  full_path = os.path.join(file_path,fileItem)  if os.path.isdir(full_path): 判断是否为文件夹  findFile(full_path)  else:  print(fileItem)  pass  pass  else:  return findFile('F:\\7.代码学习') 复制代码

50.python的内置函数

abs(-27) #绝对值
round(21.1123) #浮点近似值 pow(2,3) #幂 2**3 divmod(10,3) # 商余 max(1,2,3,4) #最大值 min(1,2,3,4) #最小值 sum(1,2,3,4) #求和 eval() #动态执行表达式 复制代码

51.类型转换函数

int #整型
float #浮点型 str #字符类型 ord #返回对应字符的ASCII chr #数字转字符 ASCII bool #boolean bin # 转换二进制 hex #转换为十六进制 oct #八进制 list #元祖转列表 tuple #元祖 dict #建立字典 bytes #转为字节  复制代码

52.可迭代参数 all

#all 用于断定给定的可迭代参数中的全部元素是否都为TRUE,若是是返回TRUE,不然返回FALSE,除了0,空,False 外都算TRUE
 def all(iterable):  for ele in iterable:  if not ele:  return False  return True  li = [1,2,3,4,5,6,False] print(all(li)) ##False 复制代码

53 可迭代参数 any

#所有为false,返回false
def any(iterable):  for ele in iterable:  if ele:  return False  return True  li = [0,False,''] print(any(li)) ##False  复制代码

54.enumerate 列出遍历数据和下标

li = ['a','b','c']
for index,item in enumerate(li,7):  print(index,item)  #改下标 7 a 8 b 9 c 复制代码

55.set集合 不支持索引和切片,无序不重复

55.1.建立集合1

set1 = {'1','2'}
set2 = {'11','1'} #添加 add set1.add('3')  #清空 clear() set1.clear()  #取差集 difference set1.difference(set2) ##set1取set1中有的  #取交集 set1.intersection(set2)  #取并集 set1.union(set2) set1 | set2  #末尾移除 set1.pop()  #指定移除 set1.discard(3)  #更新 update 合并一块儿去重 set1.update(set2) 复制代码

55.2 练习题1 三组数据求和

1-10,20-3035-40
def threeSum(a1,a2,a3):  return sum(a1+a2+a3)  a1 = list(range(1,11)) a2 = list(range(20,31)) a3 = list(range(35,41)) print(threeSum(a1,a2,a3)) 复制代码

55.3练习题2 大小和尚多少个

def computers():
 for i in range(1,101):  for j in range(1,34):  if i+j==100 and 3*j+i/3 ==100:  print('大和尚有{}个,小和尚有{}个'.format(j,i))  pass computers()  #大和尚有25个,小和尚有75个 复制代码

55.4 练习题3 找出独一无二的数据

li = [1,1,1,2,2,2,2,3,2,2,3,4,2,1,1]
def findUnionNumber(li):  for item in li:  if li.count(item)==1:  return item  pass print(findUnionNumber(li)) 复制代码

56.字典统计每一个元素的次数

dict ={}
for key in li:  dict[key] = dict.get(key,0)+1 print(dict)  复制代码

56.1.collection包下Counter类统计

from collections import Counter
a = [1, 2, 3, 1, 1, 2] result = Counter(a) print(result) 复制代码

56.2.pandas包下的value_counts方法统计

import pandas as pd
a = pd.DataFrame([[1,2,3],  [3,1,3],  [1,2,1]]) result = a.apply(pd.value_counts) print(result) 复制代码

56.3.利用set找出独一无二的数据

li = [1,2,3,3,2,3,4,4,5,1,2,1]
def uniqueNum(li):  set1 = set(li)  for i in set1:  li.remove(i)  set2 = set(li)   for j in set2:  set1.remove(j)  return set1  print(uniqueNum(li)) 复制代码

57 面向对象编程 oop

#面向过程编程 根据业务从上到下开始编程
#类的结构 #类名 属性 方法  class People:  name = 'zhan',  age = 20,  def eat(self):  print('正在吃饭')  #建立对象 people = People() people.eat() 复制代码

在类的内部,使用def定义的为实例方法,第一个参数为self,实例方法归实例全部web

57.1 类的实例属性添加

class People:
 name = 'zhan',  age = 20,  def eat(self):  print('正在吃饭')  #建立对象 people = People() people.eat()  #添加属性 people.name2 = 'zhan' people.age2 = 22 复制代码

57.2 类的__init__()方法

class People:
 # 初始化的操做,实例属性,自动执行  def __init__(self):  self.name = 'zhan'  self.age = 20   def eat(self):  print('正在吃饭')  #建立对象 people = People() people.eat() 复制代码

57.3 类的__init__()使用参数

class People:
 # 初始化的操做,实例属性,自动执行  def __init__(self, name, age):  self.name = name  self.age = age   def eat(self,food):  print(self.name+food)  #建立对象 people = People('叫我詹躲躲', 20) people.eat('正在吃饭') people.eat('洗澡') people.eat('跑步')  复制代码

57.4 理解类的self

#相似于js里面的this
class Person:  def eat(self):  print(id(self))  pass  pass  person = Person() person.eat() print(id(person))  #self和对象指向同一个内存地址,self就是对象的引用 # <__main__.Person object at 0x0000020864815CC0>  复制代码

58 魔术方法

#__init__ :初始化实例属性
# __str__ :自定义对象的格式 # __new__ :对象实例化  class Animal:  def __str__(self):  return '3213213123123'  pass  pass animal = Animal() print(animal)   class Animal:  def __str__(self):  return '3213213123123'  pass  pass   def __new__(cls,*args,**kwargs):  print("----new执行---")  return object.__new__(cls) 真正建立对象实例的  pass  animal = Animal() print(animal)   #__new__ 和__init__的区别  #__new__ 类的实例化方法,必须返回实例,不然建立不成功 #__init__数据属性的初始化工做,认为是实例的构造方法,接受实例化self并对其进行构造 #__new__ 至少一个参数是cls,表明要实例化的类 #__new__ 执行要比__init__早 复制代码

59 案例练习 —— 决战紫禁之巅

# 属性:
# name:玩家名称 # blood:血量  # 方法: # tong() 捅一刀,掉10滴血 # kanren() 砍一刀掉15滴血 # chiyao() 补血10滴血 # __str__打印玩家的状态  class Role:  def __init__(self,name,blood):  self.name = name  self.blood = blood  pass   砍人  def tong(self,enemy):  enemy.blood -=10  info = '【%s】捅了【%s】一刀'%(self.name,enemy.name)  print(info)  pass   砍人  def kanren(self,enemy):  enemy.blood -=15  info = '【%s】砍了【%s】一刀'%(self.name,enemy.name)  print(info)  pass   吃药  def chiyao(self):  self.blood +=10  info = '【%s】吃了一口药,增长10滴血'%(self.name)  print(info)  pass  def __str__(self):  return '%s还剩下%s的血量'%(self.name,self.blood)  xmcx = Role('西门吹雪',100) ygc = Role('叶孤城',100)  while True:  if xmcx.blood<=0 or ygc.blood<=0:  break   print('*********************')  xmcx.tong(ygc)  xmcx.kanren(ygc)  print('*********************')  ygc.tong(xmcx)  ygc.chiyao()  print('*********************')  print(xmcx)  print(ygc)  """ ********************* 【西门吹雪】捅了【叶孤城】一刀 【西门吹雪】砍了【叶孤城】一刀 ********************* 【叶孤城】捅了【西门吹雪】一刀 【叶孤城】吃了一口药,增长10滴血 ********************* 西门吹雪还剩下50的血量 叶孤城还剩下25的血量 ********************* 【西门吹雪】捅了【叶孤城】一刀 【西门吹雪】砍了【叶孤城】一刀 ********************* 【叶孤城】捅了【西门吹雪】一刀 【叶孤城】吃了一口药,增长10滴血 ********************* 西门吹雪还剩下40的血量 叶孤城还剩下10的血量 ********************* 【西门吹雪】捅了【叶孤城】一刀 【西门吹雪】砍了【叶孤城】一刀 ********************* 【叶孤城】捅了【西门吹雪】一刀 【叶孤城】吃了一口药,增长10滴血 ********************* 西门吹雪还剩下30的血量 叶孤城还剩下-5的血量 """ 复制代码

60 实例练习1 水果类

class Fruit:
 def __init__(self,name,color):  self.name = name  self.color = color  def showColor(self):  print('%s的颜色为%s'%(self.name,self.color))  apple = Fruit('苹果','红色').showColor() orange = Fruit('橘子','黄色').showColor() watermelen = Fruit('西瓜','绿色').showColor() 复制代码

61 验证self 就是实例自己

class CkeckSelf:
 def __str__(self):  print(id(self))  pass  CkeckSelf().__str__() selfObj = CkeckSelf() print(id(selfObj)) 复制代码

62 定义animal类,输出全部的属性

class Animal:
 def __init__(self, color, name, age):  self.color = color  self.name = name  self.age = age   def run(self):  print('%s在跑步'%(self.name))  pass   def eat(self):  print('%s在吃东西' %(self.name))  pass   def __str__(self):  return '%s岁的%s的%s'%(self.age,self.color,self.name)  cat = Animal('黑色','小猫',2) dog = Animal('白色','小狗',3) cat.run() dog.run()  print(cat) print(dog) """ 小猫在跑步  小狗在跑步  2岁的黑色的小猫  3岁的白色的小狗 """ 复制代码

64 简易的学生管理系统

1、显示全部学生信息
2、新建学生信息 3、查询学生信息 4、修改学生信息 5、删除学生信息 0、退出系统 复制代码
student_data = [
 {  'id': 123456,  'name': 'Tom',  'sex': '男',  'address': '迪士尼'  },  {  'id': 123457,  'name': 'Jerry',  'sex': '女',  'address': '伦敦'  }, ] 复制代码

64.1美化显示

def beauty_list(datas):
 for index, student in enumerate(datas):  print(f'序号:{index}', end="t")  print(f'姓名:{student["name"]}', end="t")  print(f'性别:{student["sex"]}', end="t")  print(f'地址:{student["address"]}') 复制代码

64.2输入名字

def input_name():
 while True:  name = input('输入名字:').strip()  if name:  return name  else:  continue 复制代码

64.3选择性别

def choose_sex():
 print('1(男) | 2(女)')  n = input('选择性别')  if n == '1':  return '男'  else:  return '女' 复制代码

64.4显示全部学生信息

def show_all():
 beauty_list(student_data) 复制代码

64.5新建学生信息

def create_student():
 sid = random.randint(1000, 10000)  name = input_name()  sex = choose_sex()  address = input('地址:')  student = {  'id': sid,  'name': name,  'sex': sex,  'address': address  }   student_data.append(student) 复制代码

64.6查询学生信息

def find_student():
 name = input_name()  for i in student_data:  if i['name'] == name:  print(i)  return  else:  print('无该学生任何信息') 复制代码

64.7修改学生信息

def edit_student():
 name = input_name()  for student in student_data:  if student['name'] == name:  print(student)  student['name'] = input_name()  student['sex'] = choose_sex()  student['address'] = input('地址:')  return  else:  print('查无此人') 复制代码

64.8删除学生信息

def delete_student():
 name = input_name()  for student in student_data:  if student['name'] == name:  student_data.remove(student)  return  else:  print('查无此人')  while True:  print('''  ********************  欢迎使用学生管理系统  一、显示全部学生信息  二、新建学生信息  三、查询学生信息  四、修改学生信息  五、删除学生信息  0、退出系统  ********************   '''  )   op = input('请输入序号:')  if op == '1':  print(student_data)  show_all()  elif op == '2':  create_student()  elif op == '3':  find_student()  elif op == '4':  edit_student()  elif op == '5':  delete_student()  else:  print('退出系统')  break 复制代码

本文使用 mdnice 排版编程

原创:叫我詹躲躲 来源:掘金 连接:juejin.im/post/5f05e1…json

相关文章
相关标签/搜索