LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.
Lesson 6: Printing Sum of Two Numbers In Python
Using the + operator to add two numbers:x = 5
y = 10
print(x + y)
Python Code For Printing the Sum of Two Numbers
Code
x = input("Type a number: ")
y = input("Type another number: ")
sum = int(x) + int(y)
print("The sum is: ", sum)
output will be:
Type a number:
Type another number:
The sum is:
Example:
Type a number: 9
Type another number: 8
The sum is: 17.
Explanation: In this example, the user must input two numbers.
Then we print the sum by calculating (adding) the two numbers.
You can type/copy paste the above code in any online compiler or editor or you can even practice to write the code by hand.
Example: 2
Code
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))
the output will be
Enter first number:
Enter second number:
The sum of 8 and 7 is 15.0
Example
Enter first number: 8
Enter second number: 7
The sum of 8 and 7 is 15.0
Explanation
input()In this program, we asked user to enter two numbers and this program displays the
sum of tow numbers entered by user. We use the built-in function to take the input.
input() returns a string, so we convert it into number using the float() function.
We add the two numbers using the + arithmetic operator. Changing this operator, we can
subtract (-), multiply (*), divide (/), floor divide (//) or find the remainder (%) of
two numbers. Find out more about arithmetic operators and input in Python.
How to Add two numbers without using variable?
print('The sum is %.1f' %(float(input('Enter first number: '))+float(input('Enter second number: '))))
Explanation: This Python Code for adding two numbers without using variable is memory efficient.
num1 and num2 are example values you can replace with any numbers you require.
The output of above example will be as under( the two user input viz Enter first number: and Enter second number: will be taken from user and added).
Enter first number: 2
Enter second number: 3
The sum is 5.0