Program 5: Find Sum of Two Integer Numbers - 1000+ Python Programs


Question 5) Write a program in Python to calculate the sum of two integer numbers.


Code Example 1: Using two hardcoded integer values

add-two-int-example-1.py
# Program 5: Example 1
# Add to Integer Numbers
# 1000+ Python Programs by Code2care.org

int_number_1 = 10
int_number_2 = 20

sum_of_two_numbers = int_number_1 + int_number_2

print(f"Sum of {int_number_1} and {int_number_2} is {sum_of_two_numbers}")
Output:

Sum of 10 and 20 is 30

Python Program Add Two Hardcoded Integers

Explanation:

  1. Create a variable int_number_1 with an integer value hardcoded. Say 10
  2. Create a variable int_number_2 with an integer value hardcoded. Say 20
  3. Now create a third variable sum_of_two_numbers to hold the sum of two numbers
  4. Print the sum using the print function with f-strings formatting.

Code Example 2: Using user inputs

add-two-int-example-2.py
# Program 4: Example 2
# Add to Integer Numbers using input
# 1000+ Python Programs by Code2care.org

int_number_1 = int(input("Enter integer number 1: "))
int_number_2 = int(input("Enter integer number 2: "))

sum_of_two_numbers = int_number_1 + int_number_2

print(f"Sum of {int_number_1} and {int_number_2} is {sum_of_two_numbers}")
Output:

Enter integer number 1: 5
Enter integer number 2: 2
Sum of 5 and 2 is 7

Python Program Sum of Two Integers input

Explanation:

We learnt a new in-build function called int() which returns a int value for the provided string.

Read More: https://docs.python.org/3/library/functions.html#int

Functions used:
  • input()
  • print()
  • int()

If an invalid integer value is provided you will get an ValueError error,

ValueError Traceback (most recent call last)
<ipython-input-39-77271dff3a60> in <module>
      4 
      5 int_number_1 = int(input("Enter integer number 1: "))
----> 6 int_number_2 = int(input("Enter integer number 2: "))
      7 
      8 sum_of_two_numbers = int_number_1 + int_number_2

ValueError: invalid literal for int() with base 10: '11.1'

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap