Python Program to Add Integer and Float Numbers

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

Getting Started

An integer is -1, 2, 3, 4, 5 etc.

A float is 1.2, 3.0, 4.3 etc. It means float is represented with decimal point.

In this article, we will learn how to add an integer value and a float value using python programming language.

We can do so in multiple ways –

Simple Approach

Using addition operator (i.e. + operator), we can add an integer with a float number. For example,

 
x = 10
y = float(9.1)

result = x + y  # Sum of integer and float using + operator 
print("sum = ", result)

Output:

 
sum =  19.1

Using User Input

We can take user input, a integer value and a float value, and add them using + operator as shown below –

 
x = int(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
12
Enter another number
98
sum of 12 and 98.0 is 110.0

Using User Input (Command Line Arguments)

User input can also be taken as command line arguments. It can be done using sys.argv present in sys module in python.

We can add taken value in below ways –

  • Method 1

    At first, import sys module. Then, use sys.argv to read user input.

     
    import sys
    a, b = sys.argv[1:3]
    print("sum is", int(a) + float(b))
    

    Output:

     
    sum is 8.6
    

    Run above code with command line arguments as 3 and 5.6

    a, b = sys.argv[1:3] reads input from user and stores them in variable a and b.

  • Method 2

    If we don’t want to restrict to read only two values, we can omit second part in sys.argv as shown below –

     
    import sys
    a, b = sys.argv[1:]
    print("sum is", int(a) + float(b))
    

    Output:

     
    sum is 8.6
    

    Run above code with command line arguments as 3 and 5.6

Using Lambda

Using Lambda function and + operator, we can write python program to add integer and float as shown below –

 
if __name__ == "__main__" :
    num1 = 10
    num2 = float(0.4)

    # Adding integer and float
    sum_twoNum = lambda num1, num2 : num1 + num2
    print("sum =", sum_twoNum(num1, num2))

Output:

 
sum = 10.4

Using Function

Below program contains logic to add integer and float values wrapped in a python function –

 
def addIntAndFloat(a, b):
    return a + float(b)
 
print("sum =", addIntAndFloat(1, 2))

Output:

 
sum = 3.0

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

Reference: Official Doc

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

Leave a Reply