Sunday, November 3, 2019

Python tutorial 10 | numeric operations and functions

Moving on with Python Tutorials for Beginners. This Python beginner tutorial explains the useful Python numeric operations and functions with examples. It also explains how to import modules in our code. Please view the Python video tutorial 10 or read on...

First, let us see Python examples of numeric operations in Python programming.

# Python code example
i = -10
# print absolute value of i, which is 10
print (abs(i))

# use max numeric operation
# print the maximum value from a number of values, which is 100
print (max(-1, 100, 2.3, 4, 90))

# use min numeric operation
# print the minimum value from a number of values, which is -1
print (min(-1, 100, 2.3, 4, 90))

# use round numeric operation
a = 1.234
# print the float value rounded off to the nearest integer value
print (round(a))
# print the float value rounded off to 2 decimal places
print (round(a, 2))

In order to use the numeric functions available in the math module, we have to use the import statement. Then, let us see Python examples of numeric functions in Python programming.

# Python code example
import math

# use the ceiling numeric function
# i.e. print the smallest integer greater than the given value, which is 3
print (math.ceil(2.4))

# use the factorial numeric function
# print the factorial of the given integer value, which is 24
print (math.factorial(4))

# If we want to avoid typing the name of the module, we can use another form of the import statement
# import all public names from the math module
from math import *

# use the floor numeric function
# print the largest integer less than the given value, which is 3
print (floor(3.99))

# use the truncate numeric function
# print the integer value of the given value, which is 10
print (trunc(10.11))

# print the greatest common divisor of two given values, which is 5
print (gcd(10, 15))

# print the square root of the given value, which is 3.0
print (sqrt(9))

# print the value of pi
print (pi)

Want to see the Python samples working? View my Python video tutorial 10. Thank you.

No comments:

Post a Comment