学习目标:
掌握 Python函数知识
学习内容:
1.函数:
函数 =》方法 【区别不大】
scala 【有区别】
1.内置函数 【 常用类的api】
1.数学相关的 【math 包下的】
2.自定义函数
3.匿名函数【没有名字的函数】
1.内置函数 【 常用类的api】
print(abs(-10)) #绝对值
print(max(1, 2, 3, 4, 5))
print(min(1, 2, 3, 4))
print(sum([1, 2, 3]))
import math
print(math.sqrt(16))
print(math.ceil(3.2))
print(math.floor(3.5))
2.自定义函数
def play():
print(“hello play play”)
play()
def myAbs(num):
if(num >= 0):
return num
else:
return -num
print(myAbs(0))
1.Default Argument Values
def play_01(name,age=30):
print(f"{name} is playing xxx,and his age is {age}")
play_01(“longshao”)
play_01(“longshao”,21)
play_01(name=“longshao”,age=21)
play_01(age=21,name=“longshao”)
def play_02(*args,name=“ns”):
print(args[0],args[1],args[2],name)
play_02(1,2,3)
3.匿名函数
def play():
print(“hello play play”)
play()
p = (lambda :print(“hello play play”))
p()
def f1(x,y):
return x*y
print(f1(1, 2))
p1 = (lambda x,y: x*y)
print(p1(2, 3))
格式化输出:
print(1,2,3,4)
print(1,2,3,4)
print(1,“1”,sep=“,”)
print(str(1)+“1”)
2.格式化输出
name=“ns”
age=21
print(f"{name},{age}“)
print(”{0},{1}".format(name,age))
3.异常
java 异常:Throwable
error :
exception:
1.编译时异常
2.运行时异常
异常处理:
1.try [catch ] …[finally]
2.throws
3.throw
1
2
3
4
python:
异常处理:
1.try except
2.finally
3.raise 主动抛出异常
语法结构:
try:
//可能发生异常的代码
except xxxERROR
todo。。。。
except xxxERROR
todo。。。。
except xxxERROR
todo。。。。
finally:
def f1(n1,n2):
if(n1 >0 and n2 >0):
return n1+n2
else:
raise BaseException(“输入的值不是正数”)
try:
print(f1(-1, 3))
except BaseException as e:
print(e)
4.导包(import)
import xxx
from xxx import xx
import xx as x
from xxx import *
5.面向对象
class 对象
1.
动物 =》 类
猫 =》 对象
2.类的定义
1.属性+方法+构造器
2.Python中 通过构造器定义属性
3.构造器:
__init__() => 构造器
self =》 this
def init(self):
时间类:
from datetime import datetime
dt = datetime(2022,3,30)
print(dt)
print(dt.year)
print(datetime.now())
s1=“2022-03-01”
dt2= datetime.strptime(s1,‘%Y-%m-%d’)
print(type(dt2))
文件读写:
io:
java:
io:
字节流:
inputStream
outputStream
字符流:
Reader
Writer
1.读文件
1.open
2.read
3.close
with open
1
f = open(r"D:\sxwang\project\pycharm\python-sk\data\1.txt")
res = f.read()
print(res)
f.close()
with open(r"D:\sxwang\project\pycharm\python-sk\data\1.txt") as f:
res = f.read()
print(res)
f = open(r"D:\sxwang\project\pycharm\python-sk\data\1.txt")
for line in f:
print(line,end=“”)
f.close()
with open(r"D:\sxwang\project\pycharm\python-sk\data\1.txt") as f:
line = f.readline()
while (line):
print(line, end=“”)
line = f.readline()
with open(r"D:\sxwang\project\pycharm\python-sk\data\1.txt",‘a’) as f:
f.write(“a,a,a,a\n”)
f.writelines([“1,1,1,1\n”,“2,2,2,2\n”])