8个实用的Python内置函数

发布时间:2023-12-25 23:35:39

大家好,Python是一种简单而强大的编程语言,作为Python编程的基础,掌握一些实用的内置函数对于初学者来说是至关重要的。本文将介绍8个适合初学者的实用Python内置函数。

1.?print()

print('apple')
print('orange')
print('pear')

#?apple
#?orange
#?pear

将某些内容输入print()中时,它会被打印到终端(也称为标准输出)。

2.?abs()

print(abs(-5))??#?5
print(abs(6))???#?6

abs()给出了一个数的绝对值,负数变成正数,而正数保持不变。

3.?input()

通过input()函数,可以要求用户在Python程序中输入某些内容。

name?=?input('what?is?your?name??')
print('your?name?is?'?+?name)

#?what?is?your?name??tom
#?your?name?is?tom

注意,input()始终返回一个字符串值。因此,如果用户想要数字或其他任何值,需要自己进行必要的类型转换。

4.?range()

range()作为for循环的一部分,允许多次重复代码操作,而不需要多次复制和粘贴代码。

for?i?in?range(5):
??print('apple')

#?apple
#?apple
#?apple
#?apple
#?apple

5.?dir()

x?=?'apple'
print(dir(x))

#?['__add__',?'__class__',?'__contains__',?'__delattr__',?
#?'__dir__',?'__doc__',?'__eq__',?'__format__',?'__ge__',?
#?'__getattribute__',?'__getitem__',?'__getnewargs__',?
#?'__getstate__',?'__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',?'isascii',?'isdecimal',?'isdigit',?
#?'isidentifier',?'islower',?'isnumeric',?'isprintable',?
#?'isspace',?'istitle',?'isupper',?'join',?'ljust',?
#?'lower',?'lstrip',?'maketrans',?'partition',?
#?'removeprefix',?'removesuffix',?'replace',?'rfind',?
#?'rindex',?'rjust',?'rpartition',?'rsplit',?'rstrip',?
#?'split',?'splitlines',?'startswith',?'strip',?
#?'swapcase',?'title',?'translate',?'upper',?'zfill']

将某个对象传递给dir()时,可以打印出该对象中存在的每个方法或属性,想要快速检查某个对象可能具有的方法/属性时会很有帮助(而无需上网查找文档)。

6.?help()

help(print())


#?Help?on?NoneType?object:

#?class?NoneType(object)
#??|??Methods?defined?here:
#??|
#??|??__bool__(self,?/)
#??|??????True?if?self?else?False
#??|
#??|??__hash__(self,?/)
#??|??????Return?hash(self).
#?...

将某个内容传递给help()时,它会自动打印出其文档,如果不想上网查找某些文档,这也是很有用的。

7.?len()

print(len('apple'))????#?5
print(len('orange'))???#?6
print(len('pear'))?????#?4

当我们将某个内容传递给len()时,可以得到该对象的长度(如果对象没有长度,例如整数,将得到一个错误)。

8.?max()min()

print(max(1,3,2))??#?3
print(min(1,3,2))??#?1

max()查找最大的对象,而min()查找最小的对象。

?本文简单介绍了8个适合初学者的实用Python内置函数,包括print()abs()input()range()dir()help()len()max()min()。这些函数是Python编程中不可或缺的工具,能够帮助大家执行各种常见任务,掌握这些函数能更好地理解和使用Python编程语言。

文章来源:https://blog.csdn.net/csdn1561168266/article/details/135210679
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。