In this article, we will learn about python program to multiply two float numbers with examples.
Getting Started
The task is to multiply two float numbers in python. For example,
If a = 1.1 and b = 2.2, then output is 2.42.
We can do so in multiple ways –
- Simple Approach
- Using User Input
- Using User Input(Command Line Arguments)
- Using Lambda
- Using Function
Simple Approach
- Define two variables, a1 and a2, and store float numbers in them.
- Multiply them using multiplication operator i.e. * operator.
a1 = 17.3 a2 = 7.1 result = a1 * a2 # Get product of two float numbers using * operator print("Result =", result)
Output:
Result = 122.83
Using User Input
- Use input() method to take input from user. Then, store entered value in a1 and a2 variables.
- Multiply a1 and a2 using * operator.
a1 = float(input("Enter a number")) a2 = float(input("Enter another number")) result = a1 * a2 print("Product of {0} and {1} is {2}" .format(a1, a2, result))
Output:
Enter a number 23.2 Enter another number 4.76 Product of 23.2 and 4.76 is 110.43199999999999
Using User Input (Command Line Arguments)
- Use sys.argv in sys module in python to read input from command line arguments.
- Convert them to float using float() method.
- Then, multiply them using multiplication operator i.e. * operator.
-
Method 1
a1, a2 = sys.argv[1:3] reads two values from command line and store them in a1 and a2 variables.
import sys a1, a2 = sys.argv[1:3] print("Result:", float(a1) * float(a2))
Output:
Result: 5.8500000000000005
Run above code with command line arguments as 1.3 and 4.5.
-
Method 2
Omit second parameter in sys.argv[1:3] if we want to read all values in command line arguments.
import sys a1, a2 = sys.argv[1:] print("Result:", float(a1) * float(a2))
Output:
Result: 5.8500000000000005
Using Lambda
Lambda method can also be used to multiply two numbers in python as shown below –
if __name__ == "__main__" : a1 = 16.2 a2 = 2.5 # Multiply two float numbers multiply_twoNum = lambda a1, a2 : a1 * a2 print("Result:", multiply_twoNum(a1, a2))
Output:
Result: 40.5
Using Function
If we want to define a function that returns product of two float numbers, it can be done as below –
def multiply(m1, m2): return m1 * m2 print("Result:", multiply(15.3, 28.2))
Output:
Result: 431.46000000000004
That’s how we can write python program to multiply two float numbers with examples.
Reference: Multiplication
Learn about more python examples at – https://tutorialwing.com/python-tutorial/