本系列博文基于廖雪峰老师的官网Python教程,笔者在大学期间已经阅读过廖老师的Python教程,教程相当不错,官网链接: 廖雪峰官方网站.请需要系统学习Python的小伙伴到廖老师官网学习,笔者的编程环境是Anaconda+Pycharm,Python版本:Python3.
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的绝对值为: 12.函数定义
# 定义函数使用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)in 15 16 # 传入"a"将抛出错误 ---> 17 myAbs("A") 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)
注:以上代码均经过验证,但并不是生产环境部署的代码,只是一些小Demo,以用来说明Python的相关知识,大神请跳过!



