Exercise
Function Swap With Mutable Parameters
Objective
Develop a Python program with a function called "swap" to exchange the values of two integer variables, which are passed by reference.
For example:
x = 5 y = 3 swap(x, y) print(f"x={x}, y={y}") (which should print "x=3, y=5")
Example Python Exercise
Show Python Code
# Define the function swap which swaps the values of two elements in a list
def swap(nums):
nums[0], nums[1] = nums[1], nums[0] # Swap the first and second elements
# Main function to test the swap function
def main():
# Create a list with two integers (5 and 3)
nums = [5, 3]
# Call the swap function to exchange the values of the two numbers
swap(nums)
# Print the swapped values
print(f"x={nums[0]}, y={nums[1]}")
# Call the main function to execute the program
main()
Output
x=3, y=5
Share this Python Exercise