python基础记录

var1 = 1
var2 = 10
print(var1 - var2)
print(var1 ** var2)

str = 'Runoob'
print(str[2:])
print(str[0], str[5])

list = ['a', 3.33, 'b', 6, 'c']
lis = [1, 2, 3, 4]
list[0] = 2
print(list[1])
print(list + lis)  # 列表

tuple = ['abc', 1, 2.222, 323, 'sa']
print(tuple[0:2])  # 元组不能赋值

dict = {'a': 'a1', 'b': 'b1'}
print(dict.keys())
print(dict.values())

i = 123
fol = 1.23
new = i + fol
print('datatype of i:', type(i))
print('datatype of fol:', type(fol))
print('Value of new:', new)
print('datatype of new:', type(new))

names = ['1wewq', '212', '2123', '2', '2121', 'sad1']
new_names = [name.upper() for name in names if len(name) > 3]
print(new_names)

mul = [i for i in range(30) if i % 3 == 0]
print(mul)  # 列表推导式  表达式 for 可迭代变量 in 列表 if 条件表达式

listdemo = ['12123', '21212', '2131212']
newdict = {key: len(key) for key in listdemo}
print(newdict)

dic = {x: x ** 2 for x in (2, 4, 6)}
print(dic)

setnew = {i ** 2 for i in (1, 2, 3)}
print(setnew)  # 字典推导式

a = {x for x in 'sasasasaewsdef' if x not in 's,a'}
print(a)  # 集合推导式

a = (x for x in range(1, 10))
print(a)

a = 10
b = 20
list = {10, 2, 3, 4, 5, 6}
if (a > b):
    print('大于b')
else:
    print('小于b')
    if (a in list):
        print('在list中')
    else:
        print('不在list中')

if (b not in list):
    print("在")
else:
    print('不在')

var1 = 0
var2 = 10
del var1

print(abs(-101))
print(math.ceil(4.121))

L = [
    ['Apple', 'Google', 'Microsoft'],
    ['Java', 'Python', 'Ruby', 'PHP'],
    ['Adam', 'Bart', 'Lisa']
]
print((L[0])[0])
print((L[2])[2])
print((L[1])[1])

height = 1.75
weight = 80.5
bmi = weight / weight
if bmi < 18.5:
    print('轻')
elif 18.5 < bmi < 25:
    print('正常')
elif 25 < bmi < 28:
    print('过重')
elif 28 < bmi < 32:
    print('肥胖')

sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
print(sum)

L = ['Bart', 'Lisa', 'Adam']
for x in L:
    print('hello,' + x)

n = 1
while n <= 100:
    if n > 3:
        break
    n = n + 1
    print('end')  # 当n>3时,停止

n = 0
while n < 10:
    n = n + 1
    if n % 2 == 0:
        continue
    print(n)  # 查找10以内的奇数,跳过偶数

d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
if 'tm' in d:
    print('true')
else:
    print('false')  # 查找'tm'在不在dict中

d.get('tm')
print(d.get('tm', -1))  # get方法,如果key值不存在可以返回none或者返回自己定义值

d.pop('Bob')
print(d)  # 删除一个key,value也会被删除
# dict查找和插入速度快,不会随key增多而变慢,但是占用空间多,浪费内存多
# list查找插入时间随元素增加而增加,占用空间小,浪费内存少
# dict是用空间换取时间
# dict用key来计算位置的方法叫哈希算法(hash

s = set([1, 2, 3, 1, 2, 4, 6])
s.add(45)
print(s)  # 重复元素自动被过滤
s.remove(1)  # remove删除元素
print(s)
s1 = set([1, 2, 5, 5, 6])
print(s & s1)
print(s | s1)  # set内无法放入可变对象

a = ['1', '2', '1', '3']
a.sort()
print(a)

a = 'asdasdasd'
print(a.replace('a', 'A'))

r = 12
r1 = 14.44
s = 3.14 * r * r
s1 = 3.14 * r1 * r1
print(s)
print(s1)  # 计算圆面积

age = int(input('年龄为:'))
print('')
if age <= 0:
    print('您还未出生')
elif 0 < age <= 6:
    print('幼年期')
elif 6 < age < 18:
    print('初级期')
elif 18 <= age:
    print('成长期')

sti = ['aaa', 'bbb', 'ccc', 'ddd']
for st in sti:
    if st == 'ccc':
        print('输出')
        break
        print('输出数据' + sti)
    else:
        print('没有输出')
print('输出成功')

for i in range(-8, 14):
    print(i)  # 遍历从小到大

for i in range(1, 22, 2):  # 2为步长,即间隔
    print(i)

i = ['aaa', 'bbb', 'ccc']
for i in range(len(a)):
    print(i, a[i])

i = ['aaa', 'bbb', 'ccc', 'dddd', 'cccc', 'dddddd', 'adsdas']
for ie in i:
    if len(i) != 4:
        print(ie)
    if ie == 'cccc':
        break
print('break')

a = 9
while a > 0:
    a -= 2
    if a == 6:
        continue
    print(a)
print('结束')

list1 = [1, 2, 3, 4, 5, 6]
iter1 = iter(list1)
print(next(iter1))
print(next(iter1))
print(next(iter1))
print(next(iter1))


# iter和next是最基本的迭代器
# 字符串,列表或元素对象都可以用于创建迭代器

class Number:
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        x=self.a
        self.a += 1
        return x


class1 = Number()
iter2 = iter(class1)

print(next(iter2))


class Number:
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        if self.a <= 20:
            x = self.a
            self.a += 1
            return x
        else:
            raise StopIteration


class2 = Number()
iter2 = iter(class2)

for x in iter2:
    print(x)

     #Stoplteration异常用来标识迭代的完成


import sys


def fibonacci(n):  # 生成斐波那契数列函数
    a, b, counter = 0, 1, 0
    while True:
        if counter > n:
            return
        yield a
        a, b = b, a + b
        counter += 1


f = fibonacci(10)  # f是一个迭代器,由生成器生成
while True:
    try:
        print(next(f),end='')
    except StopIteration:
        sys.exit()

list=[1, 2, 3, 4, ]
it=iter(list)
print(next(it))

list=[1, 2, 3, 4, ]
it=iter(list)
for x in  it:
    print(x)

import sys #引入sys模块
list=[1, 2, 3, 4]
it=iter(list)#创建迭代对象
while True:
    try:
        print(next(it))
    except StopIteration:
        sys.exit()

def max(a,b):
    if(a<b):
        return a
    else:
        return b

def h():
    print('hello world')
h()

def max(a,b):
    if(a>b):
        print(a)
    else:
        print(b)
a=4
b=7
print(max(a,b))

def area(width,height):#创建面积函数
    return width*height
w=4
h=5
print('width=', 4, 'height=', 5, 'area=', area(w,h))


def printme(str):
   print(str)
   return
printme('调用函数')
printme('再次调用')


a=[1,23,1,3]
a[2]=8

print(a)
#strings,tuples,numbers是不可变对象,list,dict是可修改对象
#例元组,数字1,字符串,整数传递的只是a的值,没有影响到其本身。如果在run(a)修改a的值,则是生成一个新的对象
#类似C++传递引用,如字典列表则是将数据完完整整传过去,修改之后外部数据也会受影响


def chuang(a):
    print(id(a))
    a=19
    print(id(a))
a=50
print(id(a))
chuang(a) #查看内存地址变化
、
def change(mylist):#定义一个函数
    mylist.append([1, 2, 3, 1, 153, 1])
    print('函数内取值', mylist)
    return

mylist=[1, 0, 3135,153, 11]
change(mylist)
print('取值后', mylist)

def can(str):
    print(str)
    return
can(str='测')#必须传带参数,不然会出现语法错误

def printinfo(name,age):
    print('名字:',name)
    print('年龄:',age)
    return
name='睡'
age='18'
printinfo(name, age)#函数参数的使用不需要使用指顺序

def printinfo(name=0,   age=34):
    print('名字', name)
    print('年龄', age)
    return
printinfo(age=32,name='runoob')
print('---------')
printinfo(name='runbob')


def printinfo(age1, *vartuple ):#设定一个参数
    print('输出')
    print(age1)
    print(age1, vartuple)
    return
#调用一次printinto函数
printinfo(11, 45, 45, 54)

def pringinfo(arg1, **vardict):
    print('输出:')
    print(arg1)
    print(vardict)
pringinfo(1, a=2, b=3)

X=lambda  a:a+10
print(X(5))

sum=lambda arg1, arg2:arg1+arg2
print('相加之后值为=',sum(10,20))
print('相加之后值为=',sum(10,30))

def myfunc(n):#创建一个函数
 return lambda  a:a*n #返回值

mydoubler=myfunc(2)
mytripler=myfunc(5)
print(mydoubler(11))
print(mytripler(11))

def sum(age1,age2):#创建函数
    log=age1+age2
    print('函数内:', log)
    return log
log=sum(10,20)#调用函数
print('函数外:', log)

list=[1,31,5,1,651]
L=[1,31,5,1,651]
x=999
i=888
list.append(x)#把一个元素放在列表结尾
list.extend(L)#把一个列表中的所有元素来扩充列表
list.insert(0,x)#指定位置插入一个参数,现在这个方法会使i插入列表前
list.remove(x)#删除列表值中为x的第一个元素,如果你、没有这个元素,就返回错误
list.pop()#从指定的位置移除元素,如果为空则从倒数第一个开始
#list.clear() 移除表中所有项#
list.index(x)#返回列表值为x的索引,如果没有匹配的元素就返回一个错误
list.count(x)#返回x在列表里出现的次数
list.sort()#对列表中的元素进行排序
list.reverse()#倒排列表中的元素
list.copy()#返回列表浅复制
print(list)

stack=[1,2,3]
stack.append(4)
stack.append(5)
stack.append(6)
stack.pop()
stack.pop()
print(stack)

jie=[1,2,3,4]
jie1=[2,4,6,8]
print([3*x for x in jie])
print([(2,2**x) for x in jie])
print([jie[i]*jie1[i] for i in range(len(jie))])
print([(x+3) for x in jie])

print([str(round(333/121, i)) for i in range(1, 6)])

mir=[
    [1,2,4,4],
    [1,3,6,6],
    [1,4,8,8],
]
print([[row[i] for row in mir]for i in range(4)])
tre = []
for i in range(4):
    tre.append([(row[i])for row in mir])
print(tre)

a = [-1, 1, 66.25, 333, 333, 1234.5]
del a[:]
print(a)#从列表中切割掉一个数

t=123,123,12,3,123,12,3
u='wqeeqw','eqweqw',213213,21312
t=u,(123123,123,12,231,121)
print(t)

bk={'sasa','sasa','dwqd','wqwq','ewqe','wqd'}
print('sasa' in bk)#查重
print(bk)#去重

a=set('jkjsasasljaksja')
b=set('aksajsakspjasjaskkjsak')
print(a)#在a
print(a|b)#在a在b
print(a-b)#在a不在b
print(a^b)#a,b独有
print(a&b)#a,b共有

tel={'hel':111, 'helr':222, 'belra':333}
tel['ask']=299
print(tel)
del tel['helr']#删除
print(tel)
print(list(tel.keys()))#只要键不要值
print(list(tel.values()))#只要值不要键
print(sorted(tel.keys()))#对传入的字母序排序
print('lis' in tel)

print(dict([('dic',1103),('diu',1104),('die',1105)]))

br={'dic': 1103, 'diu': 1104, 'die': 1105}
for b,r in br.items():#遍历关键字和对应值取值items
    print(b,r)

for q,w in enumerate(['bar','bre','bra']):#遍历函数索引位置和对应值enumerate
    print(q,w)

we=['we','blg','ax']
ew=['aa','bb','cc']
for w,e in zip(we,ew):
    print('1 '+w+'    ''2 '+e)#zip组合遍历

for i in reversed(range(1,100,3)):#reversed反向遍历
    print(i)

se=['sa','ae','wr','122','bt','py']#按顺序排列一个序列
for i in sorted(set(se)):
    print(i)

import sys
print('命令行参数:')
for i in sys.argv:
    print('参数:',i)
    print('路径:',sys.path)



def foo(n):
    if n == 1:
        return 1
    else:
        return n * foo(n - 1)
print(foo(5))


def func(a,alist=[]):
    alist.append(a)
    return alist
re1=func(10)
print(re1)
re2=func(20)
print(re2)
print(re1 is  re2)#默认参数为可变时,调用多少次,都指向同一地址

def func(a,b,*ddl,**ddm):
    print(a,b)
    print(ddl)
    print(ddm)
func(1, 2, 3, 4, c=5,m=89,d=998,e=2)

m=1
def func():
    global m#对全局变量进行修改需要用到global
    m+=1
func()
print(m)

def func():
    m = 1
    print('原始func:', m)

    def func1():
        m = 2
        print('原始func1:', m)
        def func2():
            nonlocal m#nonlcoal不能修改全局变量,只能对局部作用域中的父级变量进行更改
            m+=7
            print('修改之后:',m)
        func2()
    func1()
func()

def func():
    print('输出值')
def func1(func2):
    print('输出值1')
    return func2
res=func1(func)
res()

i=[1,2,3,4]
j=[2,3,4,5]
m=[4,5,6,7]
list=[i,j,m]#用容器当元素
for k in list:
    print(k)

def func():
    print('输出值')
def func1():
    print('输出值1')
def func2():
    print('输出值2')
list=[func,func1,func2]#用函数名当元素
for i in list:
    i()

il='海'
im='陆'
print(f'你来自{il}还是{im}')
#f-strings结构是F(f)+str的形式,
#在字符串中想替换的位置用{}展位,与format类似

print(f'结果是:{4*22}')#{}中可以插入任何表达式
i='sadsdadd'
print(f'全部大写:{i.upper()}')

aa='aadc'
bb=1,2,2,5,4
cc='A,b,2,1,d'
print('__iter__' in dir(aa))
print('__iter__' in dir(bb))#内部含有__inter__的方法都是可迭代对象

def func():
    print(1)
    yield 2
#使用yield的函数是生成器
#生成器是一个返回迭代器的函数,只能用于迭代操作
#在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,
#返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行
re=func()
print(re)
print(re.__next__())

def func():#创建函数
    for i in range(1,40):#遍历循环
        yield '饼'+str(i)#迭代
bin=func()
for i in range(1,22):
    print(next(bin))

def func():
    x=yield 1
    yield x
    yield x
rs=func()
print(next(rs))
m=rs.send(709)
print(m)
print(next(rs))#send和next都可以获取到yield的值,第一次获取值不能用send

li=[1,2,3,45,6,7,3]
nx=['ssa','sas','s','sas']
def func():
    yield li
def func1():
    yield from li#yield是把全部元素取出,而yield from只能取出一个
    yield from nx
re=func()
print(next(re))
re1=func1()
print(next(re1))
print(next(re1))
print(next(re1))
for i in re1:
    print(i)

#列表推导式的语法:
#1、循环模式:[变量(加工的变量) for 变量 in iterable]
#2、筛选模式: [变量(加工的变量) for 变量 in iterable if 条件]

it=[i for i in range(2,11,2)]#创建一个只有偶数
print(it)
iu=[i*i for i in range(1,11)]#创建一个10以内整数平方的列表
print(iu)
io=[i for i  in range(1,11)]
for l in io:
    print('包子',l,'号')#创建包子一号到10号的列表1
im=[f'包子{i}号' for i in range(1,10)]
print(im)#创建包子一号到10号的列表2

import sys
#命令行参数:print(sys.argv)
#路径:print(sys.path)

import supprot
supprot.func('Runoob')#创建另一个python文件,import导入之后就可以使用这个模块

import fibonacci #引入模块
fibonacci.fib(1000)#引用模块访问函数
fibonacci.fib2(100)
print(fibonacci.__name__)
fib=fibonacci.fib
fib(500)#经常使用一个函数给函数赋上本地名称就可以使用了

from fibonacci import fib,fib2
fib(50)#使用import直接导入函数和变量
from fibonacci import *
fib(100)#一次性把模块中的所有函数和变量都导入进来

if __name__=='__main__':
    print('本身运行')
else:
    print('另一模块')
#每个模块都有一个__name__属性,当值为'__main__时',表示是自身运行

import fibonacci,sys
print(dir(fibonacci))
print(dir(sys))

a = [1, 2, 3, 4, 5]
import fibonacci
fib = fibonacci.fib
print(dir())#当前模块中的属性列表
a = 5#建立一个新变量
print(dir())
del a#删除变量名
print(dir())#删除后的属性列表

import E.eff
eff=E.eff.on()
print(eff)#只导入一个特定模块

from E.eff import on
print(on())#导入子模块1

E.eff.on()#导入子模块2,必须全名访问
on()
#如使用 import E.eff导入形式,除了最后一个,其他只能是包,而最后一项可以为模块或包

he='he,llo\n'
hel=repr(he)#repr可以转译字符串中的特殊字符
print(hel)#repr的参数可以是python中的所有对象

for x in range(1,11):
    print(repr(x).rjust(2),repr(x*x).rjust(2),end='')
    print(repr(x*x*x).rjust(4))
#rjust字符串靠右,左边填充空格
#end末尾不换行

for x in range(1,11):
    print('{0:2d} {1:3d} {2:4d}'.format(x,x*x,x*x*x))
#ljust和center不会写任何东西只会返回新的字符串
print('12'.zfill(10))#zfill会在数字左边填充0

print('{0}:"{1}"'.format('导航','daohang.com'))#{}中的数字指向传入对象在format的位置

import math
print('近似值为:{}'.format(math.pi))
print('近似值为:{!s}'.format(math.pi))
print('近似值为:{0:.2f}'.format(math.pi))
table={'Google':1,'fox':2,'360':3}
for name,number in table.items():
    print('{0:10}-->{1:11d}'.format(name,number))
#在:后输入一个整数,靠右保证该域至少这么宽

#读和写文件
op=open('E/txt','w')
op.write('睡起来\n再说')
op.close()

f=open('E/txt','r')
str=f.read()#读取一个文件的内容,调用f.read()
print(str)
f.close()

f=open('E/txt','r')
str=f.readline()#readline读取单独一行
print(str)
f.close()

f=open('E/txt','r')
str=f.readlines()#readlines返回文件中包含的所有行
print(str)
f.close()

f=open('E/txt','r')
for line in f:#d迭代一个对象然后读取每行
    print(line,end='')
f.close()

f=open('E/txt','w')
num=f.write('睡起来\n再说')#write(string)返回写入的字符数
print(num)
f.close()

import pickle

f=open('E/txt','w')#打开一个文件并写入
val=('chuang.com',10)#创建一个list
han=str(val)#转换类型
f.write(han)
f.close()#关闭文件

f=open('E/tx','rb+')
f.write(b'012d21s21w12w12')
print(f.seek(4))#移动倒文件的第四个字节  f.seek
print(f.read(1))
print(f.seek(-3,2))#移动到文件倒数第三字节
print(f.read(11))

with open('E/txt','r')as f:#只读方法打开文件:with...as...
    read_data=f.read()
    print(f.closed)

fo=open('E/txt','wb')
print('文件名:'+fo.name)
fo.flush()
fo.close()

fo=open('E/txt','wb')
print('文件名:',fo.name)
ret=fo.isatty()
print('返回值',ret)
fo.close()

fo=open('E/txt','r')
te=fo.name
print('文件名为:',te)
line=fo.read()#不给参表示读取整个文件
print(line)

fo=open('E/txt','r')
f=fo.name
print('文件名为:',f)
line=fo.readline()#readline默认读取第一行,若参数非负,则读取相应字符串
print('读取:',line)
linr=fo.readline(-1)
print('读取:',linr)
fo.close()

fo=open('E/txt','r')
f=fo.name
print("文件名",f)
line=fo.readlines()#readlines默认读取所有行并返回列表,若给定参>0,则返回比参大的行
print('读取:',line)

import os

import sys,os
fo=os.access('E/txt',os.F_OK)#测试path是否存在
print(fo)
fo1=os.access('E/txt',os.R_OK)#测试path是否可读
print(fo1)
fo2=os.access('E/txt',os.W_OK)#测试path是否可写
print(fo2)
fo3=os.access('E/txt',os.X_OK)#测试path是否可执行
print(fo3)

import stat
import sys,os
pyth='venv'
retval=os.getcwd()#查看当前工作目录
print(retval)
os.chdir('E')#修改工作目录
retval=os.getcwd()#查看修改后的工作目录
print(retval)

while True:
    try:
      x=int(input('请输入数字:'))
      break
    except ValueError:
        print('请输入数字!')

import sys,E

for txt in sys.argv[1:]:
    try:
        f=open('E/txt','r')
    except IOError:
        print('cannot open',txt)
    else:
        print(txt,'has',len(f.readline()),'lines')
        f.close()

x=6
if x>5:
    raise Exception('x值不能大于5,x的值为:{}'.format(x))#raise触发异常

try:
    raise NameError('HiThere')#raise唯一的一个参数指定了要被抛出的异常
except NameError:
    print('An exception')
    raise

for line in open('E/txt'):
    print(line,end='')

with open('E/txt') as f:#执行完毕清理文件
    for line in f:
        print(line,end='')

class Myclass:
    i = 136
    def f(self):
        return 'ces'
x = Myclass()
print(x.i)
print(x.f())

class Canshu:
    def __init__(self,realpart,imagpart):
        self.r=realpart
        self.i=imagpart
x=Canshu(2.0,4.5)
print(x.r,x.i)

class Test:
    def log(self):
        print(self)
        print(self.__class__)
t=Test()
t.log()

class pope:#定义类
    name=''
    age=0
    def __init__(self,n,a):#定义构造方法
        self.name=n
        self.age=a
    def py(self):
        print('姓',self.name,'岁',self.age)
p=pope('姓',20)#实例化
p.py()

class jicheng(pope):
    dy=''
    def __init__(self,n,a,d):
        self.dy=d
    def ys(self):
        print('定义',self.d)
diao=jicheng('',10,'')
diao.py()

class duo:
    ces=''
    es=''
    def __init__(self,c,e):
        self.ces=c
        self.es=e
    def cc(self):
        print('测试',self.ces,'案例',self.es)

class duotai(pope,duo):
    def __init__(self,n,a,c,e):
       pope.__init__(self,n,a)
       duo.__init__(self,c,e)
tes=duotai('测',1,'什','?')
tes.cc()


class dan:
    ean = ''
    run = ''

    def __init__(self, e, r):
        self.ean = e
        self.run = r

    def shi(self):
        print('%s%s' % (self.ean, self.run))


class fan:
    tun = ''
    uan = ''

    def __init__(self, t, u):
        self.tun = t
        self.uan = u

    def shi(self):
        print('%s%s' % (self.tun, self.uan))


class Test(dan, fan):
    def __init__(self, e, r, t, u):
        dan.__init__(self, e, r)
        fan.__init__(self, t, u)


tat = Test('我', '使', '着', 'python')
tat.shi()


class Djc(fan):
    wit = ''

    def __init__(self, t, u, w):
        fan.__init__(self,t, u)
        self.wit = w

    def pss(self):
        print( self.tun, self.uan,self.wit)
sc = Djc('使着', 'pythond的', '是我')
sc.pss()

class A:
    B=0
    C=0
    def D(self):
        self.__B+=1
        self.C-=1
        print(self.__B)
a=A()
a.D()
a.D()
print(a.C)
print(a.__B)#__B变量私有化

class A:#创建类
    def __init__(self):#创建可调用方法
        self.a=0
        self.b=1#初始化两个计时器
    def __iter__(self):
        return self#实例本身即迭代对象,返回本身
    def __next__(self):
        self.a,self.b=self.b,self.a+self.b#计算下一个
        if self.a>100:
            raise StopIteration#停止
        return self.a
for i in A():
    print(i)


import sys
def func(n):
    a,b,counter=0,1,0
    while True:
        if counter>n:
            return
        yield a
        a,b=b,b+a
        counter+=1
f=func(10)
while True:
    try:
        print(next(f),end='\n')
    except StopIteration:
        sys.exit()
#命名空间:局部-全局-内置
#作用域规则顺序:局部-局部外局部-全局-内置
num=10
def func():
    global num#使用外部变量需要用global声明
    print(num)
    num=101
    print(num)
func()
print(num)

def func():
    bia=10
    def func1():
        nonlocal bia#修改外部变量nonlocal声明
        bia=100
        print(bia)
    func1()
    print(bia)
func()

import glob
import os

print(glob.glob('*.py'))#查找所有文件
os.system('mkdir today')#os模块创建一个新的文件

import datetime
import sys
from datetime import date
now=date.today()
print(now)
print(datetime.date(2220,7,10))

import doctest#doctest测试模块
print(doctest.testmod(verbose=True))

import unittest#unittest测试模块
class TestFunc(unittest.TestCase):
    def Func(n):
        a,b,bot=0,1,0
        while True:
            if bot>n:
                return
            yield a
            a,b=b,a+b
            bot+=1
    f=Func(10)
    while True:
        try:
            print(next(f),end='\n')
        except StopIteration:
            sys.exit()
    unittest.main

num=int(input('输入:'))
sum = 0
n = len(str(num))
temp = num
while temp > 0:
    blm = temp % 10
    sum+=blm ** n
    temp //= 10
if num == sum:
    print(num, '是阿姆斯特朗数')
else:
    print(num, '否,不是阿姆斯特朗数')
#日志
import logging
logger=logging.getLogger('test')
logging.basicConfig()#basicConfig是logging配置最简单办法,不使用则需要手动配置handler
logger.setLevel(logging.INFO)#输出所有大于info级别的日志
logger.info('I am <info> message')#info输出
logger.debug('I am <debug> message')#debug不输出

import logging
logger=logging.getLogger('test')
logger.setLevel(logging.DEBUG)#输入所有大于INFO的log
fmt=logging.Formatter('%(name)s-%(levelname)s-%(asctime)s-%(message)s')
#logger.addHandler(logging.StreamHandler())添加StreamHandler
#设置级别为WARNING
stream_hdl=logging.StreamHandler()
stream_hdl.setLevel(logging.DEBUG)
stream_hdl.setFormatter(fmt)
logger.addHandler(stream_hdl)
logger.addHandler(logging.FileHandler('test.log'))#添加一个FileHandler,在当前文件夹下创建一个新的log
logger.setLevel(logging.INFO)
#添加FileHandler,设置级别为DEBUG
file_hdl=logging.FileHandler('test.log')
file_hdl.setLevel(logging.DEBUG)
file_hdl.setFormatter(fmt)
logger.addHandler(file_hdl)

logger.info('I am <info> message.')
logger.debug('I am <debug> message.')


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值