python program to add two numbers

In this lesson, we are going, to sum up, the numbers stored inside two individual variables. We will create two separate programs. First without user input and second with user input.

To understand this, you should know the following topics in python –

  • variables
  • the print function
  • taking user input
  • conversion of user input to an integer.

Sample program one (By initializing variables manually)

x = 4
y = 7
myresult = x + y
print(myresult)

Output: –

11

Explanation

  • We have declared two variables named x and y and initialized them with values 4 and 7 respectively.
  • Then we declared a variable named myresult and we have d the sum of x and y in myresult (Of course we have added the values of the variables by the addition operator ‘+’).
  • Finally we have displayed the output by passing the variable myresult as an argument in the print function.

The print function displays anything that has passed as an argument. If we pass a string, then it would be displayed, and if we pass a variable, then the value that the variable is holding would be displayed.

Sample Program two (By taking input from the user)

x = int(input("Enter first number"))
y = int(input("Enter Second number"))
myresult = x + y
print(myresult)

Output: –

Enter first number12

Enter first number10

22

In the second example, we have taken the inputs from the user and stored them to x and y. We have taken the inputs by using the inbuilt input function.

The input function always returns a string irrespective of what the user enters. So if for example, the user enters 24, the input function would return 24 but in string form. But we need the number in integer form, so we need to convert the inputs to integer form to calculate the sum. We have done this by using the int function.

Finally, we have displayed the calculated sum using the print function.

When this program runs, it first asks the user to enter the first number. After the user enters a number it again asks for the second number. When the user press enter after giving the second number, the sum of the two numbers displays.