python函数基础设置 python怎么设计函数

python如何定义和调用函数1、函数定义
①使用def关键字定义函数

def 函数名(参数1.参数2.参数3...):
"""文档字符串 , docstring,用来说明函数的作用"""
#函数体
return 表达式
注释的作用:说明函数是做什么的,函数有什么功能 。
③遇到冒号要缩进,冒号后面所有的缩进的代码块构成了函数体 , 描述了函数是做什么的,即函数的功能是什么 。Python函数的本质与数学中的函数的本质是一致的 。
2、函数调用
①函数必须先定义,才能调用 , 否则会报错 。
②无参数时函数的调用:函数名(),有参数时函数的调用:函数名(参数1.参数2.……)
③不要在定义函数的时候在函数体里面调用本身,否则会出不来,陷入循环调用 。
④函数需要调用函数体才会被执行 , 单纯的只是定义函数是不会被执行的 。
⑤Debug工具中Step into进入到调用的函数里 , Step Into My Code进入到调用的模块里函数 。
Python基础入门-函数的定义与使用通过关键字def来创建函数,def的作用是实现python中函数的创建
函数定义过程:
函数名 ()小括号执行函数
函数体内对全局变量只能读?。?不能修改
局部变量 , 无法在函数体外使用
python 使用 lambda 来创建匿名函数 。
所谓匿名,意即不再使用 def 语句这样标准的形式定义一个函数 。
「Python3基础」函数 表示一个功能,函数定义着是提供功能的人 , 函数调用者是使用功能的人 。
print:打印功能,将括号中的内容,显示到终端 。
将括号中的内容显示在控制台.
input:输入功能,从终端中获取输入的信息,存到程序变量当中
作用:将用户输入的内容赋值给变量
第一个字符必须是字母表中字母或下划线 _。
标识符的其他的部分由字母、数字和下划线组成 。
标识符对大小写敏感 。
python最具特色的就是使用缩进来表示代码块,不需要使用大括号{}。
缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数 。实例如下:
python基?。耗谥煤⒎椒ā⒆遄址笕?/h2>在写python程序时,常能用到一些函数和方法,总结一下,保存起来 , 方便查询 。
一、内置函数
# abs()获取数字绝对值
# chr(i)数字转换为字符类型
# divmod() 获取两个数值的商和余数
# enumerate() 将可遍历序列组合为索引序列
# float()转换为浮点数
# format() 格式化字符串
# int()转换为整数
# input() 接受用户输入内容
# len() 计算元素个数
# max() 返回最大值
# min() 返回最小值
# math.ceil() 返回指定数值的上舍整数
# open()打开文件并返回文件对象
# pow() 幂运算
# print()打印输出
# range() 生成器
# reversed()反转所有元素
# round()四舍五入求值
# sorted()对可迭代对象进行排序
# str() 转换为字符串
# sum() 求和
# set() 创建集合
# tuple() 将序列转换为元组
# zip()将可迭代对象打包成元组
二、方法
# append() 添加列表元素
# capitalize()首字母转换为大写
# count()字符出现次数
# close() 关闭文件
# decode() 解码字符串
# dict.keys() 获取字典所有的键
# find()字符串首次出现的索引
# f.read() 读取文件内容
# dict.update()更新字典
# dict.items() 获取字典键/值对
# dict.get() 返回指定键的值
# encode() 编码字符串
# list.sort() 排序列表元素
# index() 元素首次出现的索引
# isdigit() 判断字符串是否只由数字组成
# isupper() 是否所有字母都为大写
# isnum() 判断字符串是否由字母和数字组成
# islower() 是否所有字母都为小写
# isdecimal() 检查字符串是否只包含十进制字符
# isalpha() 检测字符串是否为纯字母
# random.shuffle()随机排序
# random.sample()返回无重复随机数列表
# random.choice() 返回一个随机元素
# random.randint() 生成指定范围的随机整数
# random.randrange() 生成指定范围的指定递增基数随机整数
# pop() 删除列表中的元素
# remove()删除列表中的指定元素
# strip()去除空格
# lstrip()去除左侧空格
# rstrip() 去除右侧空格
# readline() 读取单行内容
# root.after() Tkinter中等待一段时间后再执行命令
# str.isnumeric() 验证字符串是否为数字(适用于Unicode)
# split()分割字符串
# ord() 将字符转换为整数
# replace() 字符串替换
# ljust() 左对齐填充
# rjust() 左对齐填充
# readlines() 读取所有行内容
# datetime.datetime.now() 返回指定时区的本地日期时间
# datetime.datetime.today() 获取当前本地日期的date对象
# datetime.utcnow() 返回当前UTC时间的datetime对象
# time.strptime()把时间字符串解析为元组
# time.time()返回当前时间的时间戳
# time.sleep()暂停指定秒数
# time.strftime() 返回指定格式的日期字符串
# time.mktime() 接收时间元组并返回时间戳
# os.getcwd() 获取当前工作目录
# os.listdir() 获取指定路径下的目录和文件列表
# os.makedirs() 递归创建目录
# os.rename() 重命名目录或文件
# os.path.exists() 判断路径是否存在
# upper() 全部转换为大写字母
# lower()全部转换为小写字母
# sys.stdout.write() 标准输出打印
# sys.stdout.flush()刷新输出
# shutil.copy() 复制单个文件到另一文件或目录
# write() 写入文件内容
# winsound.Beep() 打开电脑扬声器
# zfill() 在字符串前面填充0
三、循环语句
# break终止当前循环
# continue 终止本循环进入下一次循环
# with open() as file 以with语句打开文件(数据保存)
四、转义字符
\行尾续行符
\' 单引号
\'' 双引号
\a 响铃
\e 转义
\n 换行
\t 横向制表符
\f 换页
\xyy 十六进制yy代表的字符
\\反斜杠符号
\b 退格
\000 空
\v 纵向制表符
\r 回车
\0yy 八进制yy代表的字符
\other 其他的字符以普通格式输出
python 基础教程 运算
a = 21
b = 10
c = 0
c = ab
print "1 - c 的值为:", c
c = a - b
print "2 - c 的值为:", c
c = a * b
print "3 - c 的值为:", c
c = a / b
print "4 - c 的值为:", c
c = a % b
print "5 - c 的值为:", c
a = 2
b = 3
c = a**b
print "6 - c 的值为:", c
a = 10
b = 5
c = a//b
print "7 - c 的值为:", c
python比较
a = 21
b = 10
c = 0
if ( a == b ):
print "1 - a 等于 b"
else:
print "1 - a 不等于 b"
if ( a != b ):
print "2 - a 不等于 b"
else:
print "2 - a 等于 b"
if ( ab ):
print "3 - a 不等于 b"
else:
print "3 - a 等于 b"
if ( ab ):
print "4 - a 小于 b"
else:
print "4 - a 大于等于 b"
if ( ab ):
print "5 - a 大于 b"
else:
print "5 - a 小于等于 b"
a = 5
b = 20
if ( a = b ):
print "6 - a 小于等于 b"
else:
print "6 - a 大于b"
if ( b = a ):
print "7 - b 大于等于 a"
else:
print "7 - b 小于 a"
赋值
a = 21
b = 10
c = 0
c = ab
print "1 - c 的值为:", c
c= a
print "2 - c 的值为:", c
【python函数基础设置 python怎么设计函数】 c *= a
print "3 - c 的值为:", c
c /= a
print "4 - c 的值为:", c
c = 2
c %= a
print "5 - c 的值为:", c
c **= a
print "6 - c 的值为:", c
c //= a
print "7 - c 的值为:", c
逻辑运算符:
a = 10
b = 20
if ( a and b ):
print "1 - 变量 a 和 b 都为 true"
else:
print "1 - 变量 a 和 b 有一个不为 true"
if ( a or b ):
print "2 - 变量 a 和 b 都为 true,或其中一个变量为 true"
else:
print "2 - 变量 a 和 b 都不为 true"
a = 0
if ( a and b ):
print "3 - 变量 a 和 b 都为 true"
else:
print "3 - 变量 a 和 b 有一个不为 true"
if ( a or b ):
print "4 - 变量 a 和 b 都为 true,或其中一个变量为 true"
else:
print "4 - 变量 a 和 b 都不为 true"
if not( a and b ):
print "5 - 变量 a 和 b 都为 false,或其中一个变量为 false"
else:
print "5 - 变量 a 和 b 都为 true"
in,not in
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print "1 - 变量 a 在给定的列表中 list 中"
else:
print "1 - 变量 a 不在给定的列表中 list 中"
if ( b not in list ):
print "2 - 变量 b 不在给定的列表中 list 中"
else:
print "2 - 变量 b 在给定的列表中 list 中"
a = 2
if ( a in list ):
print "3 - 变量 a 在给定的列表中 list 中"
else:
print "3 - 变量 a 不在给定的列表中 list 中"
条件
flag = False
name = 'luren'
if name == 'python':# 判断变量否为'python'
flag = True# 条件成立时设置标志为真
print 'welcome boss'# 并输出欢迎信息
else:
print name
num = 5
if num == 3:# 判断num的值
print 'boss'
elif num == 2:
print 'user'
elif num == 1:
print 'worker'
elif num0:# 值小于零时输出
print 'error'
else:
print 'roadman'# 条件均不成立时输出
循环语句:
count = 0
while (count9):
print 'The count is:', count
count = count1
print "Good bye!"
i = 1
while i10:
i= 1
if i :# 非双数时跳过输出
continue
print i# 输出双数2、4、6、8、10
i = 1
while 1:# 循环条件为1必定成立
print i# 输出1~10
i= 1
if i10:# 当i大于10时跳出循环
break
for letter in 'Python':# 第一个实例
print '当前字母 :', letter
fruits = ['banana', 'apple','mango']
for fruit in fruits:# 第二个实例
print '当前水果 :', fruit
print "Good bye!"
获取用户输入:raw_input
var = 1
while var == 1 :# 该条件永远为true,循环将无限执行下去
num = raw_input("Enter a number:")
print "You entered: ", num
print "Good bye!"
range,len
fruits = ['banana', 'apple','mango']
for index in range(len(fruits)):
print '当前水果 :', fruits[index]
print "Good bye!"
python数学函数:
abs,cell,cmp,exp,fabs,floor,log,log10,max,min,mod,pow,round,sqrt
randrange
访问字符串的值
var1 = 'Hello World!'
var2 = "Python Runoob"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
转义字符
格式化输出
print "My name is %s and weight is %d kg!" % ('Zara', 21)
字符串函数:
添加元素
list = []## 空列表
list.append('Google')## 使用 append() 添加元素
list.append('Runoob')
print list
删除元素
list1 = ['physics', 'chemistry', 1997, 2000]
print list1
del list1[2]
print "After deleting value at index 2 : "
print list1
列表操作
列表方法
删除字典
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # 删除键是'Name'的条目
dict.clear();# 清空词典所有条目
del dict ;# 删除词典
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
字典的函数:
当前时间戳:
import time
time.time()
格式化日期输出
import time
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())
a = "Sat Mar 28 22:24:24 2016"
print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))
获取某个月日历:calendar
import calendar
cal = calendar.month(2016, 1)
print "以下输出2016年1月份的日历:"
print cal
当前日期和时间
import datetime
i = datetime.datetime.now()
print ("当前的日期和时间是 %s" % i)
print ("ISO格式的日期和时间是 %s" % i.isoformat() )
print ("当前的年份是 %s" %i.year)
print ("当前的月份是 %s" %i.month)
print ("当前的日期是%s" %i.day)
print ("dd/mm/yyyy 格式是%s/%s/%s" % (i.day, i.month, i.year) )
print ("当前小时是 %s" %i.hour)
print ("当前分钟是 %s" %i.minute)
print ("当前秒是%s" %i.second)
不定长参数:*
lambda:匿名函数
def....
python模块搜索路径
获取用户输入
str = raw_input("请输入:")
print "你输入的内容是: ", str
input可以接收表达式
open参数
write要自己添加换行符
读取10个字符
重命名:os.rename
os.remove
os.mkdiros.chdir
os.getcwd
os.rmdir
open参数
file的方法
异常:
try:
fh = open("testfile", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print "Error: 没有找到文件或读取文件失败"
else:
print "内容写入文件成功"
fh.close()
try:
fh = open("testfile", "w")
fh.write("这是一个测试文件,用于测试异常!!")
finally:
print "Error: 没有找到文件或读取文件失败"
用户自定义异常:
os模块提供了非常丰富的方法用来处理文件和目录 。常用的方法如下表所示:
| 序号 | 方法及描述 |
| 1 |
os.access(path, mode)
检验权限模式 |
| 2 |
os.chdir(path)
改变当前工作目录 |
| 3 |
os.chflags(path, flags)
设置路径的标记为数字标记 。|
| 4 |
os.chmod(path, mode)
更改权限 |
| 5 |
os.chown(path, uid, gid)
更改文件所有者 |
| 6 |
os.chroot(path)
改变当前进程的根目录 |
| 7 |
os.close(fd)
关闭文件描述符 fd |
| 8 |
os.closerange(fd_low, fd_high)
关闭所有文件描述符,从 fd_low (包含) 到 fd_high (不包含), 错误会忽略 |
| 9 |
os.dup(fd)
复制文件描述符 fd |
| 10 |
os.dup2(fd, fd2)
将一个文件描述符 fd 复制到另一个 fd2 |
| 11 |
os.fchdir(fd)
通过文件描述符改变当前工作目录 |
| 12 |
os.fchmod(fd, mode)
改变一个文件的访问权限,该文件由参数fd指定 , 参数mode是Unix下的文件访问权限 。|
| 13 |
os.fchown(fd, uid, gid)
修改一个文件的所有权,这个函数修改一个文件的用户ID和用户组ID,该文件由文件描述符fd指定 。|
| 14 |
os.fdatasync(fd)
强制将文件写入磁盘,该文件由文件描述符fd指定,但是不强制更新文件的状态信息 。|
| 15 |
os.fdopen(fd[, mode[, bufsize]])
通过文件描述符 fd 创建一个文件对象,并返回这个文件对象 |
| 16 |
os.fpathconf(fd, name)
返回一个打开的文件的系统配置信息 。name为检索的系统配置的值,它也许是一个定义系统值的字符串 , 这些名字在很多标准中指定(POSIX.1, Unix 95, Unix 98, 和其它) 。|
| 17 |
os.fstat(fd)
返回文件描述符fd的状态,像stat() 。|
| 18 |
os.fstatvfs(fd)
返回包含文件描述符fd的文件的文件系统的信息,像 statvfs() |
| 19 |
os.fsync(fd)
强制将文件描述符为fd的文件写入硬盘 。|
| 20 |
os.ftruncate(fd, length)
裁剪文件描述符fd对应的文件, 所以它最大不能超过文件大小 。|
| 21 |
os.getcwd()
返回当前工作目录 |
| 22 |
os.getcwdu()
返回一个当前工作目录的Unicode对象 |
| 23 |
os.isatty(fd)
如果文件描述符fd是打开的,同时与tty(-like)设备相连 , 则返回true, 否则False 。|
| 24 |
os.lchflags(path, flags)
设置路径的标记为数字标记,类似 chflags() , 但是没有软链接 |
| 25 |
os.lchmod(path, mode)
修改连接文件权限 |
| 26 |
os.lchown(path, uid, gid)
更改文件所有者,类似 chown,但是不追踪链接 。|
| 27 |
os.link(src, dst)
创建硬链接,名为参数 dst,指向参数 src |
| 28 |
os.listdir(path)
返回path指定的文件夹包含的文件或文件夹的名字的列表 。|
| 29 |
os.lseek(fd, pos, how)
设置文件描述符 fd当前位置为pos, how方式修改: SEEK_SET 或者 0 设置从文件开始的计算的pos; SEEK_CUR或者 1 则从当前位置计算; os.SEEK_END或者2则从文件尾部开始. 在unix,Windows中有效 |
| 30 |
os.lstat(path)
像stat(),但是没有软链接 |
| 31 |
os.major(device)
从原始的设备号中提取设备major号码 (使用stat中的st_dev或者st_rdev field) 。|
| 32 |
os.makedev(major, minor)
以major和minor设备号组成一个原始设备号 |
| 33 |
os.makedirs(path[, mode])
递归文件夹创建函数 。像mkdir(), 但创建的所有intermediate-level文件夹需要包含子文件夹 。|
| 34 |
os.minor(device)
从原始的设备号中提取设备minor号码 (使用stat中的st_dev或者st_rdev field ) 。|
| 35 |
os.mkdir(path[, mode])
以数字mode的mode创建一个名为path的文件夹.默认的 mode 是 0777 (八进制) 。|
| 36 |
os.mkfifo(path[, mode])
创建命名管道,mode 为数字,默认为 0666 (八进制) |
| 37 |
os.mknod(filename[, mode=0600, device])
创建一个名为filename文件系统节点(文件,设备特别文件或者命名pipe) 。
|
| 38 |
os.open(file, flags[, mode])
打开一个文件 , 并且设置需要的打开选项 , mode参数是可选的 |
| 39 |
os.openpty()
打开一个新的伪终端对 。返回 pty 和 tty的文件描述符 。|
| 40 |
os.pathconf(path, name)
返回相关文件的系统配置信息 。|
| 41 |
os.pipe()
创建一个管道. 返回一对文件描述符(r, w) 分别为读和写 |
| 42 |
os.popen(command[, mode[, bufsize]])
从一个 command 打开一个管道 |
| 43 |
os.read(fd, n)
从文件描述符 fd 中读取最多 n 个字节,返回包含读取字节的字符串,文件描述符 fd对应文件已达到结尾, 返回一个空字符串 。|
| 44 |
os.readlink(path)
返回软链接所指向的文件 |
| 45 |
os.remove(path)
删除路径为path的文件 。如果path 是一个文件夹,将抛出OSError; 查看下面的rmdir()删除一个 directory 。|
| 46 |
os.removedirs(path)
递归删除目录 。|
| 47 |
os.rename(src, dst)
重命名文件或目录,从 src 到 dst |
| 48 |
os.renames(old, new)
递归地对目录进行更名,也可以对文件进行更名 。|
| 49 |
os.rmdir(path)
删除path指定的空目录,如果目录非空,则抛出一个OSError异常 。|
| 50 |
os.stat(path)
获取path指定的路径的信息,功能等同于C API中的stat()系统调用 。|
| 51 |
os.stat_float_times([newvalue])
决定stat_result是否以float对象显示时间戳
|
| 52 |
os.statvfs(path)
获取指定路径的文件系统统计信息 |
| 53 |
os.symlink(src, dst)
创建一个软链接 |
| 54 |
os.tcgetpgrp(fd)
返回与终端fd(一个由os.open()返回的打开的文件描述符)关联的进程组 |
| 55 |
os.tcsetpgrp(fd, pg)
设置与终端fd(一个由os.open()返回的打开的文件描述符)关联的进程组为pg 。|
| 56 |
os.tempnam([dir[, prefix]])
返回唯一的路径名用于创建临时文件 。|
| 57 |
os.tmpfile()
返回一个打开的模式为(w b)的文件对象 .这文件对象没有文件夹入口,没有文件描述符,将会自动删除 。|
| 58 |
os.tmpnam()
为创建一个临时文件返回一个唯一的路径 |
| 59 |
os.ttyname(fd)
返回一个字符串,它表示与文件描述符fd 关联的终端设备 。如果fd 没有与终端设备关联,则引发一个异常 。|
| 60 |
os.unlink(path)
删除文件路径 |
| 61 |
os.utime(path, times)
返回指定的path文件的访问和修改的时间 。|
| 62 |
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
输出在文件夹中的文件名通过在树中游走,向上或者向下 。|
| 63 |
os.write(fd, str)
写入字符串到文件描述符 fd中. 返回实际写入的字符串长度 |
关于python函数基础设置和python怎么设计函数的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

    推荐阅读