Write a program that has a user defined function to accept 2 numbers as parameters, if number 1 is less than number 2 then numbers are swapped and returned, i.e., number 2 is returned in place of number1 and number 1 is reformed in place of number 2, otherwise the same order is returned.
python
Program to swap two numbers using user defined function
def swapNumbers(num1, num2): """Function to accept two numbers as parameters. If num1 < num2, numbers are swapped and returned. Otherwise, same order is returned.""" if num1 < num2: # Swap the numbers num1, num2 = num2, num1 return num1, num2
Main program
Accepting two numbers from user
number1 = int(input("Enter first number: ")) number2 = int(input("Enter second number: "))
Calling the user defined function
result1, result2 = swapNumbers(number1, number2)
Displaying the result
print("After function call:") print("First number:", result1) print("Second number:", result2)
Output Example:
Enter first number: 3 Enter second number: 7 After function call: First number: 7 Second number: 3
Explanation
This program demonstrates the use of user defined functions with parameters and return values. The function swapNumbers() accepts two numbers as parameters and uses a conditional statement to check if the first number is less than the second. If true, the numbers are swapped using tuple unpacking (num1, num2 = num2, num1), and both values are returned. Otherwise, the numbers are returned in the same order. The main program accepts input from the user, calls the function, and displays the returned values.
Solution Steps
Step 1: Define a user defined function swapNumbers() that accepts two parameters num1 and num2.
Step 2: Inside the function, check if num1 < num2 using an if statement.
Step 3: If condition is true, swap the numbers using tuple unpacking and return both values.
Step 4: If condition is false, return the numbers in the same order.
Step 5: In the main program, accept two numbers from the user and call the function.
Step 6: Store the returned values and display the result.