Math functions in ‘math’ module -II

             Basic mathematical functions in math module are explained in part1 post.

https://www.blogger.com/blog/post/edit/5251857942821229/5740320177801086000.

Remaining mathematical functions are explained in this blog post.

Trigonometry functions in ‘math’ module:

            Trigonometry is a field of mathematics which deals with angles. To measure angles, radian and degree are used. In ‘math’ module, there are two functions to convert radian to degree and degree to radian.

#import the math module

import math

#get the input of degree value and store as integer in ‘de’

de = int(input("Enter the degree value"))

#print the converted radian value

print(math.radians(de))

#get the input value as float and store it as float in ‘ra’

ra = float(input("Enter the radian value"))

#print the degree value

print(math.degrees(ra))

Output:

Some of the other functions are…

Sin(),cos(),tan(),sinh(),cosh(),tanh(). These built in functions are used in below program.

#import the math module.

import math

#print the sin,cos,tan,sinh,cosh,tanh values.

print(math.sin(90))

print(math.cos(30))

print(math.tan(45))

print(math.sinh(60))

print(math.cosh(90))

print(math.tanh(90))

when executing this program, user gets the below output.

Log functions in ‘math’ module:

It is the inverse function of exponentiation. The below program uses the built in log functions.

Here, log() gives the log value.

Log10() returns the log 10 value.

Log2() provides the log 2 value.

Log1p denotes log 1+p value.

#program to print log values

import math

#prints the log values of different base.

print(math.log(16))

print(math.log10(23))

print(math.log2(2))

print(math.log1p(34))

output:

These are various functions in ‘math’ built in module.

 

Math function in python

    Python has variety of built in modules. One of the commonly used module is “math”. It has many built in functions and constants.

To use this module, use the keyword “import”

import math

It has some constant values that are listed below.

#This program uses the math constants.

import math

#math.pi gives the pi value (3.14…).

print(math.pi)

#math.e denotes euler’s number.

print(math.e)

#math.tau represents tau.

print(math.tau)

#math.inf gives floating point infinity value.

print(math.inf)

#math.nan provides floating point not a number value.

print(math.nan)

When executing this program, the user gets the below output.

output:

3.141592653589793

2.718281828459045

6.283185307179586

inf

nan

 

math module’s functions:

            math module has variety of built in functions for performing basic mathematical calculations to advanced calculations.

Here, some of the basic mathematical functions are listed below.

math built in functions: ceil(), floor() ,fabs():

            As we know already, ceil is used to round up the number to nearest integer. Function floor gives down to nearest integer. ‘fabs’ returns you the absolute value.

#math function ‘ceil’, ‘floor’, ‘fabs’

import math

#ceil function round up the number.

print(math.ceil(15.6))

#floor function returns the down integer value.

print(math.floor(15.6))

#fabs gives you the exact value.

print(math.fabs(45.8))

The output of the program is

Math built in functions: factorial(), fmod(), gcd() :

            Here, ‘factorial’ returns the factorial value of the given number. ‘fmod’ gives you the reminder value. ‘gcd’ finds the greatest common factor of the given numbers.

import math

#It prints the factorial value of 6.

print(math.factorial(6))

#This line prints the reminder value of 10/3 as floating number.

print(math.fmod(10,3))

#This statement gives you the greatest common factor between 45 and 55.

print(math.gcd(45,55))

Output is

math built in functions :pow(),sqrt(), trunc() :

            These three are the commonly used functions. ‘pow’ is used to give the number’s multiple value. ‘sqrt’ gives you the square root of a variable.’trunc’ returns the integer part of the number.

import math

#This dispalys the 2*2*2*2*2 value.

print(math.pow(2,5))

# This function returns the square root of the number 25.

print(math.sqrt(25))

#trunc returns the integer value.

print(math.trunc(56.4))

 While executing this program, you will get the below output.

These are the basic math functions and constants used in ‘math’ module.

Python scope

   Scope of a variable depends on the place, where it is defined and where it is used. Based on this, variables have categorized into following types.

  • ·       Local
  • ·       Non local
  • ·       Global

1. Local variables:

              These are the normal variables that any user use. Let, a variable t is defined inside a function.

Its scope is applicable within the function or file.

Eg:

a = 56

print(a)

Here, a is the local variable. its scope is within this program.

Next, local variable  is defined inside a function is given below.

def  its_fn():

     b = 99

     print(b)

#function call is given below.

its_fn()

while executing this program, you get the below output.


Text Box: 99

 2.Non local variables.

              When a function is defined inside the other function, this scope is used. Same variable name is used in many functions, the developer wants to differentiate it by the keyword “non local”.

#define a function its_fn() .Declare a variable ‘b’. This is the local variable.

def its_fn():

    b = 99

#Define a function  its_fn1(). Declare a nonlocal b and assign the value. call this function in its_fn() definition and return the value.

    def its_fn1():

        nonlocal b

        b = "Best wishes"

    its_fn1()

    return b

#call the its_fn() and print the value.

print(its_fn())

The output is given below.

Best Wishes

3.Global variable:

              A variable is defined and it can be used anywhere of the program. Here,the keyword is “global”

#Let a variable ‘b’ is assigned with a value 99. It is considered as local variable.

b = 99

#let a function its_fn() is defined. Here, variable ‘b’ is declared as global and assigned with 199.

def its_fn():

    global b

    b = 199

#call the function its_fn()

its_fn()

#print the value of b. it prints the global variable value.

print(b)


So, the output is

 Text Box: 199

 These are the various types of variables used in python and its scope is explained with examples.

How to do Exception handling in python??

               A good developer knows about the structure of proper coding. It’s always good to practice exception handling mechanisms.

In python, we have the following mechanisms for exception handling.

  1. try except
  2. try, except, else
  3. Using finally

1.try except exception handling:

              This is the common method used in many languages. Try is the beginning keyword. It follows a coding block and end by a keyword “except” follows a statement.

Syntax:

try:

 coding block

except:

 a line of statement.

For example,

#Get a float number

a = float(input("Enter the number"))

#Create a try except block using the print statement.

try :

     print(a/0)

except:

     print("Exception occurred")

The outcome of this program is

Enter the number 45.7

Exception occurred

2.try,except,else:

              When a condition occurs, the user has two options. Either true or false. If the condition is true, it follows a set of statements. Otherwise, if one more control statement occurs, it follows another set of statements.

Syntax:

 try :

       ----------

       ----------

except :

    ------------

    ------------

else :

     ------------

     ------------

Example:

#Enter the two values a and b.

a = int(input("Enter the numerator"))

b = int(input("Enter thedenominator"))

#use the values for division. If the denominator is zero. It creates an exception. Else it prints the output.

try:

     d = a/b

except:

         print("Your denominator value is zero. please change it to non zero value")

else:

        print("Your answer is",d)

output:


  3.Using finally:

This is one of the error handling mechanisms in python. This keyword “finally” can be added in the code to execute the final statement in the block

Syntax:

---------------

---------------

finally :

Set of statements to execute…….

Eg:

#create a function fn_final(). Print the values according to the flow of control. Add the print statement to try,except and else block.

def fn_final():

    try:

        print("The control is in try block")

    except exception as er:

        print(er)

    finally:

        print("The control is in finally block")

  #call the function and print the returned value.     

print(fn_final())

These are the error handling mechanisms in python.

Common errors in python

               These are special conditions which may occur due to some situations. Some of the commonly known errors are listed below.

  1. 1.       Assertion error
  2. 2.       Attribute error
  3. 3.       Value error
  4. 4.       Tab error
  5. 5.       Import error
  6. 6.       Index error

1.Assertion error:

              When an assertion statement fails, this error occurs.

Eg:

 a = 5

 b =  10

 assert b < a , “b is less than a”

when executing this, you get the assertion error.


2. Attribute Error:

              It occurs while assigning values to attributes or related operations.

Eg:


 Here, append function is not available with float attributes.

3. Value Error :

              User enters data in right datatype,but the value is in wrong datatype. Here, user enters string, but it changed to int.

Eg:

4. Tab error:

              Python follows indentation in each line of code. Generally,4 spaces or 1 tab space used for indentation. If it fails, this error occurs.

Refer my basic errors blog.

https://rajeeva84.blogspot.com/2024/05/basic-errors-in-python.html

5. Import Error:

              When a module imported fails to open, this error occurs.

from greetings import greet1,greet2

greet1.message1()

greet2.message2()


 6.Index error:

              User enters out of range element in a list, this error occurs.

Some of the other errors  involves the user interrupts  keyboard input or programs run out of the memory in the system.

These are common errors in python.