Python自定义函数的学习使用

定义函数时,需要确定函数名和参数个数;

如果有必要,可以先对参数的数据类型做检查;

函数体内部可以用return随时返回函数结果;

函数执行完毕也没有return语句时,自动return None。

函数可以同时返回多个值,但其实就是一个tuple。

测试学习代码

"""
# -*- coding: utf-8 -*-
# @Time    : 2023/9/18 21:53
# @Author  : 王摇摆
# @FileName: function.py
# @Software: PyCharm
# @Blog    :https://blog.csdn.net/weixin_44943389?type=blog
"""


def my_abs(x=None):
    if x >= 0:
        return x
    else:
        return -x


# 将自定义函数进行完善,对输入的参数进行限定:对参数类型进行检查
def my_abs1(x=None):
    if not isinstance(x, (int, float)):
        raise TypeError("bad operand type")
    if x >= 0:
        return x
    else:
        return -x

主函数

"""
# -*- coding: utf-8 -*-
# @Time    : 2023/9/18 21:47
# @Author  : 王摇摆
# @FileName: test.py
# @Software: PyCharm
# @Blog    :https://blog.csdn.net/weixin_44943389?type=blog
"""

'''
练习:请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串
'''
n1 = 255
n2 = 1000
from liaoxuefeng.dict.function import my_abs, my_abs1

if __name__ == '__main__':
    # print(str(hex(n1)))
    # print(str(hex(n2)))

    # 现在开始使用自定义Python函数
    print(my_abs(100))
    print(my_abs(-100))

    print(my_abs1('hello'))

运行结果

D:\ANACONDA\envs\pytorch\python.exe C:/Users/Administrator/Desktop/Code/Learn_Pyhon3.7/liaoxuefeng/dict/test.py
100
100
Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/Code/Learn_Pyhon3.7/liaoxuefeng/dict/test.py", line 25, in <module>
    print(my_abs1('hello'))
  File "C:\Users\Administrator\Desktop\Code\Learn_Pyhon3.7\liaoxuefeng\dict\function.py", line 21, in my_abs1
    raise TypeError("bad operand type")
TypeError: bad operand type

Process finished with exit code 1

猜你喜欢

转载自blog.csdn.net/weixin_44943389/article/details/132998958
今日推荐