Let us understand some of the common numeric functions we use with Python as a programming language.
We have functions even for standard operators such as +
, -
, *
, /
under a library called as operator. However, we use operators more often than functions.
add
for+
sub
for-
mul
for*
truediv
for/
We can use pow
for getting power value.
We also have the math
library for some advanced mathematical operations.
Also, we have functions such as min
, max
to get the minimum and maximum of the numbers passed.
4 + 5
5 % 4
We can also perform arithmetic operations using the operator library. It includes functions such as add
, sub
, mul
, and truediv
.
import operator
from operator import add, sub, mul, truediv
add(4, 5)
truediv(4, 5)
The math
module provides several important functions which are useful on a regular basis.
Here are some of the important functions from math
:
pow
ceil
- get the next integer to the passed decimal value.floor
- get the prior integer to the passed decimal value.round
- it is not from themath
module and is typically used to get the prior or next integer. It will give us the prior integer if the decimal is up to.5
. If the decimal is greater than.5
, thenround
will return the next integer.
import math
math.pow(2, 3)
math.ceil(4.4)
math.floor(4.7)
round(4.4)
round(4.7)
round(4.5)
round(4.662, 2) # You can also round a decimal to the desired number of decimal places.
math.sqrt(2)
We can use min
to get the minimum of passed numbers. You can pass as many numbers as you want.
min(2, 3)
We can use max
to get the maximum of passed numbers. You can pass as many numbers as you want.
max(2, 3, 5, 1)
Hands-On Tasks
Perform the following tasks to practice using the numeric functions discussed:
- Calculate the power of 3 to the 4th.
- Find the square root of 16 using the
math
library.
Conclusion
In this article, we explored common numeric functions in Python, including basic arithmetic operations, advanced math functions, and finding the minimum and maximum of numbers. Remember to practice these functions to strengthen your Python skills and engage with the community for further learning.