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 –
print ( "result = " , result) |
Output:
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" )) |
print ( "Product of {0} and {1} is {2}" . format (m1, m2, result)) |
Output:
Product of 34 and 6.5 is 221.0 |
- 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.
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 –
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__" : |
multiply_twoNum = lambda m1, m2 : m1 * m2 |
print ( "Result:" , multiply_twoNum(m1, m2)) |
Output:
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 –
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/