【第9章】 Python的内建函数

本文介绍了Python中的几个重要内建函数,如abs()用于获取绝对值,bool()用于判断真假等,并通过实例演示了如何使用这些函数。同时,还介绍了dir()函数,用于查看变量或对象可用的方法和属性。

9.1 12个内建函数

  • abs函数:返回一个数字的绝对值

  • >>> print(abs(-10))
    10

    bool函数:根据这个参数的值返回真假

  • >>> print(abs(-10))
    10
    >>> print(bool(1))
    True
    >>> print(bool(None))
    False
    >>> print(bool('a'))
    True

    bool函数对于空的列表,元组和字典返回False,否则就返回True

  • >>> my_sily_list = []
    >>> print(bool(my_sily_list))
    False
    >>> my_sily_list = ['s','i','l','y']
    >>> print(bool(my_sily_list))
    True

    例子分析:

    • 第一行使用input函数把输入保存到变量year中(不包括Year of birth),(回车键也会保存到变量中)
    • rstrip函数:把字符串结尾的空白和回车删除
    • not关键字:如果函数没有返回True的话才做这件事
  • >>> year = input('Year of birth') Year of birth >>> if not bool(year.rstrip()): print('You need to enter a value for your year of birth') You need to enter a value for your year of birth

    dir函数:可以返回任何值的相关信息,显示对一个列表值可用的函数(可以作用于字符串,数字,函数,模块,对象,类)

  •  

    >>> dir(['a','short','list'])
    ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

     

    快速查找一个变量可以做什么

  • >>> dir(pop)
    ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

     

 

转载于:https://www.cnblogs.com/jiaqianghan/p/8351352.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值