Write a program to Add Two Variables in Python
Python 3 Code:
1 2 3 4 5 6 7 8 9 |
# This program adds two numbers num1 = 5.5 num2 = 1.15 # Add two numbers sum = float(num1) + float(num2) # Display the sum print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) |
Output:
The code you provided is a simple Python program that adds two numbers, num1
and num2
, and outputs the result.
The program starts by defining two variables, num1
and num2
, and assigns them the values of 5.5 and 1.15 respectively. These variables are floats, which are numbers with decimal places.
Then, the program uses the +
operator to add num1
and num2
together and assigns the result to the variable sum
.
Next, the print()
function is used to output the sum of the two numbers to the console. The format()
method is used to insert the values of num1
, num2
and sum
into the string that is passed to the print()
function. The curly braces {}
acts as placeholders for the variables that are to be inserted. The numbers within the braces correspond to the index of the variable passed to the format()
method.
The final output will be “The sum of 5.5 and 1.15 is 6.65”.
Take your time to comment on this article.