write a python code to swap two numbers
- User
write a python code to swap two numbers
Assistant
Python Code to Swap Two Numbers
Here are three different ways to swap two numbers in Python:
Method 1: Using a Temporary Variable
# Swapping two numbers using a temporary variable a = 5 b = 10 print(f"Before swapping: a = {a}, b = {b}") # Swapping temp = a a = b b = temp print(f"After swapping: a = {a}, b = {b}")Method 2: Without Using a Temporary Variable (Arithmetic Method)
# Swapping two numbers without temporary variable a = 5 b = 10 print(f"Before swapping: a = {a}, b = {b}") # Swapping a = a + b b = a - b a = a - b print(f"After swapping: a = {a}, b = {b}")Method 3: Pythonic Way (Tuple Unpacking)
# Swapping two numbers using tuple unpacking a = 5 b = 10 print(f"Before swapping: a = {a}, b = {b}") # Swapping a, b = b, a print(f"After swapping: a = {a}, b = {b}")The third method is the most Pythonic and recommended way as it's concise and efficient. Python internally handles the swapping operation in this case.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.