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('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**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='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 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)

 

 

以上内容由本人学习中所记录的,有点乱,~~共勉

 

转载于:https://www.cnblogs.com/ysq0908/p/9106099.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python基础.doc》是一份讲解Python编程基础的文档。Python是一种简洁、易学、高效的编程语言,因此它成为了很多人入门编程的首选语言。 这份文档应该包含了Python的基本语法、变量、数据类型、运算符、流程控制、循环语句等内容。首先,它会详细介绍Python的注释规则,以及如何定义和使用变量。变量是存储数据的容器,它可以用于存储不同类型的数据,包括整数、浮点数、字符串等。接下来,文档应该解释各种常见的运算符,如算术运算符、比较运算符和逻辑运算符,以及它们的优先级和使用方法。 然后,文档应该涵盖Python中的条件语句和循环语句。条件语句如if语句和else语句,用于根据条件执行不同的代码块。循环语句如for循环和while循环,用于重复执行某些代码段。在解释这些语句时,应该给出一些实际的例子来帮助读者更好地理解。 此外,文档还应该介绍一些常用的内置函数和字符串操作方法。内置函数是Python提供的一些预先编写好的函数,可以直接使用,如print()和len()等。字符串操作方法主要是对字符串进行切片、连接、替换以及查找等操作。 最后,文档中还应该提供一些练习题或者编程示例,让读者能够通过实践来巩固所学的知识。 总之,《Python基础.doc》是一份详细讲解Python编程基础的文档,内容应该涵盖Python的基本语法、变量、数据类型、运算符、流程控制、循环语句等,并配有实例和练习题,以帮助读者更好地理解和掌握Python编程知识。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值