Built-in functions
Think of Python's built-in functions as tools in a ready-to-use toolbox. Just as you’d grab a hammer or screwdriver for specific tasks, Python offers pre-made functions for common coding tasks—like summing numbers, finding the length of a list, or checking the type of a variable.
These functions are always available, so you don’t need to install or import anything special to use them!
What are built-in functions?
Built-in functions are pre-written pieces of code included with Python. They perform specific tasks and save you time and effort. To use a built-in function, simply call it by name. For example:
print("Hello, world!")
Here, print
Why use built-in functions?
- Saves time: No need to write code for common tasks.
- Reliable: Built-in functions are well-tested and dependable.
- Improves readability: Using them makes your code clearer and easier to understand.
Commonly used built-in functions
Let’s explore some of Python’s most useful built-in functions with examples:
-
: Displays text or values on the screen.print() print("Hello, Python!") # Output: Hello, Python!
-
: Returns the number of items in an object (like a list, string, or tuple).len() fruits = ["apple", "banana", "cherry"] print(len(fruits)) # Output: 3
-
: Tells you the data type of a variable.type() age = 25 print(type(age)) # Output:
-
: Gets user input.input() name = input("What's your name? ") print("Hello, " + name + "!")
-
: Adds up all numbers in a collection.sum() numbers = [5, 10, 15] print(sum(numbers)) # Output: 30
-
andmax() : Find the highest and lowest values in a collection.min()
numbers = [2, 8, 3, 5] print(max(numbers)) # Output: 8 print(min(numbers)) # Output: 2
-
: Rounds a number to a specified number of decimal places.round() price = 5.678 print(round(price, 2)) # Output: 5.68
-
: Returns the absolute value of a number.abs() difference = -7 print(abs(difference)) # Output: 7
-
: Sorts items in a list in ascending (or descending) order.sorted() scores = [50, 20, 75, 30] print(sorted(scores)) # Output: [20, 30, 50, 75]
-
: Generates a sequence of numbers, often used in loops.range() for number in range(1, 5): print(number) # Output: # 1 # 2 # 3 # 4
Combining built-in functions
You can combine multiple built-in functions to perform more complex tasks.
Example: Calculating the average of a list of numbers:
numbers = [3, 5, 7, 9]
total = sum(numbers)
average = total / len(numbers)
print("The average is:", round(average, 2))
# Output: The average is: 6.0
Here, we used sum
len
round
Conclusion
Python’s built-in functions are your coding shortcuts—ready to handle common tasks efficiently. They save time, reduce errors, and make your code clearer and more professional. By mastering these functions, you'll unlock the ability to write powerful, concise programs.
So, dive in and explore these tools—you’ll find yourself coding faster and smarter in no time!