Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    Python Program to Swap Two Variables Using a Temporary Variable

    Python Programming Examples


    This Python program interchanges the values of two variables using a temporary variable and prints them on the screen. In this example, the values are predefined, but you can take the value from the user and swap it.

    Program:

    #Variable definition and assignment
    n1 = 15
    n2 = 30
    
    #Remove comments from the bottom lines to take input from the user
    #n1 = input('Enter value of x: ')
    #n2 = input('Enter value of y: ')
    
    #Declaring a temporary variable and swapping values
    temp = n1
    n1 = n2
    n2 = temp
    
    #Print the output
    print('The value of n1 after swapping: {}'.format(n1))
    print('The value of n2 after swapping: {}'.format(n2))

    Program Output:

    The value of n1 after swapping: 30
    The value of n2 after swapping: 15


    Found This Page Useful? Share It!
    Get the Latest Tutorials and Updates
    Join us on Telegram

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.