Thursday, 19 December 2024

Day 46: Python Program to Swap Two Numbers Without Using The Third Variable

 

def swap_numbers(a, b):

    a = a + b

    b = a - b

    a = a - b

    return a, b

a = int(input("Enter the first number: "))

b = int(input("Enter the second number: "))

a, b = swap_numbers(a, b)

print(f"After swapping: First number = {a} and Second number = {b}")

#source code --> clcoding.com 

Code Explanation:

Function: swap_numbers
def swap_numbers(a, b):
    a = a + b
    b = a - b
    a = a - b
    return a, b
Purpose: This function swaps the values of a and b using arithmetic operations.
Process:
a = a + b: The sum of a and b is stored in a.
b = a - b: The new value of b becomes the original value of a.
a = a - b: The new value of a becomes the original value of b.

Return Value: The function returns the swapped values of a and b.

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
Input:
Prompts the user to enter two integers (a and b).
Converts the inputs into integers using int().
a, b = swap_numbers(a, b)

Function Call: Passes the user-provided values of a and b to the swap_numbers function.
Result: After the function executes, the values of a and b are swapped.

print(f"After swapping: First number = {a} and Second number = {b}")

Output: 
Prints the swapped values of a and b.

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (49) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (929) Python Coding Challenge (351) Python Quiz (21) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses