Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Functions

Function to add two numbers - Python Program

Example 1 :

def add_numbers(a, b): """Return the sum of two numbers.""" return a + b # Example usage print("Sum:", add_numbers(5, 3))

Output

 
OUTPUT  :
Sum: 8

Example 2 : Advanced Program

def add_numbers(num1, num2): """ This function takes two numbers as input and returns their sum. """ sum_result = num1 + num2 return sum_result # Get input from the user number1_str = input("Enter the first number: ") number2_str = input("Enter the second number: ") # Convert input strings to numbers (float to handle decimals) try: number1 = float(number1_str) number2 = float(number2_str) except ValueError: print("Invalid input. Please enter valid numbers.") else: # Call the function and store the result result = add_numbers(number1, number2) # Display the result print(f"The sum of {number1} and {number2} is: {result}")

Output

 
OUTPUT  :
Enter the first number: 10.5
Enter the second number: 20
The sum of 10.5 and 20.0 is: 30.5

Explanation

Function Definition:

The add_numbers(num1, num2) function is defined using the def keyword. It takes two parameters, num1 and num2, which represent the numbers to be added.

Addition Operation:

Inside the function, the + operator is used to perform the addition of num1 and num2. The result is stored in the sum_result variable.

Return Value:

The return sum_result statement sends the calculated sum back to where the function was called.

User Input:

The program prompts the user to enter two numbers using the input() function. These inputs are initially strings.

Type Conversion and Error Handling:

The float() function is used to convert the input strings into floating-point numbers, allowing for decimal values. A try-except block is included to handle potential ValueError if the user enters non-numeric input.

Function Call:

The add_numbers() function is called with the converted number1 and number2 as arguments. The returned sum is stored in the result variable.

Output Display:

Finally, an f-string is used to print a clear message displaying the original numbers and their calculated sum.