10个用Python编写的常用函数
1. print()
The print() function is used to output text or data to the console. It can take a single argument or multiple arguments separated by commas.
Example:
print("Hello, world!")
Output:
Hello, world!
2. input()
The input() function is used to accept user input from the console. It takes an optional prompt string argument and returns a string.
Example:
name = input("What is your name? ")
print("Hello, " + name)
Output:
What is your name? John
Hello, John
3. len()
The len() function is used to determine the length of a string, list, or tuple.
Example:
s = "Hello, world!"
print(len(s))
Output:
13
4. range()
The range() function is used to generate a sequence of numbers. It can be used to iterate over a loop a specific number of times or to create a list of numbers.
Example:
for i in range(5):
print(i)
Output:
0
1
2
3
4
5. max() and min()
The max() and min() functions are used to find the maximum and minimum values in a list or tuple.
Example:
nums = [4, 10, 3, 8]
print(max(nums))
print(min(nums))
Output:
10
3
6. sorted()
The sorted() function is used to sort a list or tuple in ascending order. It returns a new list or tuple.
Example:
nums = [4, 10, 3, 8]
sorted_nums = sorted(nums)
print(sorted_nums)
Output:
[3, 4, 8, 10]
7. sum()
The sum() function is used to find the sum of all the elements in a list or tuple.
Example:
nums = [4, 10, 3, 8]
print(sum(nums))
Output:
25
8. zip()
The zip() function is used to combine two or more lists or tuples into a single list of tuples.
Example:
names = ["John", "Mary", "Tom"]
ages = [20, 25, 30]
zipped_data = zip(names, ages)
print(list(zipped_data))
Output:
[('John', 20), ('Mary', 25), ('Tom', 30)]
9. open()
The open() function is used to open a file in read or write mode.
Example:
file = open("file.txt", "r")
print(file.read())
Output:
Content of the file
10. range()
The range() function is used to generate a sequence of numbers. It can be used to iterate over a loop a specific number of times or to create a list of numbers.
Example:
for i in range(5):
print(i)
Output:
0
1
2
3
4
