欢迎访问宙启技术站
智能推送

Python开发实战:10个常用函数示例

发布时间:2023-06-25 08:14:53

Python是一种非常流行的编程语言,拥有很多常用的函数,可以帮助您提高编程效率和减少代码量。在本文中,我们将分享10个常用的Python函数示例,帮助您更好地理解Python的实际应用。

1. print()

print()函数是Python中最常用的函数之一,可以将文本或变量输出到终端。可以在print()函数中添加多个参数,每个参数之间用逗号分隔。

例如:

name = 'Bob'
print('Hello', name)

输出:

Hello Bob

2. input()

input()函数可以从用户获取输入内容,将用户输入的数据作为字符串返回。

例如:

name = input('What is your name? ')
print('Hello', name)

输出:

What is your name? Bob
Hello Bob

3. len()

len()函数可以计算字符串或列表的长度。

例如:

text = 'Hello, World!'
print(len(text))

numbers = [1, 2, 3, 4, 5]
print(len(numbers))

输出:

13
5

4. str()

str()函数可以将不同类型的数据转换为字符串格式。

例如:

year = 2022
print(str(year) + ' is coming soon!')

输出:

2022 is coming soon!

5. int()

int()函数可以将字符串转换为整数。

例如:

age = input('What is your age? ')
age = int(age)
print('Next year, you will be', age+1, 'years old.')

输出:

What is your age? 25
Next year, you will be 26 years old.

6. float()

float()函数可以将字符串转换为浮点数。

例如:

price = input('What is the price? ')
price = float(price)
discount = 0.2
total = price * (1 - discount)
print('The total is', total)

输出:

What is the price? 100
The total is 80.0

7. max()

max()函数可以找到列表中最大的元素。

例如:

numbers = [3, 1, 5, 4, 2]
print('The maximum number is', max(numbers))

输出:

The maximum number is 5

8. min()

min()函数可以找到列表中最小的元素。

例如:

numbers = [3, 1, 5, 4, 2]
print('The minimum number is', min(numbers))

输出:

The minimum number is 1

9. sorted()

sorted()函数可以将列表中的元素按照升序排列。

例如:

numbers = [3, 1, 5, 4, 2]
sorted_numbers = sorted(numbers)
print('The sorted numbers are', sorted_numbers)

输出:

The sorted numbers are [1, 2, 3, 4, 5]

10. range()

range()函数可以生成一系列连续的整数。

例如:

for i in range(1, 6):
    print(i)

输出:

1
2
3
4
5

以上是十个常用的Python函数示例,可以帮助您更好地理解Python的实际应用。在编写Python代码时,可以灵活运用这些函数,提高编程效率和减少代码量。