In this article, we will learn about python program to add two float numbers with examples
Getting Started
Float numbers consist of decimal point. For example, 1.2, 1.0, 3.0, 3.6 etc.
In this article, our task is to write python program that can add two floating point numbers.
We can do so in multiple ways –
- Simple Approach
- Using User Input
- Using User Input(Command Line Arguments)
- Using Lambda
- Using Function
Simple Approach
Two float numbers in python can be added using addition operator (i.e. + operator) as shown below –
x = float(7.1) y = float(8.3) result = x + y # Get sum of two floats using + operator print("result = ", result)
Output:
result = 15.4
Using User Input
We can also take float numbers as input from user and add them as shown below –
x = float(input("Enter a number")) y = float(input("Enter another number")) result = x + y print("sum of {0} and {1} is {2}" .format(x, y, result))
Output:
Enter a number 1.2 Enter another number 4.3 sum of 1.2 and 4.3 is 5.5
float() converts input from user to float numbers. Using + operator, we add them and printed result using print() function.
Using User Input (Command Line Arguments)
sys.argv present inside sys module in python is used to take input from user using command line arguments.
We can take input from user and convert them into float numbers using float() function. Then, add them and print result using print() function.
-
Method 1
import sys a, b = sys.argv[1:3] print("sum is", float(a) + float(b))
Output:
sum is 16.0
Run above program using command line arguments 12 and 4.
In above code,- a, b = sys.argv[1:3] reads input from user as command line arguments. Then, stores them to variable a and b.
- float() converts value of a and b into float numbers
- Then, print result using print() function.
-
Method 2
If we don’t want to restrict number of values to be read from command line, we can omit second part in sys.argv as shown below –
import sys a, b = sys.argv[1:] print("sum is", float(a) + float(b))
Output:
sum is 16.0
Run above program using command line arguments 12 and 4.
-
Method 3
We can write previous code in more pythonic way as shown below –
import sys summ = sum(float(i) for i in sys.argv[1:]) print("sum is", summ)
Output:
sum is 16.0
Run above program using command line arguments 12 and 4.
Using Lambda
We can wrap logic to add two float numbers in python inside lambda as shown below –
if __name__ == "__main__" : num1 = 1 num2 = 2 # Adding two floats sum_twoNum = lambda num1, num2 : float(num1) + float(num2) print("sum =", sum_twoNum(num1, num2))
Output:
sum = 3.0
Using Function
We can also a function that returns sum of two float numbers in python as shown below –
def addTwoFloats(a, b): return float(a) + float(b) print("sum =", addTwoFloats(1, 2))
Output:
sum = 3.0
That’s how we can write python program to add two float numbers with examples.
Reference: Official Doc
Learn about more python examples at – https://tutorialwing.com/python-tutorial/