[Python] 函数基本
使用def 函数名(): 来定义一个函数,函数体一缩进块的形式写,返回结果是return xx
例如:
def myAbs(x):
if x >= 0:
return x
else:
return –x
可变参数
在参数的前面加一个*号,函数里面接收到的参数是tuple类型,遍历一下
#可变参数
def myCalc(*nums):
sum=0
for num in nums:
sum+=num
return sum
print(myCalc(1,2,3))
迭代
通过for循环来遍历list或者tuple,这种遍历称为迭代
使用for in来迭代list,for key in list:,例如:
for item in myList:
print(item)
使用for in来迭代dict,for k,v in d.items:,例如:
user={"name":"taoshihan","age":"100"}
for k,v in user.items():
print(k+"=>"+v)
切片
取一个list或tuple的部分元素,使用切片操作符list[a:b],取list的元素从a开始到b结束(不包含b)
例如:myList=[1,2,3]
print(myList[0:2]) 输出[1, 2]
函数递归
求n的阶乘(n!)
def myFact(n):
if n==1:
return 1
return myFact(n-1)*n
print(myFact(30))
使用尾递归优化来解决栈溢出问题,return语句里面不能包含表达式,但是Python语言没有引入尾递归,因此不能使用
解决汉诺塔问题:
def myMove(n,source,bridge,destination):
if n==1:
print("从"+source+"移动"+"到"+destination)
else:
myMove(n-1,source,destination, bridge)
print("从"+source+"移动"+"到"+destination)
myMove(n-1,bridge,source,destination)
myMove(5,"a","b","c")
函数式编程的特点:允许把函数本身作为参数传入另一个函数,还允许返回一个函数
相关文章
- 交互式仪表板!Python轻松完成!⛵
- PythonRobotics | 基于python的机器人自主导航
- KG4Py:Python代码知识图谱和语义搜索的工具包
- 在Centos中安装Python3_Python自学第一节
- Python脚本介绍与基础函数_Python自学第二节
- Python运算符使用_Python自学第三节
- Python输入输出函数_Python自学第四节
- Python选择结构IF语句_Python自学第五节
- Python循环结构for和while语句_Python自学第六节
- Python类和对象概念_Python自学第七节
- Python字符串的索引和切片_Python自学第八节
- Python字符串遍历_Python自学第九节
- Python进制转换方法_Python自学第十节
- Python字符编码_ASCII码_Python自学第十一节
- Python_ASCII码和进制进行转换练习_Python自学第十二节
- Python_字符串常用函数和方法(1)_Python自学第十三节
- Python_字符串常用函数和方法(2)_Python自学第十四节
- Python_字符串常用函数和方法(3)_Python自学第十五节
- Python_字符串常用函数和方法(4)_Python自学第十六节
- Python_字符串常用函数和方法(5)_Python自学第十七节