代码详解Python的函数基础(1)

目录

  • 1.函数调用
  • 2.函数定义
  • 总结

1.函数调用
# 1.调用函数,需要知道函数的名称和参数# 2.调用函数传入的参数需要和函数定义的参数数量和类型一致# 如调用abs函数print("-2的绝对值为:",abs(-2))print("100的绝对值为:",abs(100))# 3.函数名是指向一个函数对象的引用,可以把函数名赋给一个变量,相当于给这个函数起别名abs1 = abs# 变量abs1指向abs函数print("-1的绝对值为:",abs1(-1))

# 结果输出:
-2的绝对值为: 2
100的绝对值为: 100
-1的绝对值为: 1

2.函数定义
# 定义函数使用def# 语法:"""def 函数名(参数1,参数2,...):函数体return 返回值"""def compareAB(a,b):if a > b:print("a值大于b值!")elif a == b:print("a值等于b值!")else:print("a值小于b值!")# 调用函数compareAB(5,3)# 结果输出:# a值大于b值!

# 空函数:可以用来作为占位符def nop():pass# 参数检查:Python解释器可以帮我们检查参数个数是否正确,但无法检查参数类型是否正确# 数据类型检查实例def myAbs(x):if not isinstance(x,(int,float)):raiseTypeError("Bad Operand Type.")if x >= 0:return xelse:return -x# 传入"a"将抛出错误myAbs("A")

# 结果输出:---------------------------------------------------------------------------TypeErrorTraceback (most recent call last) in 15 16 # 传入"a"将抛出错误---> 17 myAbs("A") in myAbs(x)7 def myAbs(x):8if not isinstance(x,(int,float)):----> 9raiseTypeError("Bad Operand Type.")10if x >= 0:11return xTypeError: Bad Operand Type.

# 返回多个值import mathdef move(x,y,step,angle = 0):nx = x + step * math.cos(angle)ny = y - step * math.sin(angle)return nx,ny# 获取返回值x,y = move(100,100,60,math.pi / 6)print("x的值为%f,\ny的值为%f"%(x,y))# 结果输出:# x的值为151.961524,# y的值为70.000000

# 实例1:由欧拉角转换成对应的四元数# 由角度计算四元数的值import math# yaw:绕z轴旋转的角度;# pitch:绕y轴旋转的角度;# roll:绕x轴旋转的角度;def eulerToQuaternion(yaw,pitch,roll):w = math.cos(roll/2.0)*math.cos(pitch/2.0)*math.cos(yaw/2.0)+math.sin(roll/2.0)*math.sin(pitch/2.0)*math.sin(yaw/2.0)x = math.sin(roll/2.0)*math.cos(pitch/2.0)*math.cos(yaw/2.0)-math.cos(roll/2.0)*math.sin(pitch/2.0)*math.sin(yaw/2.0)y = math.cos(roll/2.0)*math.sin(pitch/2.0)*math.cos(yaw/2.0)+math.sin(roll/2.0)*math.cos(pitch/2.0)*math.sin(yaw/2.0)z = math.cos(roll/2.0)*math.cos(pitch/2.0)*math.sin(yaw/2.0)-math.sin(roll/2.0)*math.sin(pitch/2.0)*math.cos(yaw/2.0)return x,y,z,w# 绕z轴90度print("绕z轴90度的四元数为:",(eulerToQuaternion(math.pi/2,0,0)))# 绕y轴90度print("绕y轴90度的四元数为:",(eulerToQuaternion(0,math.pi/2,0)))# 绕x轴90度print("绕x轴90度的四元数为:",(eulerToQuaternion(0,0,math.pi/2)))

# 结果输出:
绕z轴90度的四元数为: (0.0, 0.0, 0.7071067811865476, 0.7071067811865476)
绕y轴90度的四元数为: (0.0, 0.7071067811865476, 0.0, 0.7071067811865476)
绕x轴90度的四元数为: (0.7071067811865476, 0.0, 0.0, 0.7071067811865476)


总结 【代码详解Python的函数基础(1)】本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!

    推荐阅读