Spaces:
Running
Running
| python | |
| # Function to swap two numbers | |
| def swap_numbers(a, b): | |
| """ | |
| Swaps two numbers using a temporary variable | |
| Args: | |
| a: First number | |
| b: Second number | |
| Returns: | |
| Tuple of (a, b) after swapping | |
| """ | |
| print(f"Before swap: a = {a}, b = {b}") | |
| # Swapping logic | |
| temp = a | |
| a = b | |
| b = temp | |
| print(f"After swap: a = {a}, b = {b}") | |
| return a, b | |
| # Alternative method without temporary variable (using arithmetic) | |
| def swap_without_temp(a, b): | |
| """ | |
| Swaps two numbers without using temporary variable | |
| Args: | |
| a: First number | |
| b: Second number | |
| Returns: | |
| Tuple of (a, b) after swapping | |
| """ | |
| print(f"Before swap: a = {a}, b = {b}") | |
| a = a + b | |
| b = a - b | |
| a = a - b | |
| print(f"After swap: a = {a}, b = {b}") | |
| return a, b | |
| # Example usage | |
| if __name__ == "__main__": | |
| num1 = 5 | |
| num2 = 10 | |
| # Using temporary variable | |
| swapped1, swapped2 = swap_numbers(num1, num2) | |
| print("\nAlternative method:") | |
| # Using arithmetic operations | |
| swapped1, swapped2 = swap_without_temp(num1, num2) | |
| </html> |