python第三天之基本元素

今天就继续学习基本元素了。包括函数、文件操作以及异常处理

一、函数

函数是为了提高效率,把一些重复性使用 的代码综合起来。
函数要先定义使用
定义:
def 函数名():
使用:直接用函数名就可以了。
函数名()

1、普通函数

def line():
    print("无返回值无参函数")
line()

python第三天之基本元素_第1张图片

2、带参函数

有传入值

def sum(a,b):
    print(a+b);
sum(11,12)  

python第三天之基本元素_第2张图片

3、带返回值函数

有返回值用return

def sum1(a,b):
    return a+b
print(sum1(11,13))

python第三天之基本元素_第3张图片

4、多个返回值函数

def chufa(a,b):
    c = a / b
    d = a % b
    return c,d
sh,yu =chufa(8,4)
print("商:%d,余数:%d"%(sh,yu))

python第三天之基本元素_第4张图片
强调一下全局变量和局部变量
全局变量:所有函数的变量,所有函数都可以用
局部变量:定义在一个函数内部,只有这个函数可以用。

二、文件操作

文件操作里面包含一些文件的打开、关闭、读、写功能

open(“”,“”) 打开文件
.close() 关闭文件
.write(“”)
.read(x) x为数字,读个字符
.readline() 读一行
.readlines() 读全文

例子如下:文件一般开始要打开,最后一定要记得关闭。

f = open("text.txt","w")  #w为写入,文件不存在时可以创建
f.write("hello\nhello\nhello\nhello")#写入
f.close()

f = open("text.txt","r")  #r为只读
content = f.read(2)  #读两个字符
print(content)
f.close()

f = open("text.txt","r")
content1 = f.readline() #读一行
print(content1)
f.close()

f = open("text.txt","r")
content2 = f.readlines() #读全文
print(content2)
for temp in content2 :
    print(temp)
f.close()

结果如下:
he
hello
[‘hello\n’, ‘hello\n’, ‘hello\n’, ‘hello’]
hello
hello
hello
hello

三、异常处理

捕获异常:错误的时候不想提示错误信息,想要捕获下来。
模板:

f = open("text.txt","r")
try:
    content = f.read()
    print(content)
except Exception as result:       #Exception可以抓取所有异常,result里面有错误信息
    print(result)
finally:               #总是执行的代码
    f.close()

你可能感兴趣的:(python,python,开发语言)