Python Program to Swap Two Numbers

Swapping Numbers Python Program

This python program is used to swap two numbers inside the python function but changes wont be reflected in main statements.

Python is neither "call-by-reference" nor "call-by-value". In Python a variable is not an alias for a location in memory. Rather, it is simply a binding to a Python object

#!/usr/bin/python

def swap_numbers(num1, num2):
    temp = num1;
    num1 = num2;
    num2 = temp;
    print("After swapping, number1 is %d and number2 is %d" % (num1, num2));

if __name__ == '__main__':
    num1 = int(input("Enter number1: "));
    num2 = int(input("Enter number2: "));
    print("Before swapping, number1 is %d and number2 is %d" % (num1, num2));
    swap_numbers(num1, num2);
Output:
$ python swap_numbers.py 
Enter number1: 34
Enter number2: 54
Before swapping, number1 is 34 and number2 is 54
After swapping, number1 is 54 and number2 is 34
$ python swap_numbers.py 
Enter number1: 3  
Enter number2: 5
Before swapping, number1 is 3 and number2 is 5
After swapping, number1 is 5 and number2 is 3


Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^