Python - Adding numbers

In this program, you will learn how to add numbers.


Program Code : 1



    # Add Two Numbers
    num1 = 5
    num2 = 10
    
    # Example 1 : Add Two Numbers and prints the value
    print('sum = ', num1 + num2)

Output



    sum = 15

In this program, the variables num1 and num2 are having numeric values. Adding two numbers and printing the result without assigning it to any variable.

Program Code : 2



    # Add Two Numbers
    num1 = 5
    num2 = 10
    
    # Example 2 : Add Two Numbers and assign the value to sum variable
    sum = num1 + num2
    #print the value of sum variable
    print('sum = ',sum)
        
        

Output


    sum = 15
        

In this program, the variables num1 and num2 are having numeric values and assigned the results to sum variable. The result 15 is stored in sum variable and printing it.

Program Code : 3



    # Example 3: Print the sum of two numbers
    sum = num1 + num2
    print('The sum of {0} and {1} is {2}'.format(num1,num2,sum))
            
            

Output


    The sum of 5 and 10 is 15
            

In this program, printing the values of num1, num2 and sum variables in the format of the string.

The num1, num2, and sum values replaced with place holders {0}, {1}, and {2} respectively.

Program Code : 4



    # Example 4: Add Two Numbers With User Input
    num1 = input('Enter First Number: ')
    num2 = input('Enter Second Number: ')
        
    sum = int(num1) + int(num2)
    print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
            
            

Output


    Enter First Number: 5
    Enter Second Number: 10
    The sum of 5 and 10 is 15
            

In this program, you can enter your desired numbers to add them. The first number value is assinged to num1 variable and the second number value is assigned to num2 variable.

To adding the numbers, you should type cast each number to int data type. Print num1, num2, and sum values in the format of string

Program Code : 5



    # Example 5: Add Two Numbers (Decimal) With User Input
    num1 = input('Enter First Number: ')
    num2 = input('Enter Second Number: ')
    
    sum = float(num1) + float(num2)
    print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
            
            

Output


    Enter First Number: 5.7
    Enter Second Number: 10.3
    The sum of 5.7 and 10.3 is 16.0
            

In this program, you can enter your desired numbers in decemal format to add them.

The first number value is assinged to num1 variable and the second number value is assigned to num2 variable. To adding decimal numbers, you should type cast each number to float data type.

Display num1, num2, and sum values in the format of string.




The following topics can be useful to understand this program.



Related Tutorials