python新手菜鸟之基础篇
s=0
for i in range(1,101):
s += i
else:
print(s)
def main(n):
'''打印菱形图形'''
for i in range(n):
print((' * '*i).center(n*3))
for i in range(n,0,-1):
print((' * '*i).center(n*3))
main(6)
#计算理财产品收益
def licai(base,rate,days):
result = base
times = 365//days
for i in range(times):
result = result+result*rate/365*days #假设本金与利息一起滚动
return result
print(licai(100000,0.0543,90)) #多次调用同一函数而产生的bug
def demo(newiten,old_list=[]):
'''如果增加一个判断返回值初始化为默认值时,就不会产生bug
如:if old_list is None: old_list=[]'''
old_list.append(newiten)
return old_list
print(demo('',['','','']))
print(demo('aaa',['a','b']))
#在多次调用函数并不为默认值参数传递值时,默认值参数只
# 在第一次调用时进行解释,这样会导致bug
print(demo('a'))
print(demo('g')) #计算圆的面积
from math import pi as PI
def CircleArea(r):
if isinstance(r,(int,float)):
return PI * r**2
else:
print('Error')
print(CircleArea(3))
#使用lambda表达式,注意其变量的作用域
r=[]
for x in range(10):
r.append(lambda n=x:n**2)#不能直接引用x值,lambda表达式中使用局部变量
print(r[5]())
#类对象的定义
class A:
def __init__(self,value1=0,value2=0):
self._value1 = value1
self.__value2 = value2
def show(self):
print(self._value1)
print(self.__value2)
a = A()
print(a._value1)
print(a._A__value2)
#数据成员定义
class Demo(object):
total = 0
def __new__(cls, *args, **kwargs):#该方法在__init__()之前被调用
if cls.total >= 3:
raise Exception("最多只能创建3个对象")
else:
print('实例化',Demo.total)
return object.__new__(cls)
def __init__(self):
Demo.total = Demo.total + 1
t1 = Demo()
#方法
class Root:
__total =0
def __init__(self,v):
self.___value=v
Root.__total +=1
def show(self):
print('Self:',self.___value)
print('Root:',Root.__total)
@classmethod
def classShowTotal(cls):
'''类方法,只能访问类成员'''
print(cls.__total)
@staticmethod
def staticShowTotal():
'''静态方法,也是只能访问类成员'''
print(Root.__total)
r = Root(3)
Root.classShowTotal()
Root.staticShowTotal()
r.show()
#属性
class Test1:
def __init__(self,value):
self.__value = value
@property #修饰器属性,只读,无法修改和删除
def value(self):
return self.__value
class Test2:
def __init__(self,value):
self.__value = value
def __getValue(self):
return self.__value
def __setValue(self,v):
self.__value = v
value = property(__getValue,__setValue)#设置属性可读可写操作
#继承
class Person:
def __init__(self):
print('this is a parent class')
def setName(self,name):
if not isinstance(name,str):
print('name must be string.')
self.__name = ''
return
self.__name = name
print(self.__name)
#派生类
class Teacher(Person):
def __init__(self):
super(Teacher,self).__init__()#也可以直接用Persion.__init__() def setDepartment(self,department):
#if type(department) != str:
if not isinstance(department,str):
print('department must be string.')
self.__department = 'Computer'
return
self.__department = department
if __name__ == '__main__':
zhangsan = Teacher()
zhangsan.setName('Lisi')
'''探讨继承中的问题,到底基类是否要继承object呢'''
class A:
def foo(self):
print('called A.foo()')
class B(A):
pass
class C(A):
def foo(self):
print('called C.foo()')
class D(B,C):
pass
d = D()
d.foo()#A类继承object,或不继承object结果会是什么呢?(答案:called C.foo())
'''分析:如果A类是经典类(不继承object),当调用D的实例的foo()方法时,Python
会按照深度优先的方法搜索foo(),路径B-A-C,执行A中的foo();如果A是新式类(继承object),
则会按照广度优先的方法去搜索foo(),路径B-C-A,执行C中的foo();
通过以上分析:其实新式类更符合逻辑;通常对应Python3.x中的新式类已经兼容了经典类,即无论A是否
继承object类,D中都会执行C中的foo()方法,但是在Python2.7-3.0中仍然存在上述的差异,所以我们推荐使用新
式类,要继承object类'''
#类的继承机制
class A(object):
def __init__(self):
self.__private()
self.public() def __private(self):#基类的私有成员方法
print('__private Method of A1')
def public(self):
print('public Method of A2')
class B(A):
#没有构造函数,在创建实例时,直接走基类构造函数,对于重写
# 非私有成员方法后,此时在基类调用的方法为派生类中的
#如果有构造函数,实例化时则直接是走派生类中的构造函数
def __private(self):
print('Method of B1')
def public(self):
print("public Method of B2")
b = B()
b.public() #字符串
#1.短字符串驻留机制,共享同一个副本值
a=''
b=''
print(id(a) == id(b),b)
#2.格式化模板类
from string import Template
t = Template('My name is ${name},and is ${age} years old')
d ={'name':'dong','age':34}
print(t.substitute(d))
#3.字符串常用方法find(),rfind(),index(),rindex(),count()
'''find():查找字符串首次出现的位置
rfind():查找字符串最后出现的位置
index():查找字符串首次出现的位置'''
s = 'apple,peach,banana,peach,pear'
print(s.find('pp'))
print(s.index('pp'))
#4.split(),rsplit(),partition(),rpartition()
'''split(),rsplit()返回的是列表,如果有多个连线空白字符在未指定分隔符情况下,默认作为一个
partition(),rpartition()返回的是元组'''
li = s.split(',')
print(li)
print(s.partition(',,'))#分隔成3部分,如果原字符串中不包含分隔符,则返回原字符串及两个空字符串
ss='2014-10-20'
print(list(map(int,ss.split('-'))))#map对数据进行类型转换
#5.join()将列表中的多个字符串连接起来,并插入指定字符
lst = ['say','hello','miao','bai']
print("-".join(lst))
#使用split()与join()方法可以巧妙删除字符串中多余的空字符,并保留一个
#6.lower(),upper(),capitalize(),title(),swapcase()
'''lower():返回小写字符串;upp():返回大写字符串:capitalize():返回字符串首字符大写;
title():每个单词首字母大写;swapcase():大小写互换;
注意:这几个方法都是返回新字符串,对原字符串不做任何修改'''
#7.replace() 替换,也是返回新字符串
print('dfjgdifezadewwsaza'.replace('zad','ZAD'))
#8.maketrans(),translate()方法生成字符映射表和按映射表转换字符串并替换成字符,该方法可用来对字符串进行加密
#demo:创建映射表,将字符"abcdef123"一一对应转换成'uvwxyz@#$'
table =''.maketrans('abcdef123','uvwxyz@#$')
s ='Python is a greate programming language,I like it!'
print(s.translate(table))#按照映射表进行转换,使用方法可以实现恺撒加密算法
#9.对不可变对象字符串进行修改,需使用io.StringIO或array模块
#10.strip(),rstrip(),lstrip()分别用来删除两端、右端或左端连续的空字符串或指定字符串
'''这三个方法是对原字符串进行修改的'''
print('aaasdffffsfafaaaa'.rstrip('a'))
print('aaasdffaffsfafaaaa'.rstrip('af'))#注意:字符串中的af有不再两侧的,所以不删除
#11.eval()对字符串转换成Python表达式求值
print(eval('2+3'))
print(eval('[2,3,4,5]'))#注意:这里不能使用list(x)进行转换
#12.in、sartswith、endswith方法可用判断是否存在或以指定字符串开始或结束
#demo:startswith、endswith可以接受一个元组,如判断文件扩展名:
import os
[print(filename) for filename in os.listdir(r'F:\\') if filename.endswith(('.txt','.jpg','.gif'))]
#13.center()、ljust()、rjust()、zfill()返回指定宽度的新字符串,原字符串居中、左对齐、右对齐、左侧以字符0填充
print('hello world'.center(20,'-'))
print('uoi'.zfill(20))
#13.切片--读取字符串元素,不支持修改字符串
conent = 'Hello World!'
print(conent[:7])
#案例精选
#1.编写函数实现字符串加密和解密,循环使用指定密钥,采用简单的异或算法
def crypt(source,key):
from itertools import cycle
result=''
temp = cycle(key)
for ch in source:
result = result + chr(ord(ch)^ord(next(temp)))
return result
source ='ShangDong insitite of business and technology'
key ='Dong Fuguo' print('Before source:'+source)
encryt = crypt(source,key)
print('After encryt:'+encryt)
decryt = crypt(encryt,key)
print('After decryt:'+decryt)
import itertools
'''chain:连接两个列表进行迭代
count:从指定值开始,进入一个无界循环中
cycle:生成无界迭代器
filterfalse:返回一个可以使fun返回False的迭代器(python3.x中没有ifilter)
islice:返回一个迭代器,并指定start开始,stop结束,step步长
zip_longest:返回迭代器,并将列表进行组合,生成元组
repeate:将对应列表按重复生成n次'''
listone=['a','b','c']
listtwo=['11','22','33']
# for item in itertools.chain(listone,listtwo):
# print(item)
# for item in itertools.count(10):
# print(item)
# for item in itertools.cycle(listone):
# print(item)#无线循环
def funLargeFive(x):
if x > 5:
return True
# for item in itertools.filterfalse(funLargeFive,range(-10,10)):
# print(item)
listthree =[1,2,3]
def funAdd(x):
return x+5
for item in itertools.islice(listthree,1,2):
print(item)
for item in itertools.zip_longest(listone,listthree):
print(item)
stringBase='\u7684\u4e86\u662f'
print(''.join(stringBase.split('\\u')))
#目录树
import os
list_way = (list(os.walk(r".")))#产生一个三元tupple(dirpath[起始路径],dirnames[起始路径下的文件夹],filenames[起始路径下的文件名])
# for root,dirs,files in os.walk(r'F:\UpSVNProject\DownSVNProject\YzDEC',True):
# print('root:%s'%root)
# print('dirs:%s' % dirs)
# print('files:%s' % files)
dict_way = dict( zip( [ i[0] for i in list_way] , list_way ) )
print(dict_way)
def to_txt(way):
l = [ ]
three = dict_way[ way ]
print("==",three)
tab_num = way.count("\\")
if tab_num:
l.append("\t" * (tab_num - 1)+way.split("\\")[ -1 ] + "\n" )
for i in three[1]:
l = l + to_txt( way+"\\"+i )
for i in three[2]:
l.append( "\t" * tab_num + i +"\n")
return l
list_txt = to_txt(".")
print(list_txt)
with open("目录树.txt","w") as fil:
for i in list_txt:
fil.write(i)
#os.system('notepad 目录树.txt')
#正则表达式
import re
text ='apleld.be3ate...ganem..dadein'
print(re.split('[\.]+',text,maxsplit=2))#匹配分隔符.一次或多次,maxsplit最多分隔两次
print(re.findall('[a-zA-Z]+',text))#查找所有a-zA-Z的字符,以不是匹配的字符进行分隔
pat='name'
strs='Dear name..namelisty.'
print(re.sub(pat,'Mr.dong',strs))#匹配字符并替换指定的字符
example='shangdong institute of Business and technology is a very beautitful school'
print(re.findall('\\ba.+?\\b',example))#采用非贪婪模式
#使用re.compile()获取正则表达式对象,然后在使用其方法
pattern = re.compile(r'\bi\w+\b')
print(pattern.findall(example))
example1='ControlVolumne[0]'
import random
print(re.sub('(?<=\\[).+?(?=])',str(random.choice(range(100))),example1))
#match对象
email='tony@tiremove_thisger.net'
m = re.search('remove_this',email)
print(email[:m.start()],email[m.end():],m.group(0))
#子模式扩展语法
mm = re.match(r'(?P<first_name>\w+) (?P<last_name>\w+)','Malcolm Reynolds')
print(mm.group('first_name'))#命名的子模式
print(mm.groupdict())
mmm = re.match('(\d+)\.(\d+)','24.1632')
print(mmm.groups())
# s= 'aabc adcd abbcd abccd abcdd'
# p = re.compile(r'(\b\w* (?P<f>\w+) (?P=f)\w*\b)')
# print(p.findall(s))
#案例精选
#1.提取字符串中的电话号码
pattern = re.compile(r'(\d{3,4}-(\d{7,8}))')
print(pattern)
#json使用
import json
x=[1,31,4]
jx = json.dumps(x)
print(jx)#编码
print(json.loads(jx))#解码
#文件操作
'''需求:copy文件,并在新文件中行尾增加行号'''
filename =r'c:\Users\PGIDYSQ\Desktop\1111111e.gen'
with open(filename,'r') as fp:
lines = fp.readlines() #读取所有行
maxLength = max(map(len,lines)) #最长行的长度
for index ,line in enumerate(lines): #遍历所有行
newLine = line.rstrip() #清理行右侧的空白字符
newLine = newLine + ' '*(maxLength + 5 - len(newLine))
newLine = newLine + "#" +str(index + 1) + '\n' #添加行号
lines[index] = newLine
with open(filename[:filename.rfind('\\')+1] +'_new.gen','w') as fp:
fp.writelines(lines)
print(fp.name)
以上内容由本人学习中所记录的,有点乱,~~共勉
python新手菜鸟之基础篇的更多相关文章
- 智普教育Python视频教程之入门基础篇,python笔记
智普教育Python视频教程之入门基础篇,python笔记 print id()内存地址 type()变量类型 windows命令行下edit命令 python数据类型不需要指定类型 定义hostna ...
- Python(三)基础篇之「模块&面向对象编程」
[笔记]Python(三)基础篇之「模块&面向对象编程」 2016-12-07 ZOE 编程之魅 Python Notes: ★ 如果你是第一次阅读,推荐先浏览:[重要公告]文章更新. ...
- Python(四)基础篇之「文件对象&错误处理」
[笔记]Python(四)基础篇之「文件对象&错误处理」 2016-12-08 ZOE 编程之魅 Python Notes: ★ 如果你是第一次阅读,推荐先浏览:[重要公告]文章更新. ...
- Python学习笔记之基础篇(-)python介绍与安装
Python学习笔记之基础篇(-)初识python Python的理念:崇尚优美.清晰.简单,是一个优秀并广泛使用的语言. python的历史: 1989年,为了打发圣诞节假期,作者Guido开始写P ...
- 【新手学Python】一、基础篇
由于以前处理数据用Matlab和C,最近要处理大量文本文件,用C写实在是太繁琐,鉴于Python的强大文本处理能力,以及其在Deep Learning上有着很大优势,本人打算从即日起学习Python, ...
- Python学习总结之一 -- 基础篇
Python学习第一篇 一:写在前面 啊,最近我的新博客一直都没有更新学习内容了,只是最近一直都在忙着寻找实习机会(或许这只是一个借口,真实原因是我太懒惰了,改改改!).终于今天又投递了几个新的实习职 ...
- 【Python系统学习】基础篇
这次真的是最后一次了!第三次滚Python的基础.走了太多弯路.认真一点!菜鸟! 教程 转义字符 \ 可以转义很多字符,比如\n表示换行,\t表示制表符,字符\本身也要转义,所以\\表示的字符就是\ ...
- RF新手常见问题总结--(基础篇)
1. 经常有人问这个元素找不到,一般先排除这两个地方,再自己找找A:是否等待了足够的时间让元素加载 (增加sleep xx, wait Until xxx)B: 仔细查查,这个元素是否进入到另一个f ...
- Python 学习笔记(基础篇)
背景:今年开始搞 Data science ,学了 python 小半年,但一直没时间整理整理.这篇文章很基础,就是根据廖雪峰的 python 教程 整理了一下基础知识,再加上自己的一些拓展,方便自己 ...
随机推荐
- MacBook PyCharm激活码(附视频)
Windows激活请看这里:pyCharm最新2019激活码 此教程实时更新,请放心使用:如果有新版本出现猪哥都会第一时间尝试激活: pycharm官网下载地址:http://www.jetbrain ...
- [Abp vNext 源码分析] - 3. 依赖注入与拦截器
一.简要说明 ABP vNext 框架在使用依赖注入服务的时候,是直接使用的微软提供的 Microsoft.Extensions.DependencyInjection 包.这里与原来的 ABP 框架 ...
- mysql的学习笔记(一)
前言 开发中经常用mysql和SQL server交替使用,自己都产生知识的混乱.在这里重新整理下mysql的知识,也是梳理自己知识点,因为是学习笔记,所以并不会使用到图形化管理工具.mysql的安装 ...
- Spring Cloud实战的代码和视频位置
大家好,本博文的连接里包含了Spring Cloud实战的代码和视频位置. 代码下载连接: 视频下载连接:
- .NET Core微服务之基于Ocelot实现API网关服务(续)
Tip: 此篇已加入.NET Core微服务基础系列文章索引 一.负载均衡与请求缓存 1.1 负载均衡 为了验证负载均衡,这里我们配置了两个Consul Client节点,其中ClientServic ...
- C#版[击败99.69%的提交] - Leetcode 242. 有效的同构异形词 - 题解
C#版 - Leetcode 242. 有效的同构异形词 - 题解 Leetcode 242.Valid Anagram 在线提交: https://leetcode.com/problems/val ...
- 前后端同学,必会的Linux常用基础命令
无论是前端还是后端同学,一些常用的linux命令还是必须要掌握的.发布版本.查看日志等等都会用到.以下是我简单的总结了一些简单又常用的命令,欢迎大家补充.希望能帮助到大家 本文首发于公众号 程序员共成 ...
- Python:游戏:贪吃蛇原理及代码实现
一.游戏介绍 贪吃蛇是个非常简单的游戏,适合练手.先来看一下我的游戏截图: 玩法介绍:回车键:开始游戏空格键:暂停 / 继续↑↓←→方向键 或 WSAD 键:控制移动方向. 食物分红.绿.蓝三种,分别 ...
- 1.4部署到IIS「深入浅出ASP.NET Core系列」
希望给你3-5分钟的碎片化学习,可能是坐地铁.等公交,积少成多,水滴石穿,谢谢关注. 很多人第一次在IIS中部署Asp.Net Core App的人都会遇到问题,会发现原来的部署方式无法运行Asp.N ...
- Go channel实现源码分析
go通道基于go的并发调度实现,本身并不复杂,go并发调度请看我的这篇文章:go并发调度原理学习 1.channel数据结构 type hchan struct { qcount uint // 缓冲 ...