Python program to add two numbers

Python program to add two numbers

Creating a Python program to add two numbers is quite straightforward. In this tutorial, I'll walk you through the steps.

1. Basic Program to Add Two Numbers:

Let's start with a simple program where the user inputs two numbers, and the program adds them:

# Get input from user num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) # Add the two numbers sum_ = num1 + num2 # Print the result print(f"The sum of {num1} and {num2} is {sum_}") 

When you run this program, it'll prompt you to enter two numbers. After you provide the inputs, it will display their sum.

2. Using a Function:

To make the program more modular and reusable, you can define a function for the addition:

def add_two_numbers(a, b): return a + b # Get input from user num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) # Use the function to add the numbers sum_ = add_two_numbers(num1, num2) # Print the result print(f"The sum of {num1} and {num2} is {sum_}") 

3. Handling Exceptions:

You might want to ensure that the user input is indeed a number. This can be done using a try-except block:

def add_two_numbers(a, b): return a + b # Use a loop to keep prompting the user until valid input is received while True: try: # Get input from user num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) break except ValueError: print("Please enter a valid number!") # Use the function to add the numbers sum_ = add_two_numbers(num1, num2) # Print the result print(f"The sum of {num1} and {num2} is {sum_}") 

With this version, if the user enters something that's not a number, the program will kindly ask them to enter a valid number and will not crash.

That's it! This is a simple Python tutorial to add two numbers. As you delve deeper into Python, you'll find that there are numerous ways to enhance even such a basic program.


More Tags

row-height photo floating-point-precision javafx qprinter angular2-formbuilder mach syntax-highlighting pygtk intellij-lombok-plugin

More Programming Guides

Other Guides

More Programming Examples