Python >> Most Used Functions

2022-12-24 Python

Table of Contents

This tutorial will introduce most used functions in Python.
print(), len(), range(), sum(), min() and max(), sorted(), abs(), int() and float(), str(), round().

Python

print()

This function is used to output text or other values to the console or terminal.
Here is an example of how you can use the print() function in Python:

name = "John"
age = 30

print("My name is", name, "and I am", age, "years old.")

This code will output the following text to the console:

My name is John and I am 30 years old.

You can also use the print() function to print the value of an expression or the result of a function call. For example:

import math

print(math.pi)
print(math.sqrt(25))

This code will output the value of pi (which is approximately 3.14) and the square root of 25 (which is 5).

You can also use the print() function to print multiple values on the same line by separating them with a comma, or to print each value on a new line by using the sep parameter:

print("First value:", 1)
print("Second value:", 2)

print("First value:", 1, "Second value:", 2, sep=" ")
print("First value:", 1, "Second value:", 2, sep="\n")

The first example will output each value on a new line, while the second example will output both values on the same line separated by a space, and the third example will output each value on a new line.

len()

This function is used to get the length of a string, list, tuple, or other iterable object.

Here is an example of how you can use the len() function in Python:

name = "John"
colors = ["red", "green", "blue"]

print(len(name))
print(len(colors))

This code will output the following values:

4
3

The len() function returns the length of a string, list, tuple, or other iterable object. In this example, len(name) returns the length of the string “John” (which is 4), and len(colors) returns the length of the list [“red”, “green”, “blue”] (which is 3).

You can use the len() function with any iterable object in Python, including strings, lists, tuples, and dictionaries.

For example:

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

fruits = {"apple": 1, "banana": 2, "orange": 3}
print(len(fruits))

The first example will output 5, and the second example will output 3.

range()

Here is an example of how you can use the range() function in Python:

for i in range(5):
    print(i)

This code will output the numbers 0 through 4, one number per line:

0
1
2
3
4

The range() function generates a sequence of numbers, starting from 0 by default, and increments by 1 (also the default), and ends at a specified number. In this example, the range() function generates a sequence of numbers from 0 to 4 (not including 5).

You can also specify a start and step (increment) value for the sequence:

for i in range(2, 10, 2):
    print(i)

This code will output the numbers 2, 4, 6, 8 (not including 10):

2
4
6
8

The range() function is often used in a for loop to repeat a block of code a certain number of times. You can also use the range() function to generate a list of numbers by passing it to the list() function:

numbers = list(range(5))
print(numbers)

This code will output the list [0, 1, 2, 3, 4].

sum()

Here is an example of how you can use the sum() function in Python:

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

This code will output the sum of the numbers in the list [1, 2, 3, 4, 5], which is 15.

The sum() function adds up the elements of a sequence (such as a list or tuple) and returns the total. You can also specify a starting value for the sum using the start parameter:

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

This code will output the sum of the numbers in the list [1, 2, 3, 4, 5], plus the starting value of 10, which is 25.

You can use the sum() function with any iterable object that contains numbers, including integers, floating point numbers, and complex numbers.

For example:

decimals = [0.1, 0.2, 0.3]
print(sum(decimals))

complex_numbers = [1 + 2j, 3 + 4j, 5 + 6j]
print(sum(complex_numbers))

The first example will output 0.6, and the second example will output (9+12j).

min() and max()

These functions are used to get the minimum and maximum values in a sequence, respectively.

Here is an example of how you can use the min() and max() functions in Python:

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

This code will output the minimum and maximum values in the list [1, 2, 3, 4, 5], which are 1 and 5, respectively:

1
5

The min() function returns the minimum value in a sequence, and the max() function returns the maximum value. You can use these functions with any iterable object that contains comparable values, including strings, lists, tuples, and dictionaries.

For example:

words = ["apple", "banana", "cherry"]
print(min(words))
print(max(words))

letters = ("a", "b", "c")
print(min(letters))
print(max(letters))

The first example will output “apple” and “cherry”, and the second example will output “a” and “c”.

You can also use the min() and max() functions to find the minimum and maximum values in a dictionary by specifying the key parameter:

prices = {"apple": 0.5, "banana": 0.25, "cherry": 0.75}
print(min(prices, key=prices.get))
print(max(prices, key=prices.get))

This code will output the keys of the minimum and maximum values in the dictionary {“apple”: 0.5, “banana”: 0.25, “cherry”: 0.75}, which are “banana” and “cherry”, respectively.

sorted()

This function is used to sort a sequence in ascending order.

Here is an example of how you can use the sorted() function in Python:

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

This code will output a sorted list of the numbers in the list [5, 2, 3, 1, 4], in ascending order:

[1, 2, 3, 4, 5]

The sorted() function returns a new sorted list from the elements of a sequence (such as a list or tuple). The original sequence is not modified.

You can also use the sorted() function to sort a list of strings:

words = ["cherry", "apple", "banana"]
print(sorted(words))

This code will output a sorted list of the words in the list [“cherry”, “apple”, “banana”], in alphabetical order:

["apple", "banana", "cherry"]

You can use the reverse parameter to sort the list in descending order:

words = ["cherry", "apple", "banana"]
print(sorted(words, reverse=True))

This code will output a sorted list of the words in the list [“cherry”, “apple”, “banana”], in reverse alphabetical order:

["cherry", "banana", "apple"]

You can also use the sorted() function with a dictionary by specifying the key parameter:

prices = {"apple": 0.5, "banana": 0.25, "cherry": 0.75}
print(sorted(prices, key=prices.get))

This code will output a sorted list of the keys in the dictionary {“apple”: 0.5, “banana”: 0.25, “cherry”: 0.75}, based on the values:

["banana", "apple", "cherry"]

abs()

This function returns the absolute value of a number.

Here is an example of how you can use the abs() function in Python:

print(abs(-10))
print(abs(-3.14))
print(abs(2 + 3j))

This code will output the absolute values of the given numbers:

10
3.14
3.605

int() and float()

These functions are used to convert a value to an integer or floating point number, respectively.

Here is an example of how you can use the int() and float() functions in Python:

print(int("123"))
print(int(123.45))

print(float("123.45"))
print(float(123))

This code will output the following values:

123
123
123.45
123.0

The int() function is used to convert a value to an integer, and the float() function is used to convert a value to a floating point number.

In the first example, the int() function converts the string “123” to the integer 123. In the second example, the int() function truncates the decimal part of the float 123.45 and returns the integer 123.

In the third example, the float() function converts the string “123.45” to the float 123.45. In the fourth example, the float() function converts the integer 123 to the float 123.0.

You can also use these functions to convert values from other types to integers or floats. For example:

print(int(True))
print(float(False))
print(int([1, 2, 3]))
print(float((1, 2)))

The first example will output 1, the second example will output 0.0, the third example will raise a TypeError, and the fourth example will raise a TypeError.

Note that the int() and float() functions can only be used to convert values that can be represented as integers or floats, respectively. Attempting to convert values that cannot be represented as integers or floats will raise a ValueError or a TypeError.

str()

This function is used to convert a value to a string.

Here is an example of how you can use the str() function in Python:

number = 123
float_number = 456.789
boolean = True

print(str(number))
print(str(float_number))
print(str(boolean))

This code will output the following strings:

"123"
"456.789"
"True"

The str() function is used to convert a value to a string.

In the first example, the str() function converts the integer 123 to the string “123”. In the second example, the str() function converts the float 456.789 to the string “456.789”. In the third example, the str() function converts the boolean value True to the string “True”.

You can use the str() function to convert values of any type to a string. For example:

print(str([1, 2, 3]))
print(str((1, 2)))
print(str({"apple": 1, "banana": 2}))

The output will be like the following.

"[1, 2, 3]"
"(1, 2)"
"{'apple': 1, 'banana': 2}"

round()

This function is used to round a floating point number to the nearest whole number.

Here is an example of how you can use the round() function in Python:

print(round(3.14159))
print(round(3.14159, 2))
print(round(12345, -2))

This code will output the following values:

3
3.14
12300

The round() function is used to round a number to the nearest integer or to a specified number of decimal places.

In the first example, the round() function rounds the float 3.14159 to the nearest integer, which is 3.

In the second example, the round() function rounds the float 3.14159 to two decimal places, which is 3.14.

In the third example, the round() function rounds the integer 12345 to the nearest multiple of 100, which is 12300.

Subscribe and be the FIRST reader of our latest articles

* indicates required

Contact us