Python Program: Swap Two Numbers in Python

Python Program: Swap Two Numbers in Python

  • Post category:Python
  • Post last modified:July 13, 2023
  • Reading time:5 mins read

Here you will get Python program to swap two numbers with and without using the function in Python

Swap Two Numbers in Python without Function

a=10
b=20
print("before swapping\na=", a, " b=", b)

temp = a
a = b
b = temp
print("\nafter swapping\na=", a, " b=", b)

Output :
before swapping a= 10 b= 20

after swapping a= 20 b= 10

Swap Two Numbers in Python using Function

def swap_numbers(num1, num2):
    temp = num1
    num1 = num2
    num2 = temp
    return num1, num2

# Prompt the user to enter the first number
num1 = int(input("Enter the first number: "))

# Prompt the user to enter the second number
num2 = int(input("Enter the second number: "))

# Call the function to swap the numbers
num1, num2 = swap_numbers(num1, num2)

# Print the swapped values
print("After swapping:")
print("First number:", num1)
print("Second number:", num2)

Output :

After swapping:

First number: 5

Second number: 3

In this code, we define a function called swap_numbers that takes two arguments, num1 and num2. The function swaps the values of the two numbers using a temporary variable temp and returns the swapped values.

After prompting the user to enter the two numbers, we call the swap_numbers function with the input values. The function returns the swapped values, which we then assign to num1 and num2. Finally, we print the swapped values on the console.


More Imp Topics

How Looker Writes SQL?

How to calculate percent of total in looker?

Table Calculations in Looker

What are Derived tables in Looker?

How to set conditional formatting in LOOKER?

Looker Interview Questions And Answers

New Looker Performance Recommendations Dashboard

Looker Git Version Control: How To Revert To A Specific Commit In Looker, No Git Commands Necessary

_______________________________________________________________________________________

Reference :

About Me:-
I am Om Prakash Singh – Data Analytics Consultant , Looker Consultant , Solution Architect .
I am Highly analytical and process-oriented Data Analyst with in-depth knowledge of database types; research methodologies; and big data capture, manipulation and visualization. Furnish insights, analytics and business intelligence used to advance opportunity identification.

You’ve got data and lots of it. If you’re like most enterprises, you’re struggling to transform massive information into actionable insights for better decision-making and increased business results.
Reach out to us if you are interested to evaluate if Looker is right for you or any other BI solution.

DataScience Roadmap

Leave a Reply