Python- 函数(1)


#函数
# help() 查看函数信息
help(abs)
#abs(x, /)  Return the absolute value of the argument.
abs(-5)#5
#函数传入参数有误 会报TypeError 错误
#abs(-5,-1)#TypeError: abs() takes exactly one argument (2 given)
#如果传入参数数量是对的,参数类型错误也会报 TypeError 错误
#abs('a')#TypeError: bad operand type for abs(): 'str'


#help(max)
#max(...)
# max(iterable, *[, default = obj, key = func]) -> value
# max(arg1, arg2, *args, *[, key = func]) -> value
# With a single iterable argument, return its biggest item.The default keyword - only
# argument specifies an object to return if the provided iterable is empty.
# With two or more arguments, return the largest argument.
max('abcdef')#f
max(1,2,3,4,5)#5

#数据类型转换
int('123')      # int: 类型 123
int(12.34)    # int: 类型 12 忽略小数部分 int('12.34') 会报错
float('12.34')  # float: 类型 12.34
str(1.23)       # 字符串: '1.23'
str(100)        # 字符串: '100'
bool(1)         # bool: True
bool('')        # bool: False

# 函数可以赋值给变量 相当于给函数起别名
a = abs
a(-1)# -1

hex(32)#0x20 把10进制转换为16进制


# 定义函数 def `函数名(参数1,参数2):` 用return 返回结果

# 自定义求绝对值
def my_abs(x):
    if x < 0:
        return  -x
    else:
        return  x
# 函数可以没有 return 关键字, 这时返回 None

# 空函数 pass 语句 用做占位符, 函数还没想好怎么写,先占着,让程序跑起来
def nop():
    pass
# pass 用在 if 语句中
age = 0
if age >= 18:
    pass


# 函数参数检查  只做数量检查,布恩那个进行参数类型检查,我们可以自己检验参数类型
# 如: abs(1,2) #TypeError: abs() takes exactly one argument (2 given)
#my_abs('a') # TypeError: '<' not supported between instances of 'str' and 'int'
# 好像也可以做参数类型检查

# 自己做参数类型检查
def my_abs_a(x):
    if not isinstance(x,(int,float)):
        raise TypeError('bad operand type')
    if x < 0:
        return -x
    else:
        return x
#my_abs_a('a')# 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)# x = 151.96152422706632 y = 130.0
# 上面的 x,y 其实是一个 tuple
r = move(100,100,60,math.pi/6) # r = (151.96152422706632, 130.0)


#练习  求一元二次方程: ax^2 + bx+ c =0
import math
def quadratic(a:float,b:float,c:float):
    a = float(a)
    b = float(b)
    c = float(c)
    x1 = 0
    x2 = 0
    if b*b -4*a*c > 0:
        x1 = (-b + math.sqrt(b*b - 4 * a * c)) / (2*a)
        x2 = (-b - math.sqrt(b*b - 4 * a * c)) / (2*a)
    return x1, x2

quadratic(2,3,1)#(-0.5, -1.0)
aa = quadratic(1,3,-4)#(1.0, -4.0)


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 课程概要:1、认识函数2、形参与实参3、全局变量与局部变量4、函数的使用与返回值5、文档字符串(Python中特有...
    LuCh1Monster阅读 3,685评论 0 1
  • 测验1: 执行这两个函数的时候分别做了几次乘法运算? 其中 square 函数就是个求方的函数 这里重点测试的是对...
    法号无涯阅读 1,814评论 0 0
  • 最近整理了一下Python使用经验,希望对于脑海中Python函数的相关知识进行一下梳理。因为内容可能会比较多,所...
    _Zhao_阅读 3,785评论 0 8
  • 变量本质上是一个占位符 就是先把那个位置用变量占上,表示这里有一个东西,至于这个位置放什么东西,以后再说,反正先用...
    SateZheng阅读 1,950评论 0 0
  • 现在的人讲究颜值,特别是明星达人,颜值高者粉丝如潮,一出场便万人空巷。在自媒体异常发达的今天,普通人物颜值高...
    目送归鸿阅读 3,762评论 2 3

友情链接更多精彩内容