Python教程

Python操作笔记

本文主要是介绍Python操作笔记,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

# -- coding: utf-8 --

# print('Hello python!')

# print(1 * 1)

# print('hello ' + ' python')

# print('hello' * 8)

# print('hello\n' * 8)

# print('hello\n' +8)

# print('------猜数字游戏------')

# temp = input('请猜数字:')

# guess = int(temp)

# if guess == 8:

# print('恭喜你,猜中了!')

# else:

# print('猜错了')

# print('游戏结束')

# print(1+1)#2

# print(1*2)#2

# print(1/2)#0.5

# print(7%5)#2

# print(7//5)#1

# print(2**2)#4

# print(type(3))

# print(type('str'))

# print('二进制',0b11)

# print('八进制',0o176)

# print('十六进制',0xff)

# a = input('请输入第一个数字:')

# b = input('请输入第二个数字:')

# print(int(a)+int(b))

# a = b = c = d = 20

# print(a, b, c, d)

# f1 = False

# f2 = True

# print(f1 + f2)

# print(f1 - f2)

# name = 'lzx'

# age = 23

# print(type(name), type(age))

# print('我叫' + name + ',今年' + str(age) + '岁')

# print('aaa')

# s1 = '123'

# s2 = '12.3'

# print(int(s1))

# print(f(3))

# 列表堆栈

# stack = [3, 4, 5, 6, 7]

# print(stack)

# # [3, 4, 5, 6, 7]

# stack.pop()

# # 7

# print(stack)

# # 4, 5, 6]

# stack.pop()

# # 6

# stack.pop()

# # 5

# print(stack)

# # [3, 4]

# from collections import deque

# deque = deque(['aa', 'bb', 'cc'])

# deque.append('dd')

# print(deque)

# deque.popleft()

# print(deque)

# deque.popleft()

# print(deque)

# from typing import List

# matrix: List[List[int]] = [

# [1, 2, 3, 4],

# [5, 6, 7, 8],

# [9, 10, 11, 12]]

# # print(matrix)

# # 转置行列

# print(list(zip(*matrix))) # [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

# # 删除指定列表元素,或者清空列表

# a = [1, 3, 4, 5]

# del a[1]

# print(a)

# del a[:]

# print(a)

# list1 = list(range(2, 10))

# print(list1)

# 元组

# t = 'aa', 'dd', 'a1'

# print(t)

# u = t, ('cc', 'gg')

# print(u)

# 求偶数和

# a = 1

# sum1 = 0

# while a <= 100:

# if a % 2 == 0:

# sum1 += a

# a += 1

# print(sum1)

# # 求奇数和

# a = 1

# sum1 = 0

# while a <= 100:

# if a % 2:

# sum1 += a

# a += 1

# print(sum1)

# 求数列和

# a = 1

# sum1 = 0

# while a <= 100:

# sum1 += a

# a += 1

# print(sum1)

# 集合

# basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

# # print(basket) # {'orange', 'banana', 'apple', 'pear'} 集合没有重复的

# # # 字典

# tel = {'jack': 1990, 'age': 50}

# # print(tel) # {'jack': 1990, 'age': 50}

# # print(tel['jack']) # 1990 以关键字作为索引

# # dict() 构造函数可以直接用键值对序列创建字典

# kel = dict([('sade', 4139), ('guido', 4127), ('tony', 4098)])

# print(kel)

# # 在字典中循环时,用 items() 方法可同时取出键和对应的值

# # for k, v in kel.items():

# # print(k, v)

# # 在序列中循环时,用 enumerate() 函数可以同时取出位置索引和对应的值:

# for i, k, in enumerate(kel.items()):

# print(i, k)

# # 同时循环两个或多个序列时,用 zip() 函数可以将其内的元素一一匹配

# for q, a in zip(tel, kel):

# print('What is your {0}? It is {1}.'.format(q, a))

# # 按指定顺序循环序列,可以用 sorted() 函数,在不改动原序列的基础上,返回一个重新的序列:

# for i in sorted(tel):

# print(i)

# # 使用 set() 去除序列中的重复元素。使用 sorted() 加 set() 则按排序后的顺序,循环遍历序列中的唯一元素:

# for f in sorted(set(basket)):

# print(f)

# for i in range(1, 5):

# for j in range(1, 6):

# print('*', end='\t')

# print()

# for i in range(1, 10):

# for j in range(1, i + 1):

# print(i, '*', j, '=', i * j, end='\t')

# print()

# list = [{

# 'rating': [9.7, 20244],

# 'id': '13131',

# 'type': ['犯罪', '剧情'],

# 'title': '肖生克的救赎',

# 'actors': ['蒂姆·罗宾斯', '摩根·弗里曼']

# }, {

# 'rating': [9.6, 27114],

# 'id': '13211',

# 'type': ['爱情', '剧情'],

# 'title': '逃学威龙',

# 'actors': ['周星驰', '吴孟达']

# }, {

# 'rating': [9.1, 23432],

# 'id': '13441',

# 'type': ['恐怖', '魔幻'],

# 'title': '海盗',

# 'actors': ['斯蒂芬', '洛夫斯']

# }]

# name = input('请输入演员姓名:')

# for item in list:

# # print(item['actors'])

# for actors in item['actors']:

# if name == actors:

# print(name, '出演了', item['title'])

# try:

# a = int(input('请输入第一个数'))

# b = int(input('请输入第二个数'))

# result = a / b

# print('结果为:', result)

# except ZeroDivisionError:

# print('除数不允许为0')

# except ValueError:

# print('只能输入数字')

# print('程序结束')

# try:

# a = int(input('请输入第一个数'))

# b = int(input('请输入第二个数'))

# result = a / b

# except BaseException as e:

# print('出错了', e)

# else:

# print('结果为:', result)

# finally:

# print('无论是

# 否产生异常,都执行')

# print('程序结束')

# 利用traceback打印异常信息

# import traceback

# try:

# print("-----")

# print(1 / 0)

# except:

# traceback.print_exc()

# i = 1

# while i <= 10:

# print(i)

# i += 1

# print(id(Student)) # 140420918074560

# print(type(Student)) # <class 'type'>

# print(Student) # <class 'main.Student'>

# class Student:

# native_pace = '梅州'

# # 包含实例属性:self.name 进行赋值操作 局部变量赋值给实例属性

# def init(self, name, age):

# self.name = name

# self.age = age # 不希望被类的外部被使用 加

# def pri(self):

# print(self.name, self.__age)

# # 定义在类里面的叫实例方法

# def eat(self):

# print(self.name + '吃饭')

# # 静态方法

# @staticmethod

# def method():

# print('我使用的静态方法,参数无self')

# # 类方法

# @class method

# def cmd(cls):

# print('我使用的是类方法,参数为cls')

# def drink(): # 定义在类外的叫函数

# print('喝水')

# 类的封装

# stu5 = Student('老八', 20)

# stu5.pri()

# print(stu5.name)

# # print(stu5.__age) # 无法在类外使用

# print(dir(stu5)) # 列举可以类里可以使用的方法或属性

# print(stu5._Student__age) # 20 可以访问但不建议访问

# 类的继承

# 定义父类

# class Person(object):

# def init(self, name, age):

# self.name = name

# self.age = age

# def info(self):

# print('姓名:{0},年龄:{1}'.format(self.name, self.age))

# ##定义子类

# class Teenage(Person):

# def init(self, name, age, score):

# super().init(name, age)

# self.score = score

# def info(self):

# super().info()

# print('学分' + self.score)

# ###测试

# stu6 = Teenage('jack', 20, '99')

# stu6.info()

# # 多继承 C=>A,B=>object

# class A(object):

# pass

# class B(object):

# pass

# class C(A, B):

# pass

# 类的多态 类具有多种形态,即便不知道变量所引用的对象是什么类型,任可以通过这个变量调用方法,在运行过程中,动态决定调用对象中的方法

# class Animal(object):

# def eat(self):

# print('动物要吃东西')

# class Dog(Animal):

# def eat(self):

# print('狗吃肉')

# class Cat(Animal):

# def eat(self):

# print('猫吃鱼')

# class Person(Animal):

# def eat(self):

# print('人吃五谷杂粮')

# def fun(animal):

# animal.eat()

# fun(Dog())

# fun(Cat())

# fun(Person())

# print(id(stu1)) # 4496979792

# print(type(stu1)) # <class 'main.Student'>

# print(stu1) # <main.Student object at 0x10c0a7750> 输出为16进制对象的内存地址

# print('-----------------')

# print(id(Student)) # 140420918074560

# print(type(Student)) # <class 'type'>

# print(Student) # <class 'main.Student'>

# stu1 = Student('张三', 20)

# 创建完实例对象,则可以使用类里面的方法

# print(stu1.name)

# print(stu1.age)

# 调用方法有两种

# 1、实例对象名+类方法

# stu1.eat()

# 2、类名+类方法+传入实例对象

# Student.eat(stu1)

# stu2 = Student('李四', 23)

# stu3 = Student('王五', 18)

# print(stu2.native_pace)

# print(stu3.native_pace)

# # 深修改

# Student.native_pace = '深圳'

# print(stu2.native_pace)

# print(stu3.native_pace)

# # 浅修改

# stu2.native_pace = '广州'

# print(stu2.native_pace)

# print(stu3.native_pace)

# # 调用类方法和实例方法

# Student.cmd()

# Student.method()

# # 动态绑定方法和属性

# def show():

# print('我是函数,但是我变成被动态绑定的方法')

# stu4 = Student('老刘', 99)

# stu4.gender = '男' # 动态绑定性别属性

# # print(stu4.name, stu4.age, stu4.gender)

# stu4.show = show # 动态绑定方法

# stu4.show()

# print('---------------')

# stu1.eat()

# stu2.eat()

# stu3.eat()

# stu4.eat()

# stu1.show() 只给stu4绑定了函数,不能给其他实例对象共享

# class Car:

# def init(self, brand):

# self.brand = brand

# def start(self):

# print(self.brand + '汽车启动')

# car = Car('梅塞奥斯')

# car.start()

# class A(object):

# pass

# class B(object):

# pass

# class C(A, B):

# def init(self, name, age):

# self.name = name

# self.age = age

# class D(A):

# pass

# x = C('jack', 20)

# print(x.dict) # 实例对象的属性字典 {'name': 'jack', 'age': 20}

# print(C.dict) # 类对象属性和方法字典 {'module': 'main', 'init': <function C.init at 0x10429e050>, 'doc': None}

# print('-------------')

# print(x.class) # 列出该实例对象所属的类对象 <class 'main.C'>

# print(C.bases) # 列出继承的类对象 (<class 'main.A'>, <class 'main.B'>)

# print(C.base) # 列出继承的第一个类 <class 'main.A'>

# print(C.mro) # 列出该类继承继承层次结构

# print(A.subclasses()) # 列出子类 [<class 'main.C'>, <class 'main.D'>]

# a = 10

# b = 20

# c = a + b

# print(c)

# d = a.add(b)

# print(d)

# class Student(object):

# def new(cls, *args, **kwargs):

# print('__new__被调用执行,cls的id值为:{0}'.format(id(cls)))

# obj = super().new(cls)

# print('创建对象得到id为:{0}'.format(id(obj)))

# return obj

# def init(self, name, age):

# print('__init__被调用执行,self的id值为:{0}'.format(id(self)))

# self.name = name

# self.age = age

# print('object这个的对象的id为:{0}'.format(id(object)))

# print('Student这个的对象的id为:{0}'.format(id(Student)))

# # 创建Student类的实例对象

# p1 = Student('张三', 20)

# print('p1这个Student类的实例对象的id为:{0}'.format(id(p1)))

# class CPU:

# pass

# class Disk:

# pass

# class Computer:

# def init(self, cpu, disk):

# self.cpu = cpu

# self.disk = disk

# # 变量的赋值

# cpu1 = CPU() # cpu1 {16位内存地址} => {CPU实例对象 包含 ID:0x101619710 type:value:} => {CPU类对象}

# cpu2 = cpu1

# print(cpu1) # <main.CPU instance at 0x101619710>

# print(cpu2) # <main.CPU instance at 0x101619710>

# # 类的浅拷贝 拷贝后源对象与子对象指向同一个子类对象

# print('---------------')

# disk = Disk() # 创建一个硬盘类对象

# computer = Computer(cpu1, disk) # 创建一个计算机类对象

# import copy

# computer2 = copy.copy(computer)

# print(computer, computer.cpu, computer.disk) # <main.Computer object at 0x109adb4d0> <main.CPU object at 0x109acb790> <main.Disk object at 0x109adb450>

# print(computer2, computer2.cpu, computer2.disk) # <main.Computer object at 0x109adb650> <main.CPU object at 0x109acb790> <main.Disk object at 0x109adb450>

# # 深拷贝 拷贝源对象子对象

# computer3 = copy.deepcopy(computer)

# print('---------------')

# print(computer, computer.cpu, computer.disk) # <main.Computer object at 0x109adb4d0> <main.CPU object at 0x109acb790> <main.Disk object at 0x109adb450>

# print(computer3, computer3.cpu, computer3.disk) # <main.Computer object at 0x109adb910> <main.CPU object at 0x109add090> <main.Disk object at 0x109add1d0>

# import math

# print(id(math))

# print(type(math))

# print(math)

# print(math.pi)

# print(dir(math))

# print(math.pow(2, 3), type(math.pow(2, 3)))

# 导入自定义模块,并使用 选中根目录,选择mark directory as 变成更路由

# import demo2

# from demo2 import add

# print(add(2, 10))

# 包 包+模块 可以避免模块名冲突,

# 导包

# import python_package.moudle_a as ma

# print(ma.a)

# import imp

# import sys # 与Python解释器及其环境相关的数据

# import time # 提供与时间相关的各种函数的标准库

# import os # 提供了访问操作系统服务功能的标准库

# import calendar # 提供了与日期相关的各种函数的标准库

# import urllib.request # 提供了用于读取来自网上(服务器)的数据标准库

# import json # 提供了使用json序列化和反序列化对象

# import re # 用于在字符串中执行正则表达式匹配和替换

# import math # 提供了标准算术运算函数的标准库

# import decimal # 用于进行精确控制运算精度、有效数位和四舍五入操作的十进制运算

# import logging # 提供了灵活的记录事件、错误、警告和调试信息等日志的功能

# print(sys.getsizeof(11))

# print(sys.getsizeof(True))

# print(sys.getsizeof('44'))

# print(time.time())

# print(time.localtime(time.time()))

# print(urllib.request.urlopen('http://www.baidu.com').read())

# 第三方模块的使用 例如日程模块 1、pip3 install schedule 2、进入python3 3、输入import schedule

# 实现定时发送邮件:办公自动化

# import schedule

# import time

# def job():

# print('哈哈----')

# schedule.every(3).seconds.do(job)

# while True:

# schedule.run_pending()

# time.sleep(1)

# 编码问题 utf-8 unicode

# print('你好中国')

# 文件读写原理 文件读写操作为io操作 解释器解释py文件 => 硬盘

# 打开并读取

# file = open('a.txt', 'r')

# print(file.readlines())

# file.close()

# #创建并写入

# file = open('b.txt', 'w')

# file.write('python')

# file.close()

# #创建或追加

# file = open('b.txt', 'a')

# file.write('python')

# file.close()

# #二进制打开文件,需要与其他模式使用 实现文件的复制

# src_file = open('logo.png', 'rb') # 以二进制形式打开文件源文件,并标记为二进制读取文件

# target_file = open('copylogo.png', 'wb') # 以二进制打开复制的文件,并标记为以二进制写入

# target_file.write(src_file.read())# 复制文件读取源文件,边写边读取

# target_file.close() # 关闭有效资源

# src_file.closs() # 关闭有效资源

# with管理上下文

# 优化资源的链接以及文件操作

# class Resource():

# def enter(self):

# print('===connect to resource')

# return self

# def exit(self, exc_type, exc_val, exc_tb):

# print('=close resource connection=')

# def operate(self):

# print('=in operation=')

# with Resource() as res:

# res.operate()

# #优化处理异常,增加程序可读性

# class mytry():

# def enter(self):

# print('=connet to resource=')

# return self

# def exit(self, exc_type, exc_val, exc_tb):

# print('=close resource connection=')

# return True

# def myError(self):

# 1 / 0

# with mytry() as res:

# res.myError()

# 装饰器

# def my_loging(func):

# def wrapper(*args, **kwargs):

# # args是一个数组,kwargs一个字典

# logging.warn("%s is runing" % func.name)

# return func(*args, **kwargs) # 把foo当做参数传入时,执行func()相当于执行foo()

# return wrapper

# @my_loging

# def foo(name='lzx', age=None, height=None):

# logging.warn("name is %s ,age is %s, height is %s" % (name, age, height))

# foo() # 执行foo()就相当于执行 wrapper()

# 带参数的装饰器

# def use_logging(level):

# def decorator(func):

# def wrapper(*args, **kwargs):

# if level == "warn":

# logging.warn("%s is running" % func.name)

# elif level == "info":

# logging.info("%s is running" % func.name)

# return func(*args)

# return wrapper

# return decorator

# @use_logging(level="warn")

# def foo(name='foo'):

# print("i am %s" % name)

# foo()

# 类装饰器

# class Foo(object):

# def init(self, func):

# self._func = func

# def call(self):

# print('class decorator runing')

# self._func()

# print('class decorator ending')

# @Foo

# def bar():

# print('bar')

# bar()

# 在装饰器中还原类函数信息

# from functools import wraps

# def logged(func):

# @wraps(func)

# def with_logging(*args, **kwargs):

# print func.name # 输出 'f'

# print func.doc # 输出 'does some math'

# return func(*args, **kwargs)

# return with_logging

# @logged

# def f(x):

# """does some math"""

# return x + x * x

# Flask 首次使用

# from flask import Flask, render_template # 首先导入Flask扩展,运行模板扩展

# 第一个参数应该使用 name。因为取决于如果它以单独应用启动或作为模块导入, 名称将会不同 ( 'main' 对应于实际导入的名称)

# 我们创建一个该类的实例。我们传递给它模块或包的名称。这样 Flask 才会知道去哪里寻找模板、静态文件等等。

# app = Flask(name)

# # 我们使用装饰器 route() 告诉 Flask 哪个 URL 才能触发我们的函数

# @app.route('/')

# # 定义一个函数,该函数名也是用来给特定函数生成 URLs,并且返回我们想要显示在用户浏览器上的信息。

# def hello_world():

# return 'Hello 424!'

# @app.route('/', methods=['GET', 'POST']) # 默认是get,可增加指定方式请求

# def index():

# # 浅学jinji2模板

# # 动态传值

# # 在index.html里面插值表达式使用

# url_str = 'ww里面插值表达式使用w.Google.com'

# my_list = [1, 2, 3, 4, 5, 6]

# # return 'Index Page' # 返回文字内容

# return render_template('index.html', url_str=url_str,

# my_list=my_list) # 返回页面模板

"""

目的:实现一个简单登录逻辑处理

1、路由需要有get和post请求=>判断请求方式

2、获取请求参数

3、判断表单是否为空并且确认密码是否相同

4、判断没有问题,返回一个success

"""

# Flask request实现表单验证

# request:请求对象、获取请求方式、数据

# flash:消息传递,注意模板遍历消息-->加密消息,需要摄者secret_key,做加密消息的混淆

# from flask import Flask, render_template, request, flash

# app = Flask(name)

# # 需要摄者secret_key,做加密消息的混淆

# app.secret_key = 'it'

# # 默认是get,可增加指定方式请求

# @app.route('/', methods=['GET', 'POST'])

# def index():

# # 1、请求方式判断

# if request.method == 'POST':

# # 2、获取表单数据

# username = request.form.get('username')

# password = request.form.get('password')

# repassword = request.form.get('repassword')

# # 3、判断表单密码是否相同

# if not all([username, password, repassword]):

# # print('参数不完整')

# flash(u'参数不完整')

# elif (password != repassword):

# # print('密码不一致')

# flash(u'密码不一致')

# else:

# return 'success'

# return render_template('index1.html') # 返回页面模板

# Flask

# 利用flask-wtf做表单验证

# 自定义表单类

# from flask import Flask, render_template, request, flash # request:请求对象、获取请求方式、数据

# # 导入第三方库里面的表单验证

# from flask_wtf import FlaskForm

# # 导入扩展表单验证函数

# from wtforms.validators import DataRequired, EqualTo

# # 支持的HTML库字段

# from wtforms import StringField, PasswordField, SubmitField

# app = Flask(name)

# app.secret_key = 'it'

# # 自定义表单类

# class loginForm(FlaskForm):

# username = StringField('用户名:', validators=[DataRequired()])

# password = PasswordField('密码:', validators=[DataRequired()])

# repassword = PasswordField(

# '确认密码:', validators=[DataRequired(),

# EqualTo('password', '两次密码不一致')])

# submit = SubmitField('提交')

# @app.route('/', methods=['GET', 'POST'])

# def login():

# login_form = loginForm()

# # 1、请求方式判断

# if request.method == 'POST':

# # 2、获取表单数据

# username = request.form.get('username')

# password = request.form.get('password')

# # repassword = request.form.get('repassword')

# # 3、flask-wtf验证参数 需要在模板开启token验证

# if login_form.validate_on_submit():

# print(username, password)

# return 'success'

# else:

# flash('参数有误') # 记得在模板放置flash容器

# return render_template('index2.html', form=login_form)

# # 需求1、使用同一个视图函数,来显示不同用户的订单信息

# # <>丁一路有参数,<>内需要起个名字

# # 需求2、订单参数优化,id应该为id类型

# # int:oreder_id

# @app.route('/orders/int:oreder_id')

# def get_order_id(oreder_id):

# print(type(oreder_id))

# # 需要在视图函数的括号内,填入参数名,后面才能使用

# return 'order_id %s' % oreder_id

# url与函数映射

from flask import Flask, jsonify, url_for, request, redirect # jsonify 得到数据,将其转变为json数据格式;url_for 获取函数的url,并可以进行json数据复制。添加新的字段给json对象;redirect重定向制定网页

import flask_config # 导入配置文件 集合所有自定义配置

app = Flask(name)

app.config.from_object(flask_config) # 使用配置文件

books = [{'id': 1, 'name': '三国演义'}, {'id': 2, 'name': '水浒传'}, {'id': 3, 'name': '红楼梦'}, {'id': 4, 'name': '西游记'}]

# @app.route('/book/list')

# def book_list():

# return jsonify(books)

# url与函数进行了一个映射

# 如果只是获取服务器的数据,则一般使用get请求,如果前端需要把数据发送给服务器,则用post请求

# 在路由路径加入参数methods,限制请求方式

@app.route('/book/detail/string:book_id', methods=['GET', 'POST'])

def book_detail(book_id):

for book in books:

if book_id == str(book['id']):

return book

return f'不存在id为: {book_id} 的书本'

# url重构:url随时会根据需求变化,因此使用url_for()动态改变url地址

@app.route("/book/list")

def book_list():

for book in books:

# url_for() 第一个参数为目标函数名,将其路由转换为url,第二个参数为关键字 需要填入url后置,参数的多少。与目标函数所绑定的url相匹配

book['url'] = url_for('book_detail', book_id=book['id'])

return jsonify(books)

@app.route("/profile")

def profile():

# 获取用户在接口输入的url

user_id = request.args.get('id')

# 参数传递的两种方式:

# 1、作为url的组成部分:/book/1

# 2、查询字符串:/book?id=1

# print(user_id)

if user_id:

return "用户个人中心"

else:

return redirect(url_for("index"))

@app.route('/')

def index():

return "首页"

# if name == 'main':

# 确保服务器只会在该脚本被 Python 解释器直接执行的时候才会运行,而不是作为模块导入的时候。

if name == 'main':

# 最后我们用函数 run() 启动本地服务器来运行我们的应用

app.debug = True

app.run() # 按 control-C 来停止服务器。

这篇关于Python操作笔记的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!