Skip to content

WebDevHubs

  • Home
  • HTML
  • CSS
  • JavaScript
  • Web Technologies
  • Web Templates
  • Toggle search form

Python Program to Add Two Numbers

Posted on January 18, 2025January 18, 2025 By Admin No Comments on Python Program to Add Two Numbers

Adding two numbers is one of the most fundamental tasks in programming. In Python, this can be achieved in various ways, from the simplest approach to more advanced methods that cater to different scenarios.

1. Basic Example

It is a basic example to add two numbers in Python.

a = 10
b = 20
sum = a + b
print(sum)

2. Using Simple Input and Output

The most basic way to add two numbers in Python is by taking input from the user and then printing the result.

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
sum = a + b
print("The sum is: ", sum)

3. Using Functions

Encapsulating the addition logic within a function improves code organization and reusability.

def add_numbers(a, b):
    return a + b

num1 = 10
num2 = 20
sum = add_numbers(num1, num2)
print("Sum: ", sum)

4. Using Classes

For a more structured approach, especially in larger applications, using classes can be beneficial.

class Calculator:
    def add(self, a, b):
        return a + b

calc = Calculator()
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The sum is", calc.add(num1, num2))

Object-oriented programming (OOP) principles can be applied here to create a reusable Calculator class.

5. Using NumPy Library

For scientific computations, Python’s NumPy library can handle basic arithmetic operations efficiently.

import numpy as np

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
sum = np.add(num1, num2)
print("The sum is", sum)

NumPy is powerful for numerical calculations and this shows its use for simple arithmetic as well.

Python Tags:Python-Program

Post navigation

Previous Post: Python First Program – Print Hello World
Next Post: Introduction to HTML

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Archives

  • June 2025
  • May 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024

Categories

  • CSS
  • HTML
  • JavaScript
  • Lodash
  • PHP
  • Python
  • Web Technologies
  • Web Templates

Recent Posts

  • JavaScript Array isArray() Method
  • JavaScript Array forEach() Method
  • JavaScript Array includes() Method
  • JavaScript Array keys() Method
  • JavaScript Array lastIndexOf() Method

Recent Comments

No comments to show.

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme