本系列博文基于廖雪峰老师的官网Python教程,笔者在大学期间已经阅读过廖老师的Python教程,教程相当不错,官网链接: 廖雪峰官方网站.请需要系统学习Python的小伙伴到廖老师官网学习,笔者的编程环境是Anaconda+Pycharm,Python版本:Python3.
1.函数调用
print("-2的绝对值为:",abs(-2))
print("100的绝对值为:",abs(100))
abs1 = abs
print("-1的绝对值为:",abs1(-1))
-2的绝对值为: 2
100的绝对值为: 100
-1的绝对值为: 1
2.函数定义
"""
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)
def nop():
pass
def myAbs(x):
if not isinstance(x,(int,float)):
raise TypeError("Bad Operand Type.")
if x >= 0:
return x
else:
return -x
myAbs("A")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-21934e00955a> in <module>
15
16
---> 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))
import math
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
print("绕z轴90度的四元数为:",(eulerToQuaternion(math.pi/2,0,0)))
print("绕y轴90度的四元数为:",(eulerToQuaternion(0,math.pi/2,0)))
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的相关知识,大神请跳过!
|