Python program example to add two numbers tutorial 2025
Added 'example' and 'tutorial' to specify the type of content desired, and included the year to ensure the results are up-to-date.
To create a concise yet informative Python program for adding two numbers, we can follow a structured approach. Below, I will present a simple example program, explain its components, and provide several ways to execute this task using Python.
Here’s a straightforward program that prompts the user to enter two numbers, adds them, and displays the result.
# Program to add two numbers provided by the user
# Take input from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Calculate the sum
sum_result = num1 + num2
# Display the result
print("The sum of", num1, "and", num2, "is:", sum_result)
Input Handling:
input() function. We convert these inputs to float type to allow for decimal numbers, expanding flexibility beyond integers.Calculation:
+ operator, which is the standard operator for arithmetic addition in Python. The result is stored in the variable sum_result.Output:
print() function, providing a clear message that includes both the input numbers and the computed sum.To execute this program, you can use any Python environment (like IDLE, a terminal, or Jupyter Notebook). Simply copy the code into your Python editor and run it. You will be prompted to enter two numbers.
If you're interested in different approaches, here are a few alternative methods:
This version encapsulates the addition in a function, promoting modularity:
def add_numbers(a, b):
return a + b
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print("The sum is:", add_numbers(num1, num2))
You can also accept numbers via command-line arguments, which can be useful for automation:
import sys
if len(sys.argv) != 3:
print("Usage: python add.py <num1> <num2>")
else:
num1 = float(sys.argv[1])
num2 = float(sys.argv[2])
print("The sum is:", num1 + num2)
These examples illustrate how straightforward it is to add two numbers in Python. You can choose the method that best fits your needs, whether using user input, functions, or command-line arguments. Each technique serves different use cases, from simple scripting to more complex applications.
For further understanding, I recommend visiting resources such as W3Schools and GeeksforGeeks to explore additional tutorials and examples on Python programming.