网络编程
位置:首页>> 网络编程>> Python编程>> 代码详解Python的函数基础(1)

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

作者:FUXI_Willard  发布时间:2023-08-16 17:47:22 

标签:Python,函数,基础

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)
 

来源:https://fuxi-willard.blog.csdn.net/article/details/122657365

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com