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 = basetimes = 365//daysfor 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('5',['1','2','3'])) 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**2else: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 = value1self.__value2 = value2def show(self):print(self._value1)print(self.__value2) a = A() print(a._value1) print(a._A__value2) #数据成员定义 class Demo(object):total = 0def __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 =0def __init__(self,v):self.___value=vRoot.__total +=1def show(self):print('Self:',self.___value)print('Root:',Root.__total)@classmethoddef classShowTotal(cls):'''类方法,只能访问类成员'''print(cls.__total)@staticmethoddef 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 = valuedef __getValue(self):return self.__valuedef __setValue(self,v):self.__value = vvalue = 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 = ''returnself.__name = nameprint(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'returnself.__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='1234' b='1234' 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 cycleresult=''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)
以上内容由本人学习中所记录的,有点乱,~~共勉
转载于:https://www.cnblogs.com/ysq0908/p/9106099.html
python新手菜鸟之基础篇相关推荐
- RF新手常见问题总结--(基础篇)
RF新手常见问题总结--(基础篇) 学RF快一年了,经常碰到一些问题,有些同学也经常问到,这里总结一些,期望有人后续再补充,主要是响应群里--雪霁大神的号召,技术共享.废话少说,直接上干货了. 1. ...
- python进阶记录之基础篇二十六_Python进阶记录之基础篇(十六)
回顾 在Python进阶记录之基础篇(十五)中,我们介绍了面向对象的基本概念以及Python中类和对象的基础知识,需要重点掌握类的创建和对象的使用.今天我们继续讲一下Python中面向对象的相关知识点 ...
- Python学习日记-day1基础篇 字符 输出 注释
Python学习日记-day1基础篇 字符 输出 注释 by北栀一刺 # -*- coding: utf-8 -*- """ Spyder EditorThis is a ...
- python使用rpa需要什么插件_使用Python制作ArcGIS插件基础篇——工具介绍
ArcGIS从10.0开始支持addin(ArcGIS软件中又叫作加载项)的方式进行插件制作.相对于以往9.x系列,addin的无论是从使用或者编写都更加方便快捷.通过开发语言,可以制作ArcGIS ...
- python学习历程之----基础篇(五)
去年今日此门中,人面桃花相映红. 人面不知何处去,桃花依旧笑春风. 老铁们,又到见面时间了,不知不觉,Python编程的基础篇已经四篇了,今天是第五篇,根据章节安排,最多再有三次基础文章,我们就会进入 ...
- Python自动化开发之基础篇--Day1
一.Python介绍 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC ...
- Python机器学习及实践——基础篇9(SVM回归)
小贴士:核函数是一项非常有用的特征映射技巧,同时在数学描述上也略为复杂.因此这里不做过度引申.简单一些理解,便是通过某种函数计算,将原有的特征映射到更高维度的空间,从而尽可能达到新的高维度特征线性可分 ...
- Python菜鸟入门基础篇,零基础小白必看
自从20世纪90年代初发布以来,Python一直相当火爆,在这二十多年里,它的流行程度远远超过了C.C#.Java甚至Javascript. Python为什么受欢迎? Python迅猛发展背后的一个 ...
- python之正则表达式(基础篇)
前言 在向网页进行了提交请求之类的之后,我们可以得到了网页的返回内容,里面自然而然会有我们想要的数据,但是html元素文本这么多,我们不可能一 一去找我们需要的数据,这时就需要用到正则表达式了,正则表 ...
最新文章
- UVA1411 Ants(带权二分图的最大完美匹配、zkw费用流)
- 视觉SLAM总结——后端总结
- 线程的生命周期和状态控制
- 4W1T教程1 如何使用幻灯片
- Ubuntu下svn 版本管理客户端工具及常用方法
- linux-基本开发环境搭建
- Pandas to_bool
- hdu2846(字典树)
- VS应用程序无法正常启动0xc0150002
- debian系统离线安装iperf2
- 毕业设计-论文写作笔记【毕设题目类型、论文写作细节、毕设资料】
- 让Android 设备通过USB 转RJ45有线网卡上网
- 一天天学WG--第一天
- 存活探针(Liveness Probe)
- allegro出光绘文件出现的几个问题
- minecraft服务器stats文件夹,[教程]Minecraft 文件夹目录索引及各部分作用
- 简单c语言实现的成语接龙小游戏
- 【项目总结】论文复现与改进:一般选择模型的产品组合优化算法(Research@收益管理)
- vxwork任务切换分析
- 若依使用的框架和技术