In Python, functions are an essential part of the language and provide a way to encapsulate reusable blocks of code. Here are some built-in functions in Python along with examples:
print()– Displays output to the console.print("Hello, World!")
len()– Returns the length of an object.fruits = ["apple", "banana", "orange"]print(len(fruits)) # Output: 3
input()– Reads user input from the console.name = input("Enter your name: ")print("Hello, " + name + "!")
range()– Generates a sequence of numbers.for num in range(5):print(num) # Output: 0, 1, 2, 3, 4
type()– Returns the type of an object.x = 5print(type(x)) # Output: <class 'int'>
str()– Converts an object into a string representation.num = 10 num_str = str(num)print(num_str) # Output: "10"
sum()– Returns the sum of elements in an iterable.numbers = [1, 2, 3, 4, 5]total = sum(numbers)print(total) # Output: 15
sorted()– Returns a new sorted list from an iterable.fruits = ["orange", "banana", "apple"]sorted_fruits = sorted(fruits)print(sorted_fruits) # Output: ["apple", "banana", "orange"]
max()andmin()– Returns the maximum and minimum values from an iterable.numbers = [5, 3, 9, 1, 7]max_num = max(numbers)min_num = min(numbers)print(max_num, min_num) # Output: 9 1
abs()– Returns the absolute value of a numberx = -5abs_value = abs(x)print(abs_value) # Output: 5
These are just a few examples of built-in functions in Python. Python provides a rich library of functions for various purposes. Additionally, you can define your own functions to perform custom operations and tasks.