Python Program to Multiply Integer and Float Numbers

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

Getting Started

The task is to multiply an integer and a float numbers in python. For example,

If a = 2 and b = 3.1, then output is 2 x 3.1 = 6.2.

We can do so in multiple ways –

Simple Approach

Using multiplication operator (i.e. * operator), we can perform multiplication operator as shown below –

 
m1 = 14.6
m2 = 7
 
result = m1 * m2  # Get product of integer and float numbers using * operator 
print("result = ", result)

Output:

 
result =  102.2

Using User Input

If we want to multiply integer and float numbers taken as input from user, we can do so as shown below –

 
m1 = int(input("Enter a number"))
m2 = float(input("Enter another number"))
 
result = m1 * m2
print("Product of {0} and {1} is {2}" .format(m1, m2, result))

Output:

 
Enter a number
34
Enter another number
6.5
Product of 34 and 6.5 is 221.0

Using User Input (Command Line Arguments)

  • Read value from command line arguments using sys.argv present in sys module in python.
  • Then, convert one value into integer using int() function.
  • Convert another integer using float number using float() function.
  • Multiply both numbers using multiplication operator.
  • Method 1

    m1, m2 = sys.argv[1:3] reads two values from command line arguments and store them in m1 and m2.

     
    import sys
    m1, m2 = sys.argv[1:3]
    print("Result:", int(m1) * float(m2))
    

    Output:

     
    Result: 57.39999999999999
    

    Run above code using command line arguments 7 and 8.2

  • Method 2

    If we don’t want to restrict number of variables to be read from command line argument, we can omit second parameter in sys.argv[1:] as shown below –

     
    import sys
    m1, m2 = sys.argv[1:]
    print("Result:", int(m1) * float(m2))
    

    Output:

     
    Result: 57.39999999999999
    

Using Lambda

Lambda function and multiplication can perform the task to multiply integer with float numbers as shown below –

 
if __name__ == "__main__" :
    m1 = 16
    m2 = 2.5
 
    # Multiply integer and float numbers
    multiply_twoNum = lambda m1, m2 : m1 * m2
    print("Result:", multiply_twoNum(m1, m2))

Output:

 
Result: 40.0

Using Function

If we want to define a function in python that can multiply integer and float numbers, we can do so as shown below –

 
def multiply(m1, m2):
    return m1 * m2
  
print("Result:", multiply(15.3, 28))

Output:

 
Result: 428.40000000000003

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

Reference: Multiplication

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

Leave a Reply