python函数大全及使用
时间: 2023-09-21 09:02:36 浏览: 58
Python是一种很流行的高级编程语言,它有着丰富的内置函数和标准库,同时也支持用户自定义函数。下面是一些Python常用函数的介绍及使用方法。
1. print()函数
print()函数是输出函数,可以将括号内的内容打印到屏幕上。
```python
print("Hello, World!") # 输出 Hello, World!
```
2. input()函数
input()函数是输入函数,可以让用户从键盘输入内容,并将输入的内容赋值给变量。
```python
name = input("请输入您的姓名:")
print("您好," + name + "!")
```
3. type()函数
type()函数可以用来获取变量的数据类型。
```python
num = 10
print(type(num)) # 输出 <class 'int'>
str = "Hello"
print(type(str)) # 输出 <class 'str'>
lst = [1, 2, 3]
print(type(lst)) # 输出 <class 'list'>
```
4. len()函数
len()函数可以用来获取列表、元组、字符串等的长度。
```python
lst = [1, 2, 3]
print(len(lst)) # 输出 3
str = "Hello"
print(len(str)) # 输出 5
```
5. range()函数
range()函数可以生成一系列数字,常用于循环中。
```python
for i in range(5):
print(i) # 输出 0, 1, 2, 3, 4
```
6. list()函数
list()函数可以将元组、字符串等转换成列表。
```python
tpl = (1, 2, 3)
lst = list(tpl)
print(lst) # 输出 [1, 2, 3]
str = "Hello"
lst = list(str)
print(lst) # 输出 ['H', 'e', 'l', 'l', 'o']
```
7. tuple()函数
tuple()函数可以将列表、字符串等转换成元组。
```python
lst = [1, 2, 3]
tpl = tuple(lst)
print(tpl) # 输出 (1, 2, 3)
str = "Hello"
tpl = tuple(str)
print(tpl) # 输出 ('H', 'e', 'l', 'l', 'o')
```
8. set()函数
set()函数可以将列表、元组等转换成集合。
```python
lst = [1, 2, 3, 2, 1]
s = set(lst)
print(s) # 输出 {1, 2, 3}
tpl = (1, 2, 3, 2, 1)
s = set(tpl)
print(s) # 输出 {1, 2, 3}
```
9. sorted()函数
sorted()函数可以将列表、元组等进行排序。
```python
lst = [3, 2, 1]
lst_sorted = sorted(lst)
print(lst_sorted) # 输出 [1, 2, 3]
tpl = (3, 2, 1)
tpl_sorted = sorted(tpl)
print(tpl_sorted) # 输出 [1, 2, 3]
```
10. max()函数和min()函数
max()函数可以获取列表、元组等中的最大值,min()函数可以获取最小值。
```python
lst = [1, 3, 2]
print(max(lst)) # 输出 3
print(min(lst)) # 输出 1
tpl = (1, 3, 2)
print(max(tpl)) # 输出 3
print(min(tpl)) # 输出 1
```
这只是Python中一小部分常用函数的介绍,Python有非常丰富的内置函数和标准库,可以根据需要自行查找使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)