Search code examples
pythonfunctionradians

Using if statement to call a function in Python


Convert from Degree to radian and backward

def degree_to_radian(in_degree):
    angles_in_radian=(in_degree*pi)/180
    return(angles_in_radian)

def radian_to_degree(in_radian):
    angles_in_degree=in_radian*180/pi
    return(angles_in_degree)

I am required to write a program angle converter(in num, in type)

if in_type is degree then it should use the first function and if radian the second function and I shoud get somthing like this when running the program

angle_converter (2.5 , ’Degree ’)

Degree 2.5 is equal to 0.04363323129985824 Radian

angle_converter (2.5 , ’Radian ’)

Radian 2.5 is equal to 143.2394487827058 Degree

angle_converter (2.5 , ’Float ’)

Not a valid type .


Solution

  • If your language is JavaScript so use the following code else you can use same function for other language just else changing the syntax:

    Javascript:

        var angle_converter  = function(value,valueType){
           if (valueType=="degree"){
               return (value*Math.PI)/180;
           }else
           if (valueType=="radian"){
               return value*180/Math.PI;
           }
           else{
               return "Not a valid type!"
           }
        }
    
         console.log(angle_converter(2.5,"degree"))
         console.log(angle_converter(2.5,"radian"))
         console.log(angle_converter(2.5,"float"))

    Python:

    import math
    def angle_converter(value,valueType):
    
        if valueType=="degree":
            return (value*math.pi)/180;
        else:
            if valueType=="radian":
                return value*180/math.pi;
            else:
                return "Not a valid type!"
    
    #------------ USE: ------------
    print(angle_converter(2.5,'degree'))  # >> 0.0436332312999
    print(angle_converter(2.5,"radian"))  # >> 143.239448783
    print(angle_converter(2.5,"float"))   # >> Not a valid type!
    

    Live Demo

    Or this one:

    import math
    def angle_converter(value,valueType):
        if valueType=="degree":
            return degree_to_radian(value);
        else:
            if valueType=="radian":
                return radian_to_degree(value);
            else:
                return "Not a valid type!"
    
    def degree_to_radian(in_degree):
        return((in_degree*math.pi)/180)
    
    def radian_to_degree(in_radian):
        return(in_radian*180/math.pi)
    
    print(degree_to_radian(2.5))  # >> 0.0436332312999
    print(radian_to_degree(2.5))  # >> 143.239448783
    print(angle_converter(2.5,'degree'))  # >> 0.0436332312999
    print(angle_converter(2.5,"radian"))  # >> 143.239448783
    print(angle_converter(2.5,"float"))   # >> Not a valid type!