Python Program to Add Two Numbers

Posted in

Python Program to Add Two Numbers
vinaykhatri

Vinay Khatri
Last updated on November 21, 2024

    In this Python tutorial, you will learn how to write code in Python to add two numbers.

    Prerequisites to Built the Program

    Python Program to Add Two Numbers

    number_1 = 100
    number_2= 200
    
    addition = number_1+number_2
    
    print("The sum of {0} and {1} is:".format(number_1,number_2),addition)

    Output

    The sum of 100 and 200 is: 300

    Similarly, we can perform the other operation on two numbers, such as multiplication (*), division (//), floor division (//), etc. In this above example, we have created a program where both the numbers were predefined, but python also provides us input() function, which allows us to write a program where we can accept input from the user.

    Sum of Two Numbers Provided by The User:

    number_1 = input("Enter the First Number: ")
    number_2= input("Enter the Second Number: ")
    
    addition = float(number_1) + float(number_2)
    
    print("The sum of {0} and {1} is:".format(number_1,number_2),addition)

    Output

    Enter the First Number: 124.67
    Enter the Second Number: 224.987
    The sum of 124.67 and 224.987 is: 349.657

    Behind the Code

    In this above example, we have used the input() function to accept numbers from the user, and here when we perform the addition operation, we used the float() function on both the numbers because when the python use the input() function to accept the user's input, it stores that input in the string format, but here we want numeric data, so we explicitly convert that string data into a float data type. Float represents all the numeric values, positive and negative, with decimal values.

    People are also reading:

    Leave a Comment on this Post

    0 Comments