Python Program to Divide Integer and Float Numbers

In this article, we will learn about python program to divide integer and float numbers with examples.

Getting Started

The task is to divide an integer by float numbers in python. For example,

If a = 10 and b = 2.0, then output is 5.0.

We can do so in multiple ways –

Simple Approach

We can divide integer and float numbers using / operator in python as shown below –

 
y1 = 238
y2 = 4.2
 
result = y1 / y2  # Divide using / operator
print("Result:", result)

Output:

 
Result: 56.666666666

Using User Input

User input can be taken using input() function.

After accepting input from user, convert them to float and integer using float() and int() function respectively.

Then, we can divide those numbers using division operator i.e. / operator.

 
y1 = float(input("Enter a float number"))
y2 = int(input("Enter an integer"))

result = y1 / y2
print("{0} / {1} is {2}" .format(y1, y2, result))

Output:

 
Enter a float number
15.5
Enter an integer
3
15.5 / 3 is 5.16666666666666

Using User Input (Command Line Arguments)

Using sys.argv present in sys module, we can take input by user using command line arguments.

After accepting input from user, we need to convert them to float and integer using float() and int() function respectively.

  • Method 1

     
    import sys
    y1, y2 = sys.argv[1:3]
    print("Result:", float(y1) / int(y2))
    

    Output:

     
    Result: 0.33
    

    Run above code with command line arguments as 1.32 and 4.

  • Method 2

     
    import sys
    y1, y2 = sys.argv[1:]
    print("Result:", float(y1) / int(y2))
    

    Output:

     
    Result: 0.33
    

    Run above code with command line arguments as 1.32 and 4.

Using Lambda

We can wrap logic to divide integer by float numbers inside lambda function in python as shown below –

 
if __name__ == "__main__" :
    y1 = 76.81
    y2 = 21
 
    # Divide integer and float numbers
    divide_IntFloat = lambda y1, y2 : y1 / y2
    print("Result:", divide_IntFloat(y1, y2))

Output:

 
Result: 3.6576190476190478

Using Function

Below is a function that returns output after dividing integer by float numbers in python –

 
def divideIntFloat(y1, y2):
    return y1 / y2

print("Result:", divideIntFloat(27.5, 12))

Output:

 
Result: 2.2916666666666665

That’s how we can write python program to divide integer and float numbers with examples.

Reference: Division

Learn about more python examples at – https://tutorialwing.com/python-tutorial/

Leave a Reply