0% found this document useful (0 votes)
41 views

Unit 2 Notes

Python provides two modes for executing code: 1. Interactive mode (REPL) allows executing code line-by-line and is good for beginners. 2. Script mode saves code in a file with a .py extension and allows executing larger programs. Python code is made up of statements which are individual instructions that can be executed. Keywords like if, else, for are reserved and cannot be used as variable or function names.

Uploaded by

anisha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Unit 2 Notes

Python provides two modes for executing code: 1. Interactive mode (REPL) allows executing code line-by-line and is good for beginners. 2. Script mode saves code in a file with a .py extension and allows executing larger programs. Python code is made up of statements which are individual instructions that can be executed. Keywords like if, else, for are reserved and cannot be used as variable or function names.

Uploaded by

anisha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT II DATA TYPES, EXPRESSIONS, STATEMENTS

Python interpreter and interactive mode, debugging; values and types: int, float,
boolean, string, and list; variables, expressions, statements, tuple assignment, precedence of
operators, comments; Illustrative programs: exchange the values of two variables, circulate
the values of n variables, distance between two points.

Introduction
PROGRAM:

• A program is a set of instructions that tell a computer what to do.

• Programs are used to operate the components of a computer, solve problems or


satisfy a need.
Programming terms:
code or source code : The sequence of instructions in a program.
syntax : The set of legal structures and commands that can be used in a particular
programming language.
Output : The messages printed to the user by a program.

console : The text box onto which output is printed.

Python is developed by
Guido van Rossum in 1989.
Python is named after the comedy television show Monty Python’s Flying Circus. It is not
named after the Python snake.

Python programming language is Used by Top Companies


• NASA
• Google
• YouTube
• BitTorrent, etc.
Applications of Python::
• Web development
• Machine learning
• Data Analysis
• Scripting
• Game development
• Embedded applications
• Desktop applications

Python interpreter and interactive mode

We generally write a computer program using a high-level language. A high-level language


is one that is understandable by us, humans. This is called source code.
However, a computer does not understand high-level language. It only understands the
program written in 0's and 1's in binary, called the machine code.
To convert source code into machine code, we use either a compiler or an interpreter.

Compiler
• A compiler is a software program that reads the entire program and translates the whole
program into machine code at once.
• The compiler specifies the errors at the end of the compilation with line numbers when
there are any errors in the source code.

Figure:Structure of a Compiler
Interpreter :
• A Interpreter is a software program that converts just one statement of the program at a
time into machine code and executes immediately before moving on to the next line.
• It performs line-by-line execution of a program statement,
• If there is an error in the statement, it displays an error message. The interpreter moves on
to the next line for execution only after the removal of the error .

Figure:Structure of an Interpreter

Compiler Versus Interpreter:


Python interpreter and interactive mode

In the Python programming language, there are two ways in which we can run our code:
1. Interactive mode or Shell Mode 2. Script mode or Program Mode
1. Interactive mode or Shell Mode
• Interactive mode is very convenient for writing very short lines of code.
• In python it is also known as REPL which stands for Read Evaluate Print Loop.
◦ Here, the read function reads the input from the user and stores it in memory.
◦ Eval function evaluates the input to get the desired output.
◦ Print function outputs the evaluated result.
◦ The loop function executes the loop during the execution of the entire program and
terminates when our program ends.
• This mode is very suitable for beginners in programming as it helps them evaluate their
code line by line and understand the execution of code well.
How to run python code in Interactive mode?
2 ways to to run python code in Interactive mode:
a.Using Command prompt in windows
b.Using Python Shell
a.Using Command prompt in windows
In order to run our program in the interactive mode, we can use command prompt in windows:Let
us see understand the execution of python code in the command prompt with the help of an
example:
Example 1:
To run python in command prompt type “python”. Then simply type the Python statement on >>>
prompt. As we type and press enter we can see the output in the very next line.

Example 2 : Addition of two numbers


We will declare two variables a and b and store the result in a third variable c. We further print
c. All this is done in the command prompt.
Disadvantages of interactive mode:
•The interactive mode is not suitable for large programs.
•The interactive mode doesn’t save the statements. So we cannot use it in the future.
•Editing the code in interactive mode is a tedious task.
b.Using Python Shell
Open IDLE---> Python shell opens--->Type the python code and execute it.

2. Script mode or Program Mode


• In the script mode, a python program can be written in a file.
• This file can then be saved and executed using the command prompt.
• Script mode is very suitable for writing long programs.
• The extension to save a python file is “.py”.
• By default the file is stored in Python installation folder

How to run python code in script mode?


2ways to run python code in script mode:
a. Executing using command prompt terminal
b.Executing using Python IDE

a. Executing using command prompt terminal


• In order to run a code in script mode follow the following steps.
Step 1: Make a file using a text editor. You can use any text editor of your choice. (example,
notepad)
Step 2: After writing the code save the file using “.py” extension.
Step 3: Now open the command prompt and command directory to the one where your
file is stored.
Step 4: Type python “filename.py” and press enter.
Step 5: You will see the output on your command prompt.
• Example
Python Program in IDE editor:

Output in command prompt:


b.Executing using Python IDE
• Open the Python IDE --->File --->New ---->Type the program--->save with .py
extension--->run--->Execute---->output will be displayed in Python shell

Output in Python shell:

Advantages of script mode


Script mode of execution is very much suitable to write long Python programs
We can easily do the editing of our Python program inside the script mode.
program can be saved and we can use in the future.
Script mode is execution is mostly preferred by all the experts and Python
programmers.
KEYWORDS IN PYTHON:
• Keywords are the reserved words in Python.
• We cannot use a keyword as a variable name, function name or any other identifier.
• They are used defining the syntax and structure of the Python language.
• For instance, Python keyword “if” is used for condition statements, hence you cannot use
“if” as a variable in your program.
• In Python, keywords are case sensitive.
Let us consider an example using Python keyword:

• It will print whether you are eligible to


vote or not depending on your age.
• Python understands the if-else because it
is a fixed keyword and syntax then the
further processing is done.

Mention the List of Keyword available in Python:There are more than 33 keywords in
Python 3.7

Note:
• The above keywords may get altered in different versions of Python.
• Some extra might get added or some might be removed.
• You can always get the list of keywords in your current version by typing the following in
the prompt.

True, False: these are the Boolean values in python. The result of the logical operation is indicated
by any one of these values.
• and, or, not: these are logical operators in python. And the result of these operators is always a
Boolean value.
• if, elif, else: these keywords are used in the decision control structure
• while, for: these keywords are used in a loop control structure
• break, continue: these keywords are used within the loop control structure to terminate the
execution of the loop or to terminate the execution of the current iteration of the loop
• class: this keyword is used to create a user-defined class
• def: this keyword is used to create a user-defined function
• try, except, raise, finally: these keywords are used in exception handling to handle the
exception that occurred during the execution of the program
• from, import: these keywords are used to import any in-built module of python programming
to your current namespace
• global: this keyword is used within the function if you want to access the variable defined
inside the function from outside the function.
Comparing keywords with variable name
( or)Difference between Keywords and Identifiers in Python.

STATEMENTS IN PYTHON
What is a statement in Python?
• A statement is an instruction that a Python interpreter can execute.

• Python statement ends with the token NEWLINE character

• For example, a = 10 is an assignment statement.

• Where a is a variable name and 10 is its value

• There are mainly four types of statements in Python:

◦ print statements:

▪ It prints the output value.

◦ Assignment statements:

▪ Assignment statements don’t produce a result it just assigns a value to the operand
on its left side.

Example:

◦ Conditional statements

◦ Looping statements.
Multiple statements on a single line:

Multi-Line Statements
• Python statement ends with the token NEWLINE character.

• But we can extend the statement over multiple lines using line continuation character
(\). This is known as an explicit
continuation.

Implicit continuation:
We can use parentheses () to write a multi-line statement. We can add a line continuation statement
inside it. Whatever we add inside a parentheses () will treat as a single statement even it is placed
on multiple lines.
CONSTRUCTING STATEMENTS FROM VARIABLES AND EXPRESSIONS:

EXPRESSION IN PYTHON

Expression statements
• A combination of operands and operators is called an expression.

• The expression in Python produces some value or result after being interpreted by the
Python interpreter.

• An example of expression can be : x=x+10. In this expression, the first110 is added to the
variable x. After the addition is performed, the result is assigned to the 0variable x.

Example :
x = 25 # a statement
x = x + 10 # an expression
print(x)

Output :
35

Types of Expression in Python


1. Constant Expressions:

Expressions that contains only constant values is known as a constant expression.

2.

Arithmetic Expressions

An expression in Python that contains a combination of operators, operands, and sometimes


parenthesis is known as an arithmetic expression.
3. Integral Expressions

• An integral expression in Python is used for computations and type conversion .


• (integer to float, astring to integer, etc.).
• An integral expression always produces an integer value as a resultant.
Example :

x = 10 # an integer number
y = 5.0 # a floating point number
# we need to convert the floating-point number into an integer or vice versa for summation.
result = x + int(y)
print("The sum of x and y is: ", result)
Output :
The sum of x and y is: 15

4. Floating Expressions

A floating expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). A floating expression always produces a floating-point number as a
resultant.
Example :
x = 10 # an integer number
y = 5.0 # a floating point number

# we need to convert the integer number into a floating-point number or vice versa for summation.
result = float(x) + y

print("The sum of x and y is: ", result)

Output :
The sum of x and y is: 15.0
5. Relational Expressions
• A relational expression in Python can be considered as a combination of two or more
arithmetic expressions joined using relational operators. The overall expression results
in either True or False (boolean result)

A relational operator produces a boolean result so they are also known as Boolean Expressions.
For example :
10+15>20
1 this example, first, the arithmetic expressions (i.e. 110+15 and 220) are evaluated, and then the
In
results
0 are used for further comparison. 0 0

6.
+ Logical Expressions +
• A logical expression performs the logical computation,
• The overall expression results in either True or False (boolean result).
1 • We have three types of logical expressions in 1Python, let us discuss them briefly.
5 5

>

2
0
Tuple assignment

• Tuple is an ordered sequence of items same as list. The only difference is that tuples
are immutable. Tuples once created cannot be modified.

• Tuples are used to write-protect data and are usually faster than list as it cannot
change dynamically. It is defined within parentheses () where items are separated by
commas.

• Tuple Assignment is often useful to swap the values of two variables. Tuple
assignment is more elegant:

>>> a, b = b, a

• The left side is a tuple of variables; the right side is a tuple of expressions. Each
value is assigned to its respective variable. All the expressions on the right side are
evaluated before any of the assignments.

• The number of variables on the left and the number of values on the right have
to be the same:

>>> a, b = 1, 2, 3

ValueError: too many values to unpack

• The right side of tuple can be any kind of sequence (string, list or tuple). For
example, to split an email address into a user name and a domain, you could write:

>>> addr = '[email protected]'

>>> uname, domain = addr.split('@')

The return value from split is a list with two elements; the first element is assigned to
uname, the second to domain.
>>> uname

'be'

>>> domain

'gmail.com'

Example program:

Swapping of two numbers using tuple assignment.

a=5

b = 10

print(“Before Swapping”)

print(“a=”,a,”b=”,b)

# swap the values

a, b = b,a

print(“After Swapping”)

print(“a=”,a,”b=”,b)

OPERATORS IN PYTHON

The types of operators in python are

 Arithmetic operators

 Comparison (Relational) operators

 Logical (Boolean) operators

 Bitwise operators

 Assignment operators

 Special operators
Arithmetic operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc.
Operator Meaning Example
+ Add two operands or unary plus x+y
- Subtract right operand from the left or unary minus x-y
* Multiply two operands x*y
Divide left operand by the right one (always results into
/ x/y
float)
Modulus - remainder of the division of left operand by
% x % y (remainder of x/y)
the right
** Exponent - left operand raised to the power of right x**y(x to the power y)
Example:

x = 15
y=4
print(x+y)
print(x/y)
print(x%y)
print(x**y)

Output:

19

3.75

50625

Comparison operators (Relational Operators)

Comparison operators are used to compare values. It either returns True or False according
to the condition.
OUTPUT
Operator Meaning Example Assume
x=10;y=20
> Greater than - x>y False
< Less than x<y True
== Equal to x == y False
!= Not equal to x != y True
>= Greater than or equal to x >= y False
<= Less than or equal to x <= y False
Example:

x = 10

y = 12

print(x>y)

print(x<y)

print(x!=y)

Output:

False

True

True

Logical operators

Logical Operators are used to perform logical operations like and, or and not.
Example:
Operator Meaning Output
x=6
and True if both the operands are true x < 5 and x < 10 False
or True if either of the operands is true x < 10 or x < 4 True
True if operand is false
not not(x < 5 and x < 10) True
(complements the operand)
Example:

x = True
y = False
print(x and y)
print(x or y)
print(not x)
Output:

x and y is False

x or y is True

not x is False

Bitwise operators

Bitwise operators act on operands as if they were string of binary digits. They are used to
perform bit by bit operations.
Operator Meaning Example
& Bitwise AND x& y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>> 2
<< Bitwise left shift x<< 2
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Example:

x=10

y=4

print(x&y)

Output:

Assignment operators

Assignment operators are used in Python to assign values to variables.


Operator Example Equivatent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5

Example:

x=5

print(x)

Output

5
Special operators

Python language offers some special type of operators like the identity operator or the
membership operator.

Identity operators

is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does not imply
that they are identical.
Operator Meaning Example
is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True
Example:
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
Output:

False

True

Membership operators

in and not in are the membership operators in Python. They are used to test whether a value
or variable is found in a sequence (string, list, tuple, set and dictionary).
Operator Meaning Example
in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

Example:
x = 'Hello world'
y = {1:'a',2:'b'}
print('H' in x)
print('a' not in y)
Output:
True
False
2.6.1 Precedence of Operators in Python:– PEMDAS
What is Operator Precedence???
Operator Precedence in Python programming is a rule that describe which operator is
solved first in an expression. For example: * and / have same precedence and their associativity
is Left to Right, so the expression 18 / 2 * 5 is treated as (18 / 2) * 5.

When an expression contains more than one operator, the order of evaluation depends on the
order of operations or precedence of operators.

Python Operators Precedence Rule – PEMDAS:


• Operator precedence in python follows the PEMDAS rule for arithmetic
expressions.
• Firstly, parantheses will be evaluated, then exponentiation and so on.

◦ P – Parentheses

◦ E – Exponentiation

◦ M – Multiplication

◦ D – Division

◦ A – Addition

◦ S – Subtraction

NOTE:

If two operators whose precedence is equal appear in the expression, then


the associativity rule is followed.

 Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated first,

Example: 2 * (3-1) is 4, and (1+1)**(5-2) is 8.

• Example Program:
# Parentheses () has higher precedence
>>> (10 - 4) * 2
12

Parentheses can be used to make an expression easier to read.

Example: (minute * 100) / 60, even if it doesn’t change the result.

 Exponentiation(**) has the next highest precedence, so


Example : 1 + 2**3 is 9 and 2 *3**2 is 18

 Multiplication and Division have higher precedence than Addition and Subtraction.

Examples: 2*3-1 is 5

6+4/2 is 8.

◦ For example, multiplication has higher precedence than


subtraction.
◦ Example Program:
# Multiplication has higher precedence
# than subtraction

>>> 10 - 4 * 2
2

 Operators with the same precedence are evaluated from left to right (except
exponentiation).

Example: In the expression, degrees / 2 * pi, the division happens first and the result
is multiplied by pi.

Operator Precedence Table:

• The following table shows the precedence of Python operators.

• The upper operator holds higher precedence than the lower operator.
Example Program for operator precedence:

# Precedence of and & or operators

colour = "red"

quantity = 0

if colour == "red" or colour == "green" and quantity >= 5:

print("Your parcel is dispatched")

else:

print("your parcel cannot be dispatched")

Output:

Your parcel is dispatched


ASSOCIATIVITY IN OPERATOR PRECEDENCE

• When two operators have the same precedence, associativity helps to determine the order of
operations.

• Associativity is the order in which an expression is evaluated, that has multiple


operator of same precedence.

• Almost all the operators have left to right associativity except exponentiation.

Example:

(i)Left to Right Associativity

• Mulitplication and Floor Division share the same precedence.

• Hence if both the operators were present in an expression the left one will be evaluated first.

print(10*2//3)

10*2 will be evaluated first.

Program:
# Left-right associativity
# Output: 3 Output:

print(5 * 2 // 3) 3

# Shows left-right associativity 0


# Output: 0

print(5 * (2 // 3))

ii) Right to Left Associativity

• Exponent operator ** has right-to-left associativity in Python.

Program:
# Shows the right-left associativity of ** OUTPUT:
# Output: 512, Since 2**(3**2) = 2**9 512
64
print(2 ** 3 ** 2)

# If 2 needs to be exponated fisrt, need to use ()


# Output: 64

print((2 ** 3) ** 2)
COMMENTS

 Comments can be used to explain Python code.

 Comments can be used to make the code more readable.

 Comments can be used to prevent execution when testing code.

 As programs get bigger and more complicated, they are difficult to understand. So, notes
can be added to the programs in natural language for better understanding.

 These notes are called comments, and they start with the # symbol:

Creating a Comment
• Comments starts with a #, and Python Interpreter will ignore them:

Example:

#This is a comment

print("Hello, World!")

Output:

Hello,World

• Comments can be placed at the end of a line, and Python will ignore the rest
of the line:

Multi Line Comments


• Python does not really have a syntax for multi line comments.

• To add a multiline comment you could insert a # for each line:

Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")

• Since Python will ignore string literals that are not assigned to a variable, you
can add a multiline string (triple quotes) in your code, and place your
comment inside it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

• As long as the string is not assigned to a variable, Python will read the code,
but then ignore it, and you have made a multiline comment.

 Comments are most useful during the documentation of the code.

 This comment contains useful information that is not in the code:

Example: v = 5 # velocity in meters/second.

 Good variable names can reduce the need for comments, but long names can make complex
expressions hard to read.

Example Program:

# python program to add two numbers

a=int(input(“Enter a :”)) # read a

b=int(input(“Enter b:”)) # read b

c=a+b # add a and b

print(“Addition:”,c) # to print the value of addition


ILLUSTRATIVE PROGRAMS

2.11.1 Exchange the values of two variables

i) Program to swap two values without using the third variable

#Program to swap two values without using Output:


#the third variable
Enter x value:
x = int(input(“Enter x value:”))
10
y = int(input(“Enter y value:”))
Enter y value:
print(“Before Swapping”)
20
print(“x=”,x,”y=”,y)
Before Swapping
x, y = y, x
x=10 y=20
print(“After Swapping”)
After Swapping
print(“x=”,x,”y=”,y)
x=20 y=10

ii) Program to swap two values using the third variable

#Program to swap two values using the third Output:


#variable
Enter x value:
x = int(input(“Enter x value:”))
10
y = int(input(“Enter y value:”))
Enter y value:
print(“Before Swapping”)
20
print(“x=”,x,”y=”,y)
Before Swapping
temp = x
x=10 y=20
x=y
After Swapping
y = temp
x=20 y=10
print(“After Swapping”)

print(“x=”,x,”y=”,y)
2.11.2 Circulate the values of N variables

Method 1: Method 2:

a=[1,2,3] size=int(input("Enter number of elements :"))

print("Entered List:",a) a=[]

j=len(a)-1 print("Enter the elements:")

while j>0: for i in range (0, size):

temp=a[j] a.append(int(input()))

a[j]=a[j-1] print("Entered list are:",a)

a[j-1]=temp j=len(a)-1

j=j-1 while j>0:

print("Circulated List:",a) temp=a[j]

a[j]=a[j-1]

a[j-1]=temp

j=j-1

print("Circulated List:",a)

Output Output

Entered List : [1,2,3] Enter number of elements :3


Circulated List:[3,1,2] Enter the elements:

Entered list are: [1, 2, 3]

Circulated List: [3, 1, 2]


2.11.3 Distance between two points

Formula:

Distance =

i) Program using Function: ii) Program using LIST:

import math import math

def calculate_distance (x1,y1,x2,y2): p1=[4,0]

dist=math.sqrt((x2-x1)**2+(y2-y1)**2) p2=[6,6]

print (dist) distance=math.sqrt(((p1[0]-p2[0])**2)+((p1[1]-


p2[1])**2))
calculate_distance(2,4,6,8)
print (distance)

Output Output

5.65685424949 6.32455532034

SYNTAX AND STRUCTURE OF User Defined Functions


(Own Functions)
Python allows us to define our own functions.

These own functions are called as user defined functions.

The creation of user defined functions has two parts:

1. Function Definition

2. Function Use (Function Call or Function Invocation)

Function Definition

 In Python, before using the functions in the program, the function must be defined.

Syntax:

def name of function (list of formal parameters):


body of function

def is a reserved word that tells Python that a function is about to be defined.

name of function is the name which is used to refer to the function.

List of formal parameters of the function is the sequence of names within the parentheses
following the function name.

body of function refers to any piece of Python code. A special statement return can be used
only within the body of a function.

Example:

The function definition for finding maximum of two numbers is

def max(x, y):

if x > y:

return x

else:

return y

name of function - max

list of formal parameters – x,y

Function Use (Function Call Or Function Invocation)

 A function call(function invocation) is an expression that has a value which is the value
returned by the invoked function.

 When the function is used, the formal parameters are bound (as in an assignment statement)
to the actual parameters (arguments) of the function invocation (function call).

 Syntax:

functionname (actualarguments)

Example:

max(3, 4)

- binds x to 3 and y to 4.

 The execution of a return statement terminates the invocation of the function.

Example:

The value of the expression max(3,4) * max(3,2) is 12, because the first invocation of max
returns the int 4 and the second returns the int 3.
Program:

# Python Program to add 2 numbers using function

def add(x, y): # function definition

return x+y

a=int(input("Enter a:"))

b=int(input("Enter b:"))

c=add(a,b) # function call

print("Addition:",c)

PARAMETER PASSING IN USER DEFINED FUNCTIONS:

• The parameters present in function definition statement is called as Formal Parameters or


Parameters.

• The arguments present in function call statement is called as Actual arguments or


Arguments.

• Inside the function, the arguments are assigned to variables called parameters.

def print_twice(result):

print(result)

print(result)

• This function assigns the argument to a parameter named result.

• The value can also be used as argument. When the function is called, it prints
the value of the parameter twice.

Example:

>>> print_twice('Hello')

Hello

Hello

>>> print_twice(42)

42

42

• The expression can also be used as arguments. The argument is evaluated before the
function is called.
Example:

>>> print_twice('Hello'*4)

Hello Hello Hello Hello

Hello Hello Hello Hello

• Variable can also be used as an argument.

Example:

>>> m = 'Hello Python'

>>> print_twice(m)

Hello Python

Hello Python

#FUNCTION DEFINTION

def swap(x,y):

x, y = y, x

#DRIVER CODE

x = int(input(“Enter x value:”))

y = int(input(“Enter y value:”))

print(“Before Swapping”)

print(“x=”,x,”y=”,y)

swap(x,y)

print(“After Swapping”)

print(“x=”,x,”y=”,y)

OUTPUT:
Swap two variables using function in Python

Swap of two variables using function in Python can be done by passing our variables to
the user defined function as arguments and returning or printing the swapped data.

Regarding arguments and returning values , functions are 4 types


•With arguments and return value
•With arguments and without return value
•Without arguments and with return value
•Without arguments and without return value

Python code: Swap two variables using function in Python


With arguments and return value:

You might also like