Python Program to Divide Two Float Numbers

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

Getting Started

The task is to divide two float numbers in python. For example,

If a = 4.8 and b = 2.4, then output is 4.8 / 2.4 = 2.0

We can do so in multiple ways –

Simple Approach

Using / operator, we can divide two float numbers in python as shown below –

 
z1 = 4.8
z2 = 2.4

result = z1 / z2  # Divide using / operator
print("Result:", result)

Output:

 
Result: 2.0

Using User Input

  • Accept input from user using input() function.
  • After that, convert them to float using float() function.
  • Then, divide both numbers using / operator and print result using print() function.
 
z1 = float(input("Enter a float number"))
z2 = float(input("Enter another float number"))

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

Output:

 
Enter a float number
4.8
Enter another float number
2.4
4.8 / 2.4 is 2.0

Using User Input (Command Line Arguments)

  • Accept user input from command line arguments using sys.argv in sys module.
  • Then, convert input to float numbers using float() numbers.
  • After that, divide both numbers using / operator.
  • Method 1

     
    import sys
    z1, z2 = sys.argv[1:3]
    print("Result:", float(z1) / float(z2))
    

    Output:

     
    Result: 2.0
    

    Run above code using command line arguments as 4.8 and 2.4.

  • Method 2

     
    import sys
    z1, z2 = sys.argv[1:]
    print("Result:", float(z1) / float(z2))
    

    Output:

     
    Result: 2.0
    

    Run above code using command line arguments as 4.8 and 2.4.

Using Lambda

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

 
if __name__ == "__main__" :
    z1 = 7.68
    z2 = 2.41
 
    # Divide two float numbers
    divide_Float = lambda z1, z2 : z1 / z2
    print("Result:", divide_Float(z1, z2))

Output:

Result: 3.186721

Using Function

We can write a function in python to divide two float numbers as shown below –

 
def divideFloat(z1, z2):
    return z1 / z2

print("Result:", divideFloat(415.2, 21.7))

Output:

 
Result: 19.13

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

Reference: Division

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

Leave a Reply