目录
  • 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)):
        raise  typeerror("bad operand type.")
    if x >= 0:
        return x
    else:
        return -x

# 传入"a"将抛出错误
myabs("a")
# 结果输出:
---------------------------------------------------------------------------
typeerror                                 traceback (most recent call last)
<ipython-input-8-21934e00955a> in <module>
     15 
     16 # 传入"a"将抛出错误
---> 17 myabs("a")
<ipython-input-8-21934e00955a> in myabs(x)
      7 def myabs(x):
      8     if not isinstance(x,(int,float)):
----> 9         raise  typeerror("bad operand type.")
     10     if x >= 0:
     11         return x
typeerror: bad operand type.
# 返回多个值
import math
def 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)
 

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注www.887551.com的更多内容!