Functions are one of the most important concepts in programming. It is a reusable block of code designed to perform a specific task. Also, they allow you to break code into smaller parts, making it more readable, avoiding repetitive coding, and making your programs more manageable. However, in this blog, we are not going to create a function instead using some built-in functions provided by Python and some common mistakes while using them.
Table of Contents
What is Function?
A function is an independent block of code that performs a specific task. It can take inputs, called parameters, and return some value. But why do we need functions in Python? So, when you work on a large project, you may need some code to be used multiple times. You don’t want to write the same code multiple times; that’s why functions are required that provide reusability. Hence, once you create a function, you can use it again and again.
For example,
print("Hello, World")
# Output: Hello, World
PythonThe built-in print()
function is used to print the output data in the console. To use a function, you have to just call it by using its name followed by parentheses ()
. If the function requires any input, so provide the necessary values inside the parentheses, in this case "Hello, World"
. Python provides some built-in functions that are already available and can be used directly without the need to create a function. Each function serves a specific purpose and can be used to perform common tasks without the need to write additional code.
Why Do We Need Functions?
- Reusability: As we discussed earlier, functions can be used again and again after we create them. This means we don’t have to write the same code over and over.
- Organization: Functions help us keep our code organized. This makes it easier to read and fix when needed.
- Avoiding Redundancy: Functions help us avoid repeating the same code. This reduces mistakes and saves us time.
- Abstraction: Functions use a method called abstraction, which hides complicated details behind a simple way to use them. This makes it easier for us to work with the code.
Common Built-in Functions
Here are some of the most commonly used built-in functions in Python that you must know:
1. Length
The len()
function in Python is a built-in function that returns the number of items in a sequence and collection object like a string, list, tuple, dictionary and set.
For example:
my_str = "Hello"
length = len(my_str)
print(length) # Output: 5
list_length = len([10, 20, 30, 40, 50])
print(list_length) # Output: 5
tup1 = (1, 2, 3, 4, 5)
tuple_length = len(tup1)
print(tuple_length) # Output: 5
set1 = {1, 2, 3, 4, 5}
set_length = len(set1)
print(set_length) # Output: 5
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict_length = len(dict1)
print(dict_length) # Output: 3
Python2. Sum
The sum()
function calculates the sum of all the elements in an iterable object (like a list or tuple) consisting of numbers only. Optionally, you can specify a starting value, which is added to the sum. Syntax: sum(iterable, <start>)
.
For example:
print(sum([1, 2, 3, 4]))
# Output: 10 (1 + 2 + 3 + 4)
print(sum((10, 20, 30), 5))
# Output: 65 (adds 5 to the sum)
print(sum({1.5, 2.5, 3.0}))
# Output: 7.0
Python3. Max and Min
The max()
and min()
functions return the maximum and minimum values in an iterable object, such as a list or tuple.
For example:
numbers = [5, 2, 7, 1, 3]
maximum = max(numbers)
print(maximum) # Output: 7
string = "Python"
max_char = max(string)
print(max_char) # Output: "y" (large value in ASCII)
minimum = min(numbers)
print(minimum) # Output: 1
min_char = min(string)
print(min_char) # Output: "P" (small value in ASCII)
PythonYou can also pass values directly to these functions instead of a collection or sequence like a list or tuple. Syntax: max(value1, value2, value3, …) even you can provide them with a key on which you want to get max or min.
For Example:
print(max("apple", "banana", "cherry"))
# Output: "cherry" (based on alphabetical order)
print(min("apple", "banana", "cherry"))
# Output: "apple"
Pythonwords = ["hello", "world", "Python", "AI"]
print(max(words, key=len))
# Output: "Python" (longest word)
print(min(words, key=len))
# Output: "AI" (shortest word)
PythonThis key
takes a function as a parameter, and that function takes parameters as the values provided in max
or min
function.
4. Range
The range()
function generates a sequence of numbers. It is commonly used in loops, especially for loops, to iterate over a sequence of numbers. Syntax: range(start, stop, step)
, where start is the starting value, stop is the stopping value, and step is the increment value; by default step
is 1
and start
is 0
, and you have to provide the stop
value which is not included.
For example:
print(list(range(5)))
# Output: [0, 1, 2, 3, 4]
PythonDid you notice that the output list is a range from 0 to 4? This is because the start value is default 0
and the stop value is 5
which is not included.
print(list(range(1, 6)))
# Output: [1, 2, 3, 4, 5]
print(list(range(2, 10, 2)))
# Output: [2, 4, 6, 8]
print(list(range(10, 2, -2)))
# Output: [10, 8, 6, 4]
Python5. Absolute value
The abs()
function returns the absolute value of a number. It can be used with integers, floating-point numbers, and complex numbers.
For example:
# Using abs() with an integer
print(abs(-10))
# Output: 10
# Using abs() with a float
print(abs(-3.14))
# Output: 3.14
# Using abs() with a complex number
print(abs(3 - 4j))
# Output: 5.0 (magnitude of the complex number)
Python6. Round
The round()
function rounds a floating-point number to a specified number of decimal places. It can also be used with integers. Syntax round(number, decimal_places)
where number
is the floating-point number to be rounded and decimal_places
is the number of decimal places to round to (optional, default is 0
).
For example:
# Using round() with a float
print(round(3.14159, 2))
# Output: 3.14 (rounded to 2 decimal places)
# Using round() with an integer
print(round(5))
# Output: 5 (no change)
# Rounding a float without specifying decimal places
print(round(3.6))
# Output: 4 (rounds to the nearest integer)
print(round(3.5))
# Output: 4 (rounds to the nearest integer)
# Rounding a float with a negative decimal place
print(round(1234.5678, -2))
# Output: 1200 (rounds to the nearest hundred)
PythonConclusion
In summary, being familiar with built-in Python functions can make you a more efficient, effective, and confident programmer. It allows you to write better code and solve problems more easily.