栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python第三天之基本元素

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python第三天之基本元素

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

一、函数

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

1、普通函数
def line():
    print("无返回值无参函数")
line()

2、带参函数

有传入值

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

3、带返回值函数

有返回值用return

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

4、多个返回值函数
def chufa(a,b):
    c = a / b
    d = a % b
    return c,d
sh,yu =chufa(8,4)
print("商:%d,余数:%d"%(sh,yu))


强调一下全局变量和局部变量
全局变量:所有函数的变量,所有函数都可以用
局部变量:定义在一个函数内部,只有这个函数可以用。

二、文件操作

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

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

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

f = open("text.txt","w")  #w为写入,文件不存在时可以创建
f.write("hellonhellonhellonhello")#写入
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
[‘hellon’, ‘hellon’, ‘hellon’, ‘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()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/961319.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号