Toggle

In this tutorial, we will learn simple Python program coding. We will write code for adding two numbers using Python IDLE.

Python program to add two numbers by defining variables to hold the values.

``````#Define two variables

x = 75

y = 25

result = x + y

print('Sum of the two numbers =',result)``````

Program Output

The variable ‘x’ has a value of 75, ‘y’ has a value of 25, and ‘result’ equals the sum of ‘x’ and ‘y’. The program outputs the value of the result variable.

The main disadvantage of the program is that the values are hard-coded in the program. We need to change the code every time by changing the variable’s values.

In the next section, we will improve the program by asking the user to input the values.

Take User Input

Now, let’s look at the improved version of the program. We can notice that the values of the variables are hardcoded in the program. In the next program, we will read the numbers from the user using the input() function.

``````# Program to read two numbers and compute the sum
# Python Tutorials - www.TestingDocs.com

#input numbers from the user.
num1 = int(input("Enter the first number: = "))

num2 = int(input("Enter the second number: = "))

# Compute the sum
result = num1 + num2

print("Addition of the given two numbers = ", result)```

```

Program Output

Let’s run the Python program and view the sample program output.

Enter the first number: = 120
Enter the second number: = 56
Addition of the given two numbers = 176

The int() function is used to convert the strings into integers. The input() function returns the input as strings.

Python Tutorials

Python Tutorial on this website can be found at:

https://www.testingdocs.com/python-tutorials/