Python中经常用到的10个函数
Python是一种高级编程语言,可以用于各种应用程序的开发。在Python中,函数是一种非常重要的概念,可以帮助我们组织代码、实现复杂的逻辑和操作数据。在本文中,我们将介绍Python中经常用到的10个函数。
1. print()
print()是Python中最基本的函数之一,用于将内容输出到屏幕上。它可以输出文本、数字和变量等。例如:
print("Hello World!")
print(42)
x = 3
print(x)
输出:
Hello World!
42
3
2. type()
type()函数用于查看变量的类型。Python中常见的类型有整型、浮点型、字符串、列表、元组等。例如:
x = 3
y = "Hello"
z = [1, 2, 3]
print(type(x))
print(type(y))
print(type(z))
输出:
<class 'int'>
<class 'str'>
<class 'list'>
3. len()
len()函数用于获取字符串、列表、元组等对象的长度。例如:
x = "Hello"
y = [1, 2, 3, 4]
z = (5, 6, 7)
print(len(x))
print(len(y))
print(len(z))
输出:
5
4
3
4. input()
input()函数用于从用户输入中获取数据。例如:
name = input("What is your name? ")
print("Hello, " + name + "!")
输出:
What is your name? Bob
Hello, Bob!
5. range()
range()函数用于生成一个数字序列。它有三种形式:
range(stop):生成从0到stop-1的数字序列。
range(start, stop):生成从start到stop-1的数字序列。
range(start, stop, step):生成从start到stop-1的数字序列,步长为step。
例如:
print(range(5))
print(range(1, 5))
print(range(0, 10, 2))
输出:
range(0, 5)
range(1, 5)
range(0, 10, 2)
6. int()
int()函数用于将字符串转换为整型。例如:
x = "42"
print(int(x))
输出:
42
7. str()
str()函数用于将数字或其他类型的对象转换为字符串。例如:
x = 42
y = [1, 2, 3]
print(str(x))
print(str(y))
输出:
42
[1, 2, 3]
8. max()
max()函数用于获取最大值。它可以用于数字和字符串等可比较的对象。例如:
x = [1, 3, 5, 2, 4]
y = "Hello World!"
print(max(x))
print(max(y))
输出:
5
r
9. min()
min()函数用于获取最小值。它可以用于数字和字符串等可比较的对象。例如:
x = [1, 3, 5, 2, 4]
y = "Hello World!"
print(min(x))
print(min(y))
输出:
1
10. sorted()
sorted()函数用于将可迭代对象排序并返回一个新的列表。例如:
x = [3, 2, 1, 5, 4]
y = "Python"
print(sorted(x))
print(sorted(y))
输出:
[1, 2, 3, 4, 5]
['P', 'h', 'n', 'o', 't', 'y']
