hza = 100
if hza < 100:
print('小于100')
else:
print('大于100')
大于100
hza = 110
if hza > 200:
print('%d大于200' % hza)
elif hza<100:
print('%d小于100' % hza)
else:
print('%d在100~200之间' % hza)
110在100~200之间
hza = [123,456,789]
x = 123
if x in hza:
print('%d 在hza内'%x)
else:
print('%d 不在hza内'%x)
123 在hza内
hza = {'han':123, 'zhuan':456}
x = 'han1'
if x in hza:
print('%s 在hza中' %x)
else:
print('%s 不在hza中' %x)
han1 不在hza中
n = 0
while n<10:
print(n,end=' ')
n += 1
0 1 2 3 4 5 6 7 8 9
hzas = {'han','zhu','an'}
# 只要集合不为空 就返回True 继续循环
while hzas:
hza = hzas.pop()
print(hza)
an
han
zhu
hzas = {'han','zhu','an'}
for name in hzas:
print(name)
# for循环遍历集合
an
han
zhu
for i in range(10):
print(i,end=" ")
# range(10)=>[0,10)=>[0,9]
0 1 2 3 4 5 6 7 8 9
hza = [123,456,678,33,44,1234,980,211,985,1,10,63]
for i in range(len(hza)):
print(hza[i],end=" ")
# 遍历普通list方式
123 456 678 33 44 1234 980 211 985 1 10 63
hza = [10,11,12,13,14,16]
for i in hza:
if i%2==0:
print(i,end=' ')
else:
continue
print('偶数')
10 偶数
12 偶数
14 偶数
16 偶数
hza = [10,11,12,13,14,16]
for i in hza:
if i%2==0:
print(i,end=' ')
else:
break
print('偶数')
10 偶数
def add_ab(a,b):
print (a+b)
add_ab(5,6)
11
def add_ab(a,b):
return (a+b)
x = add_ab(5,6)
x
11
# 函数参数提供默认值
def add_ab(a=1,b=2):
return (a+b)
x = add_ab(5,6)
print(x)
y = add_ab()
# 不给参数 参数就是默认值
y
11
3
print(add_ab(3,b=10))
# 这么也行
13
# 可变参数函数
def add_nums(a,*args):
for i in args:
a += i
return a
x = add_nums(1,2,3,4)
print(x)
add_nums(1,2,3,4,5)
10
15
# 可变参数是键值对
# 并如何方便地遍历键值对
def add_nums2(a,**kvargs):
for key,value in kvargs.items():
print(key,value) #直接打印2个参数
add_nums2(1,x=3,y=4,z=5)
x 3
y 4
z 5
# 可以直接返回多个返回值
def max_min(*arr):
a = max(arr)
b = min(arr)
return a,b
a,b = max_min(3,4,9,0,19,23,12)
print(a,b)
23 0
# 可以直接返回多个返回值
'''
def max_min2(*arr):
return max(arr)
return min(arr)
a,b = max_min2(3,4,9,0,19,23,12)
print(a,b)
'''
# 报错 不能这么分别返回 只能有一个return
TypeError Traceback (most recent call last)
Input In [18], in() 3 return max(arr) 4 return min(arr) ----> 6 a,b = max_min2(3,4,9,0,19,23,12) 7 print(a,b) | TypeError: cannot unpack non-iterable int object
%%writefile hza.py
#声明要生成一个.py的脚本文件
hza_v = 10
#定义一个变量值
def hza_add(hza_list):
hza_sum=0
for i in hza_list:
hza_sum +=i
return hza_sum
hza_list=[1,2,3,4,5]
print(hza_add(hza_list))
input()
Writing hza.py
%run hza.py
# 执行脚本
15
import hza
#导入脚本 第一次导入会自动帮你执行一遍
15
import hza
#不会重复导入执行了
hza
print(hza.hza_v)
# 获取脚本内的变量
10
# 修改脚本内变量值
hza.hza_v=100
hza.hza_v
100
hza_list=[10,20,30]
hza.hza_add(hza_list)
# 脚本名.函数名 形式调用脚本内的函数
60
import hza as h
#导入并取别名 方便调用
h.hza_v
100
h.hza_add([1,2,3,4,5,6,7,8,9,10])
55
from hza import hza_v,hza_add
# 导入后不用 .函数名形式 直接可以调用
hza_v
100
hza_add([1,2,3])
6
from hza import *
#所有东西全部导入
import os
os.remove('hza.py')
#删除脚本 本地文件也删除了
hza_v
# 能用 内存里还有此脚本 说明只是删除了本地文件
100
os.path.abspath('.')
#当前环境的本地目录
‘E:\data\ProjectData\JupyteNotebook\01-hello’
import math
for i in range(10):
n = input('write a number:')
if n == 'q':
break
res = math.log(float(n))
print (res)
# 接受10次输入
# 输入'q'可以提前结束
# 正常输入正数,打印 ln(n)
# 输入0,-1 数学错误,触发异常
write a number:1
0.0
write a number:10
2.302585092994046
write a number:2
0.6931471805599453
write a number:2.718281828459045
1.0
write a number:-1
ValueError Traceback (most recent call last)
Input In [3], in() |
5 if n == ‘q’:
6 break
----> 7 res = math.log(float(n))
8 print (res)
ValueError: math domain error
# 自己捕获异常
import math
for i in range(10):
try:
n = input('write a number:')
if n == 'q':
break
res = math.log(float(n))
print (res)
except ValueError:
print ('ValueError: input must > 0')
# 捕获了异常的好处 程序不会被中断, 还能继续往下执行
write a number:1
0.0
write a number:2
0.6931471805599453
write a number:0
ValueError: input must > 0
write a number:-1
ValueError: input must > 0
write a number:2.718281828459045
1.0
write a number:q
# 其他异常
import math
for i in range(10):
try:
n = input('write a number:')
if n == 'q':
break
res = 1/math.log(float(n))
print (res)
except ValueError:
print ('ValueError: input must > 0')
except ZeroDivisionError:
print ('ValueError: input can not = 1 because can not division by zero')
write a number:2
1.4426950408889634
write a number:1
ValueError: input can not = 1 because can not division by zero
write a number:2.718281828459045
1.0
write a number:q
# 其他异常
import math
for i in range(10):
try:
n = input('write a number:')
if n == 'q':
break
res = 1/math.log(float(n))
print (res)
except Exception:
print ('Has some Exception')
# 捕获所有种类异常 一种处理方式
write a number:1
Has some Exception
write a number:-1
Has some Exception
write a number:2
1.4426950408889634
write a number:q
# 其他异常
import math
for i in range(10):
try:
n = input('write a number:')
if n == 'q':
break
res = 1/math.log(float(n))
print (res)
except ValueError:
print ('ValueError: input must > 0')
except ZeroDivisionError:
print ('ValueError: input can not = 1 because can not division by zero')
except Exception:
print ('Unknow Exception')
write a number:0
ValueError: input must > 0
write a number:1
ValueError: input can not = 1 because can not division by zero
write a number:w
ValueError: input must > 0
write a number:asads
ValueError: input must > 0
write a number:q
class HzaError(ValueError):
pass
# 自定义了一个异常类 继承自ValueError
cur_list = ['han','zhu','an']
while True:
cur_input = input()
if cur_input not in cur_list:
raise HzaError('Invalid input: %s' %cur_input)
han
HAN
HzaError Traceback (most recent call last)
Input In [3], in() |
7 cur_input = input()
8 if cur_input not in cur_list:
----> 9 raise HzaError(‘Invalid input: %s’ %cur_input)HzaError: Invalid input: HAN
for i in range(4):
try:
b=int(input())
a=2/b
print(a)
except:
print('exception: ==0')
finally:
print('finally: 不管有无异常,finally一定会执行')
1
2.0
finally: 不管有无异常,finally一定会执行
2
1.0
finally: 不管有无异常,finally一定会执行
0
exception: ==0
finally: 不管有无异常,finally一定会执行
4
0.5
finally: 不管有无异常,finally一定会执行
%%writefile hza.txt
#use python crate a txt file
hello Python
han zhu an
CV cong cong cong
Overwriting hza.txt
txt = open('./hza.txt')
# 一次读取所有内容
txt_read = txt.read()
print(txt_read)
#use python crate a txt file
hello Python
han zhu an
CV cong cong cong
# 设法一行行读取
txt = open('./hza.txt')
lines = txt.readlines()
print (type(lines))
# 发现lines是一个list 多好 一行一个list项
print (lines)
[‘#use python crate a txt file\n’, ‘hello Python\n’, ‘han zhu an\n’, ‘CV cong cong cong\n’]
for line in lines:
print(line,end='')
#use python crate a txt file
hello Python
han zhu an
CV cong cong cong
# 读完记得关闭文件
txt.close()
# 读文件小结
txt = open('./hza.txt')
lines = txt.readlines()
for line in lines:
print(line,end='')
txt.close()
#use python crate a txt file
hello Python
han zhu an
CV cong cong cong
txt = open('hza_w.txt','w')
txt.write('jin tian ting hao\n')
txt.write('han zhu an')
txt.close()
# 当前目录下查看真的有文件 内容也写好了
txt = open('./hza_w.txt')
print(txt.read())
txt.close()
jin tian ting hao
han zhu an
txt = open('hza_w.txt','w')
# 'w'是覆盖写入 每次open(..'w') 会清空文件的
txt.write('123\n')
txt.write('456')
txt.close()
txt = open('./hza_w.txt')
print(txt.read())
# 发现原来内容没了 只有本次新写入的内容了
txt.close()
123
456
txt = open('hza_w.txt','a')
# 'a'是追加写入 每次open(..'a') 不会清空文件的
txt.write('\nhan\n')
txt.write('zhuan')
txt.close()
txt = open('./hza_w.txt')
print(txt.read())
# 发现文件原本的内容还在 新的内容追加在后面
txt.close()
123
456
han
zhuan
txt = open('hza_w.txt','w')
for i in range(5):
txt.write(str(i)+'\n')
# 写完后不关闭 文件直接读 能否读到?
txt2=open('hza_w.txt','r')
print(txt2.read())
# 新版Python也能读到了
# 不过有时执行也可能读不到,很正常 写后不关 OS肯定认为未写完 文件还在写 你又怎么能读呢? 经典'写后读' 数据相关(同步问题)
txt = open('hza_w.txt','w')
for i in range(5):
txt.write(str(i)+'\n')
txt.close()
# 写完后关闭了文件
txt2=open('hza_w.txt','r')
print(txt2.read())
# 新版Python也能读到了
0
1
2
3
4
txt=open('hza_write.txt','w')
try:
for i in range(100):
a = 10/(i-50)
txt.write(str(a)+'\n')
except Exception:
print ('error:',i)
finally:
txt.close()
# 一定要关闭 尤其是发生了异常时 (所以finally很好 不管前面执行得怎样,都会执行close())
error: 50
### with 打开文件 不用手动关闭文件了 执行完with会自动帮你关闭
with open('hza_write.txt','w') as f:
f.write('han zhu an\n')
f.write('han mian ying qiang\n')
class people:
'帮助信息: 此处可以写类的说明文档 [不难看出,其实就是内置了一个属性而已]'
#成员变量 (python直接这个写 默认是静态成员 所有类对象共享一份)
number = 100
# 构造函数(也是 新建对象时初始化 一定会执行) self相当于this关键字 [注意__init__ 前后都两个下划线]
def __init__(self,name,age):
self.name=name
self.age=age
# 2个普通成员方法
def display_number(self):
print ('number = ',people.number) #self.number 也行
def display_name(self):
print ('name = ',self.name)
people.__doc__
‘帮助信息: 此处可以写类的说明文档 [不难看出,其实就是内置了一个属性而已]’
# 实例化对象 很简单 (self不用传参)
p1=people('hza',23)
p2=people('hmyq',24)
# 调用对象方法
p1.display_number()
p2.display_number()
p1.display_name()
p2.display_name()
number = 100
number = 100
name = hza
name = hmyq
print(p2.name)
print(p1.number)
people.number
hmyq
100
100
# 修改属性值
p1.name='python'
p1.name
‘python’
del p1.name
p1.name
AttributeError Traceback (most recent call last)
Input In [19], in() |
----> 1 p1.nameAttributeError: ‘people’ object has no attribute ‘name’
hasattr(p2,'name')
True
hasattr(p2,'sex')
False
hasattr(p1,'name')
# 刚刚被删了该属性 应该也是没有
False
getattr(p2,'name')
‘hmyq’
setattr(p2,'name','tony')
getattr(p2,'name')
‘tony’
delattr(p2,'name')
getattr(p2,'name')
AttributeError Traceback (most recent call last)
Input In [28], in() |
----> 1 getattr(p2,‘name’)
AttributeError: ‘people’ object has no attribute ‘name’
print(people.__doc__) # 类说明文档
print(people.__name__) #类名
print(people.__module__) # 类所属模块
print(people.__bases__) # 类的父类
print('\n',people.__dict__) # 类的整个结构都打印出来了 (称为字典结构)
帮助信息: 此处可以写类的说明文档 [不难看出,其实就是内置了一个属性而已]
people
main
(,) {‘__module__’: ’ __main__ ', ‘__doc__’: ‘帮助信息: 此处可以写类的说明文档 [不难看出,其实就是内置了一个属性而已]’, ‘number’: 100, ‘__init__’:
, ‘display_number’: , ‘display_name’: , ‘__dict__’: , ‘__weakref__’: }
class Parent: #定义父类
number = 100 #直接方法外面写就是全局变量(静态变量)
def __init__(self):
print('父类构造方法')
def parentM(self):
print('父类普通成员方法')
# python定义 普通成员变量(局部变量 非静态属性) 得用函数定义、或者说直接写setXXX方法就是定义普通属性
def setAttr(self,attr):
Parent.parentAttr=attr
def getAttr(self): #getXXX方法获取属性
print ('父类属性:',Parent.parentAttr)
def overrideM(self): # self参数都写上 别丢了
print ('父类方法,等待被重写')
class child(Parent): #定义子类child 继承自父类Parent
def __init__(self):
print ('子类构造方法')
def childM(self):
print('子类普通成员方法')
def overrideM(self):
print('子类重写了后的方法')
# 实例化几个子类对象 并调用 自己的 和 继承自父类 的方法
c = child() # 创建子类对象 会调用子类构造方法
c.childM() # 调用子类自己的普通成员方法
c.parentM() # 子类调用父类普通成员方法 (继承下来了 能调用)
c.setAttr(18) # 也是子类调父类普通成员方法 子类使用父类非局部成员属性 (继承下来了)
c.getAttr() # 上行设置属性值 本行打印属性值
c.overrideM() # 子类重写父类方法 调用的就是子类方法了
子类构造方法
子类普通成员方法
父类普通成员方法
父类属性: 18
子类重写了后的方法
import time
time.time() # 1970-1-1到现在的浮点秒数 时间戳
1661524974.162104
# localtime方法自动转换
time.localtime(time.time())
time.struct_time(tm_year=2022, tm_mon=8, tm_mday=26, tm_hour=22, tm_min=44, tm_sec=5, tm_wday=4, tm_yday=238, tm_isdst=0)
struct_time = time.localtime(time.time())
time.asctime(struct_time)
‘Fri Aug 26 22:45:49 2022’
time.localtime()
time.struct_time(tm_year=2022, tm_mon=8, tm_mday=26, tm_hour=22, tm_min=48, tm_sec=5, tm_wday=4, tm_yday=238, tm_isdst=0)
time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
‘2022-08-26 22:48:50’
time.strftime('%Y年%m月%d日 %H:%M:%S',time.localtime())
‘2022年08月26日 22:49:16’
import calendar as cal
print(cal.month(2022,8))
print(cal.month(2022,9))

# 不会用可以查看文档
print(calendar.__doc__)

# 更好的文档:查看具体方法如何使用
print(help(calendar.month))
