Introduction
Adding two numbers is a basic operation in programming. This example will guide you through creating a Python program that takes two numbers as input from the user and calculates their sum.
Problem Statement
Create a Python program that:
- Prompts the user to enter two numbers.
- Adds the two numbers together.
- Displays the result.
Example:
- Input:
3
and5
- Output:
The sum of 3 and 5 is 8
Solution Steps
- Take Input from the User: Use the
input()
function to get two numbers from the user. - Convert Input to Numeric Values: Convert the input strings to integers or floats using
int()
orfloat()
. - Add the Numbers: Add the two numbers.
- Display the Result: Use the
print()
function to display the sum.
Python Program
# Python Program to Add Two Numbers
# Author: https://www.javaguides.net/
# Step 1: Take input from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Step 2: Add the two numbers
sum = num1 + num2
# Step 3: Display the result
print(f"The sum of {num1} and {num2} is {sum}")
Explanation
Step 1: Take Input from the User
- The
input()
function prompts the user to enter a number. Sinceinput()
returns a string, we convert it to a float usingfloat()
to handle decimal numbers.
Step 2: Add the Two Numbers
- The program adds the two numeric values using the
+
operator.
Step 3: Display the Result
- The
print()
function is used to display the result. Thef-string
format is used to include the variables directly within the string.
Steps to Run the Python Program
-
Install Python: Make sure Python is installed on your system. You can download it from the official Python website.
-
Create a Python File: Open a text editor (like Notepad, VSCode, or PyCharm), and create a new file. Save the file with a
.py
extension, such asadd_two_numbers.py
. -
Write the Code: Copy the Python code provided above and paste it into the file you created.
-
Run the Program:
- Using Command Line/Terminal:
- Open the command line or terminal.
- Navigate to the directory where you saved the
add_two_numbers.py
file. - Run the program by typing
python add_two_numbers.py
(orpython3 add_two_numbers.py
if you are using Python 3) and pressing Enter.
- Using an IDE:
- Open the file in your Python IDE (like PyCharm or VSCode).
- Run the program directly from the IDE by clicking the ‘Run’ button or pressing the appropriate shortcut (usually F5 or Ctrl+F5).
Output Example
Example:
Enter the first number: 3
Enter the second number: 5
The sum of 3 and 5 is 8
Example:
Enter the first number: 10.5
Enter the second number: 2.3
The sum of 10.5 and 2.3 is 12.8
Conclusion
This Python program demonstrates how to take input from the user, perform arithmetic operations, and display the result. It is an excellent exercise for beginners to understand basic input, output, and arithmetic operations in Python.