Python
Python
Introduction to Python and installation, data types: Int, float, Boolean, string, and list;
variables, expressions, statements, precedence of operators, comments; modules, functions--
- function and its use, flow of execution, parameters and arguments.
Python is a widely used general-purpose, high level programming language. It was initially
designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It
was mainly developed for emphasis on code readability, and its syntax allows programmers
to express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more
efficiently.
There are two major Python versions- Python 2 and Python 3.
On 16 October 2000, Python 2.0 was released with many new features.
On 3rd December 2008, Python 3.0 was released with more testing and includes new
features.
# Script Begins
Statement1
1
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Statement2
Statement3
# Script Ends
The following are the primary factors to use python in day-to-day life:
1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and
multiple inheritance.
2. Indentation
Indentation is one of the greatest feature in python
2
PYTHON PROGRAMMING III YEAR/II SEM MRCET
3. free (open source)
Downloading python and installing python is free and easy
4. Powerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities (e.g. Numeric, NumPy, sciPy)
Automatic memory management
5. Portable
Python runs virtually every major platform used today
As long as you have a compaitable python interpreter installed, python
programs will run in exactly the same manner, irrespective of platform.
6. easy to use and learn
No intermediate compile
Python Programs are compiled automatically to an intermediate form called
byte code, which the interpreter then reads.
This gives python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages.
Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language
Python is processed at runtime by python Interpreter
8. Interactive Programming Language
Users can interact with the python interpreter directly for writing the programs
9. Straight forward syntax
The formation of python syntax is simple and straight forward which also makes it
popular.
Installation:
There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software
from [Link]
Steps to be followed and remembered:
Step 1: Select Version of Python to Install.
Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.
3
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional)
traditional runtime execution model: Source code you type is translated to byte
code, which is then run by the Python Virtual Machine (PVM). Your code is automatically
compiled, but then it is interpreted.
PVM
[Link] [Link]
4
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Without passing python script file to the interpreter, directly execute code to Python prompt.
Once inside the python interpreter, then you can start.
hello world
>>> x=[0,1,2]
>>> x
#If a quantity is stored in memory, typing its name will display it.
[0, 1, 2]
>>> 2+3
The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python
interpreter uses to indicate that it is ready. If the programmer types 2+6, the interpreter
replies 8.
5
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Alternatively, programmers can store Python script source code in a file with
the .py extension, and use the interpreter to execute the contents of the file. To execute the
script by the interpreter, you have to tell the interpreter the name of the file. For example, if
you have a script name [Link] and you're working on Unix, to run the script you have to
type:
python [Link]
Working with the interactive mode is better when Python programmers deal with small
pieces of code as you can type and execute them immediately, but when the code is more
than 2-4 lines, using the script for coding can help to modify and use the code in future.
Example:
Data types:
The data stored in memory can be of many types. For example, a student roll number is
stored as a numeric value and his or her address is stored as alphanumeric characters. Python
has various standard data types that are used to define the operations possible on them and
the storage method for each of them.
Int:
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.
>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
6
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
20
>>> 0b10
2
>>> a=10
>>> print(a)
10
# To verify the type of any object in Python, use the type() function:
>>> type(10)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>
Float:
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8
>>> y
2.8
>>> y=2.8
>>> print(type(y))
<class 'float'>
>>> type(.4)
<class 'float'>
>>> 2.
7
PYTHON PROGRAMMING III YEAR/II SEM MRCET
2.0
Example:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
String:
Strings can be output to screen using the print function. For example: print("hello").
mrcet college
<class 'str'>
8
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> print('mrcet college')
mrcet college
''
If you want to include either type of quote character within the string, the simplest way is to
delimit the string with the other type. If a string is to contain a single quote, delimit it with
double quotes and vice versa:
Specifying a backslash (\) in front of the quote character in a string it and causes
Python to suppress its usual special meaning. It is then interpreted simply as a literal single
quote character:
The following is a table of escape sequences which cause Python to suppress the usual
special interpretation of a character in a string:
>>> print('a\
....b')
a....b
>>> print('a\
b\
c')
9
PYTHON PROGRAMMING III YEAR/II SEM MRCET
abc
>>> print('a \n b')
a
b
>>> print("mrcet \n college")
mrcet
college
In Python (and almost all other common computer languages), a tab character can be
specified by the escape sequence \t:
>>> print("a\tb")
a b
List:
Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
10
PYTHON PROGRAMMING III YEAR/II SEM MRCET
----------------------
>>> x=list()
>>> x
[]
--------------------------
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
Variables:
Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals or characters in these variables.
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable.
11
PYTHON PROGRAMMING III YEAR/II SEM MRCET
For example
c = "John" # A string
print (a)
print (b)
print (c)
100
1000.0
John
Multiple Assignment:
For example :
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.
For example
a,b,c =
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.
Output Variables:
Variables do not need to be declared with any particular type and can even change type after
they have been set.
12
PYTHON PROGRAMMING III YEAR/II SEM MRCET
x=5 # x is of type int
x = "mrcet " # x is now of type str
print(x)
Output: mrcet
Example
x = "awesome"
print("Python is " + x)
Output
Python is awesome
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z=x+y
print(z)
Output:
Python is awesome
Expressions:
Examples: Y=x + 17
>>> x=10
>>> z=x+20
>>> z
30
13
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x=10
>>> y=20
>>> c=x+y
>>> c
30
>>> y=20
>>> y
20
Python also defines expressions only contain identifiers, literals, and operators. So,
Identifiers: Any name that is used to define a class, function, variable module, or object is
an identifier.
Literals: These are language-independent terms in Python and should exist independently in
any programming language. In Python, there are the string literals, byte literals, integer
literals, floating point literals, and imaginary literals.
Operators: In Python you can implement the following operations using the corresponding
tokens.
14
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Operator Token
add +
subtract -
multiply *
Integer Division /
remainder %
and &
or \
Check equality ==
15
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Some of the python expressions are:
Generator expression:
>>> print(x)
<generator object <genexpr> at 0x033EEC30>
You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr>
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a
generator. The only thing that you need to know now about a generator now is that you
can iterate over it, but ONLY ONCE.
Conditional expression:
>>> x
'1'
Statements:
A statement is an instruction that the Python interpreter can execute. We have normally two
basic statements, the assignment statement and the print statement. Some other kinds of
statements that are if statements, while statements, and for statements generally called as
control flows.
Examples:
>>> x=10
16
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> college="mrcet"
An print statement is something which is an input from the user, to be printed / displayed on
to the screen (or ) monitor.
mrcet college
Precedence of Operators:
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first multiplies 3*2 and then adds into 7.
Example 1:
>>> 3+4*2
11
>>> (10+10)*2
40
Example 2:
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print("Value of ((a + b) * c) / d is ", e)
e = a + (b * c) / d; # 20 + (150/5)
print("Value of a + (b * c) / d is ", e)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
Comments:
Single-line comments begins with a hash(#) symbol and is useful in mentioning that the
whole line should be considered as a comment until the end of line.
A Multi line comment is useful when we need to comment on many lines. In python, triple
double and single used for multi-line commenting.
Example:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
30
18
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Modules:
Modules: Python module can be defined as a python program file which contains a python
code including python functions, class, or variables. In other words, we can say that our
python code file saved with the extension (.py) is treated as the module. We may have a
runnable code inside the python module. A module in Python provides us the flexibility to
organize the code in a logical way. To use the functionality of one module into another, we
must have to import the specific module.
Syntax:
import <module-name>
Every module has its own functions, those can be accessed with . (dot)
Enter the name of any module, keyword, or topic to get help on writing Python programs
and using Python modules. To quit this help utility and return to the interpreter, just type
"quit".
>>> print([Link](2020))
True
>>> print([Link](2017))
False
19
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Functions:
Functions and its use: Function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable. It avoids repetition and
makes code reusable.
integer = -20
Output:
def add_numbers(x,y):
sum = x + y
return sum
Output:
The sum is 25
Flow of Execution:
1. The order in which statements are executed is called the flow of execution
2. Execution always begins at the first statement of the program.
3. Statements are executed one at a time, in order, from top to bottom.
4. Function definitions do not alter the flow of execution of the program, but remember
that statements inside the function are not executed until the function is called.
5. Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the
statements there, and then comes back to pick up where it left off.
20
PYTHON PROGRAMMING III YEAR/II SEM MRCET
------------------------------------------
21
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
hi
hello
Good morning
mrcet
done!
The flow/order of execution is: 2,5,6,7,2,3,4,7,8
Parameters are passed during the definition of function while Arguments are passed during
the function call.
Example:
#here a and b are parameters
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
25
There are three types of Python function arguments using which we can call a function.
1. Default Arguments
2. Keyword Arguments
3. Variable-length Arguments
Syntax:
def functionname():
22
PYTHON PROGRAMMING III YEAR/II SEM MRCET
statements
.
.
.
functionname()
Example:
def hf():
hello world
hf()
In the above example we are just trying to execute the program by calling the function. So it
will not display any error and no output on to the screen but gets executed.
def hf():
print("hello world")
hf()
Output:
hello world
-------------------------------
23
PYTHON PROGRAMMING III YEAR/II SEM MRCET
def hf():
print("hw")
hf()
hf()
hf()
Output:
hw
gh kfjg 66666
hw
gh kfjg 66666
hw
gh kfjg 66666
---------------------------------
def add(x,y):
c=x+y
print(c)
add(5,4)
Output:
def add(x,y):
c=x+y
return c
print(add(5,4))
Output:
-----------------------------------
24
PYTHON PROGRAMMING III YEAR/II SEM MRCET
def add_sub(x,y):
c=x+y
d=x-y
return c,d
print(add_sub(10,5))
Output:
(15, 5)
The return statement is used to exit a function and go back to the place from where it was
called. This statement can contain expression which gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.
def hf():
return "hw"
print(hf())
Output:
hw
----------------------------
def hf():
return "hw"
hf()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
>>>
25
PYTHON PROGRAMMING III YEAR/II SEM MRCET
-------------------------------------
def hello_f():
return "hellocollege"
print(hello_f().upper())
Output:
HELLOCOLLEGE
# Passing Arguments
def hello(wish):
return '{}'.format(wish)
print(hello("mrcet"))
Output:
mrcet
------------------------------------------------
Here, the function wish() has two parameters. Since, we have called this function with two
arguments, it runs smoothly and we do not get any error. If we call it with different number
of arguments, the interpreter will give errors.
def wish(name,msg):
wish("MRCET","Good morning!")
Output:
26
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Below is a call to this function with one and no arguments along with their respective error
messages.
----------------------------------------------
def hello(wish,hello):
return '{},{}'.format(wish,hello)
print(hello("mrcet","college"))
Output:
himrcet,college
#Keyword Arguments
When we call a function with some values, these values get assigned to the arguments
according to their position.
Python allows functions to be called using keyword arguments. When we call functions in
this way, the order (position) of the arguments can be changed.
(Or)
If you have some functions with many parameters and you want to specify only some
of them, then you can give values for such parameters by naming them - this is
called keyword arguments - we use the name (keyword) instead of the position
(which we have been using all along) to specify the arguments to the function.
There are two advantages - one, using the function is easier since we do not need to
worry about the order of the arguments. Two, we can give values to only those
parameters which we want, provided that the other parameters have default argument
values.
func(3, 7)
func(25, c=24)
func(c=50, a=100)
Output:
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
Note:
The function named func has one parameter without default argument values,
followed by two parameters with default argument values.
In the first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the
value 5 and c gets the default value of 10.
In the second usage func(25, c=24), the variable a gets the value of 25 due to the
position of the argument. Then, the parameter c gets the value of 24 due to naming i.e.
keyword arguments. The variable b gets the default value of 5.
def func(b=5, c=10,a): # shows error : non-default argument follows default argument
-------------------------------------------------------
#Default Arguments
We can provide a default value to an argument by using the assignment operator (=)
def hello(wish,name='you'):
return '{},{}'.format(wish,name)
print(hello("good morning"))
Output:
good morning,you
---------------------------------------------
def hello(wish,name='you'):
return '{},{}'.format(wish,name)
Output:
Note: Any number of arguments in a function can have a default value. But once we have a
default argument, all the arguments to its right must also have default values.
This means to say, non-default arguments cannot follow default arguments. For example, if
we had defined the function header above as:
------------------------------------------
print (a+b)
Output:
Variable-length arguments
Sometimes you may need more arguments to process function then you mentioned in the
For this an asterisk (*) is placed before a parameter in function definition which can hold
non-keyworded variable-length arguments and a double asterisk (**) is placed before a
parameter in function which can hold keyworded variable-length arguments.
If we use one asterisk (*) like *var, then all the positional arguments from that point till the
end are collected as a tuple asterisks (**) before a variable like
**var, then all the positional arguments from that point till the end are collected as
a dictionary
def wish(*names):
"""This function greets all
the person in the names tuple."""
wish("MRCET","CSE","SIR","MADAM")
30
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Output:
Hello MRCET
Hello CSE
Hello SIR
Hello MADAM
#Program to find area of a circle using function use single return value function with
argument.
pi=3.14
def areaOfCircle(r):
return pi*r*r
r=int(input("Enter radius of circle"))
print(areaOfCircle(r))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Enter radius of circle 3
28.259999999999998
#Program to write sum different product and using arguments with return value
function.
def calculete(a,b):
total=a+b
diff=a-b
prod=a*b
div=a/b
mod=a%b
31
PYTHON PROGRAMMING III YEAR/II SEM MRCET
return total,diff,prod,div,mod
a=int(input("Enter a value"))
b=int(input("Enter b value"))
#function call
s,d,p,q,m = calculete(a,b)
#print("diff= ",d)
#print("mul= ",p)
#print("div= ",q)
#print("mod= ",m)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Enter a value 5
Enter b value 6
Sum= 11 diff= -1 mul= 30 div= 0.8333333333333334 mod= 5
def biggest(a,b):
if a>b :
return a
else :
return b
a=int(input("Enter a value"))
b=int(input("Enter b value"))
#function call
big= biggest(a,b)
print("big number= ",big)
Output:
32
PYTHON PROGRAMMING III YEAR/II SEM MRCET
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Enter a value 5
Enter b value-2
big number= 5
def biggest(a,b,c):
if a>b :
if a>c :
return a
else :
return c
else :
if b>c :
return b
else :
return c
a=int(input("Enter a value"))
b=int(input("Enter b value"))
c=int(input("Enter c value"))
#function call
big= biggest(a,b,c)
print("big number= ",big)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Enter a value 5
Enter b value -6
Enter c value 7
big number= 7
#Writer a program to read one subject mark and print pass or fail use single return
values function with argument.
def result(a):
if a>40:
return "pass"
33
PYTHON PROGRAMMING III YEAR/II SEM MRCET
else:
return "fail"
a=int(input("Enter one subject marks"))
print(result(a))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Enter one subject marks 35
fail
#Write a program to display mrecet cse dept 10 times on the screen. (while loop)
def usingFunctions():
count =0
while count<10:
print("mrcet cse dept",count)
count=count+1
usingFunctions()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
mrcet cse dept 0
mrcet cse dept 1
mrcet cse dept 2
mrcet cse dept 3
mrcet cse dept 4
mrcet cse dept 5
mrcet cse dept 6
mrcet cse dept 7
mrcet cse dept 8
mrcet cse dept 9
34
PYTHON PROGRAMMING III YEAR/II SEM MRCET
UNIT II
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif-else); Iteration: while, for, break, continue.
>>> 5 == 5
True
>>> 5 == 6
False
True and False are special values that belong to the type bool; they are not strings:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
The == operator is one of the relational operators; the others are: x != y # x is not equal to y
Note:
All expressions involving relational and logical operators will evaluate to either true or false
35
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Conditional (if):
The if statement contains a logical expression using which data is compared and a decision
is made based on the result of the comparison.
Syntax:
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If boolean expression evaluates to FALSE, then the first set of
code after the end of the if statement(s) is executed.
if Statement Flowchart:
a=3
if a > 2:
print(a, "is greater")
print("done")
a = -1
if a < 0:
print(a, "a is smaller")
print("Finish")
Output:
36
PYTHON PROGRAMMING III YEAR/II SEM MRCET
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
3 is greater
done
-1 a is smaller
Finish
--------------------------------
a=10
if a>9:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
A is Greater than 9
Alternative if (If-Else):
An else statement can be combined with an if statement. An else statement contains the
block of code (false block) that executes if the conditional expression in the if statement
resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else
Statement following if.
Syntax of if - else :
if test expression:
Body of if stmts
else:
Body of else stmts
If - else Flowchart :
37
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Example of if - else:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
enter the number 2
a is smaller than the input given
----------------------------------------
a=10
b=20
if a>b:
print("A is Greater than B")
else:
print("B is Greater than A")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
B is Greater than A
38
PYTHON PROGRAMMING III YEAR/II SEM MRCET
The elif statement allows us to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE. Similar to the else,
the elif statement is optional. However, unlike else, for which there can be at most one
statement, there can be an arbitrary number of elif statements following an if.
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
enter the number5
enter the number2
enter the number9
a is greater
>>>
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
enter the number2
enter the number5
enter the number9
c is greater
-----------------------------
var = 100
if var == 200:
print("1 - Got a true expression value")
print(var)
elif var == 150:
print("2 - Got a true expression value")
print(var)
elif var == 100:
print("3 - Got a true expression value")
print(var)
else:
print("4 - Got a false expression value")
print(var)
print("Good bye!")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
100
Good bye!
40
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Iteration:
A loop statement allows us to execute a statement or group of statements multiple times as
long as the condition is true. Repeated execution of a set of statements with the help of loops
is called iteration.
Loops statements are used when we need to run same code again and again, each time with a
different value.
Statements:
In Python Iteration (Loops) statements are of three types:
1. While Loop
2. For Loop
3. Nested For Loops
While loop:
Loops are either infinite or conditional. Python while loop keeps reiterating a block of
code defined inside it until the desired condition is met.
The while loop contains a boolean expression and the code inside the loop is
repeatedly executed as long as the boolean expression is true.
The statements that are executed inside while can be a single line of code or a block of
multiple statements.
Syntax:
while(expression):
Statement(s)
Flowchart:
41
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Example Programs:
1. --------------------------------------
i=1
while i<=6:
print("Mrcet college")
i=i+1
output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Mrcet college
Mrcet college
Mrcet college
Mrcet college
Mrcet college
Mrcet college
2. -----------------------------------------------------
i=1
while i<=3:
print("MRCET",end=" ")
j=1
while j<=1:
print("CSE DEPT",end="")
j=j+1
i=i+1
print()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
3. --------------------------------------------------
i=1
42
PYTHON PROGRAMMING III YEAR/II SEM MRCET
j=1
while i<=3:
print("MRCET",end=" ")
while j<=1:
print("CSE DEPT",end="")
j=j+1
i=i+1
print()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
4. ----------------------------------------
i=1
while (i < 10):
print (i)
i = i+1
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
1
2
3
4
5
6
7
8
9
2. ---------------------------------------
a=1
b=1
while (a<10):
print ('Iteration',a)
a=a+1
b=b+1
43
PYTHON PROGRAMMING III YEAR/II SEM MRCET
if (b == 4):
break
print ('While loop terminated')
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Iteration 1
Iteration 2
Iteration 3
While loop terminated
--------------------------
count = 0
while (count < 9):
print("The count is:", count)
count = count + 1
print("Good bye!")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link] =
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
For loop:
Python for loop is used for repeated execution of a group of statements for the desired
number of times. It iterates over the items of lists, tuples, strings, the dictionaries and other
iterable objects
44
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Sample Program:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/[Link]
1
4
16
36
121
400
Flowchart:
45
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Iterating over a list:
#list of items
list = ['M','R','C','E','T']
i=1
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
college 1 is M
college 2 is R
college 3 is C
college 4 is E
college 5 is T
tuple = (2,3,5,7)
print ('These are the first four prime numbers ')
#Iterating over the tuple
for a in tuple:
print (a)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
These are the first four prime numbers
2
3
5
7
#creating a dictionary
college = {"ces":"block1","it":"block2","ece":"block3"}
46
PYTHON PROGRAMMING III YEAR/II SEM MRCET
for keys in college:
print (keys)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Keys are:
ces
it
ece
Values are:
block1
block2
block3
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
M
R
C
E
T
for i in range(1,6):
for j in range(5,i-1,-1):
print('')
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Output:
11111
2222
333
44
48
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Break and continue:
In Python, break and continue statements can alter the flow of a normal loop. Sometimes
we wish to terminate the current iteration or even the whole loop without checking test
expression. The break and continue statements are used in these cases.
Break:
The break statement terminates the loop containing it and control of the program flows to
the statement immediately after the body of the loop. If break statement is inside a nested
loop (loop inside another loop), break will terminate the innermost loop.
Flowchart:
The following shows the working of break statement in for and while loop:
49
PYTHON PROGRAMMING III YEAR/II SEM MRCET
while test expression
Example:
print("The end")
Output:
M
R
C
E
T
The end
Output:
11
9
88
The number 88 is found
50
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Terminating the loop
#-------------------------------------
for letter in "Python": # First Example
if letter == "h":
break
print("Current Letter :", letter )
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link] =
Current Letter : P
Current Letter : y
Current Letter : t
Continue:
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
Flowchart:
The following shows the working of break statement in for and while loop:
51
PYTHON PROGRAMMING III YEAR/II SEM MRCET
for var in sequence:
# code inside for loop
If condition:
continue (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop
Example:
print("The end")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
s
t
r
n
g
The end
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
11
9
89
#------------------
for letter in "Python": # First Example
if letter == "h":
continue
print("Current Letter :", letter)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Pass:
Example:
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
53
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>>
54
PYTHON PROGRAMMING III YEAR/II SEM MRCET
UNIT III
FUNCTIONS, ARRAYS
Fruitful functions: return values, parameters, local and global scope, function composition,
recursion; Strings: string slices, immutability, string functions and methods, string module;
Python arrays, Access the Elements of an Array, array methods.
Functions, Arrays:
Fruitful functions:
We write functions that return values, which we will call fruitful functions. We have seen
the return statement before, but in a fruitful function the return statement includes a return
value. This statement means: "Return immediately from this function and use the following
expression as a return value."
(or)
Any function that returns a value is called Fruitful function. A Function that does not return
a value is called a void function
Return values:
The Keyword return is used to return back the value to the called function.
def area(radius):
temp = 3.14 * radius**2
return temp
print(area(4))
(or)
def area(radius):
return 3.14 * radius**2
print(area(2))
def absolute_value(x):
if x < 0:
55
PYTHON PROGRAMMING III YEAR/II SEM MRCET
return -x
else:
return x
Since these return statements are in an alternative conditional, only one will be executed.
As soon as a return statement executes, the function terminates without executing any
subsequent statements. Code that appears after a return statement, or any other place the
flow of execution can never reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every possible path through the program
hits a return statement. For example:
def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x
This function is incorrect because if x happens to be 0, both conditions is true, and the
function ends without hitting a return statement. If the flow of execution gets to the end of a
function, the return value is None, which is not the absolute value of 0.
By the way, Python provides a built-in function called abs that computes absolute values.
# Write a Python function that takes two lists and returns True if they have at least one
common member.
Output:
C:\Users\MRCET\AppData\Local\Programs\Python\Python38-32\pyyy\[Link]
56
PYTHON PROGRAMMING III YEAR/II SEM MRCET
True
True
None
#-----------------
def area(radius):
b = 3.14159 * radius**2
return b
Parameters:
Parameters are passed during the definition of function while Arguments are passed during
the function call.
Example:
#here a and b are parameters
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
25
#function defination
def display():
print("vandemataram")
print("i am in main")
57
PYTHON PROGRAMMING III YEAR/II SEM MRCET
#function call
display()
print("i am in main")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
i am in main
vandemataram
i am in main
def Fun1() :
print("function 1")
Fun1()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
function 1
def fun2(a) :
print(a)
fun2("hello")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Hello
def fun3():
return "welcome to python"
print(fun3())
58
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
welcome to python
def fun4(a):
return a
print(fun4("python is better then c"))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Local Scope:
A variable which is defined inside a function is local to that function. It is accessible from
the point at which it is defined until the end of the function, and exists for as long as the
function is executing
Global Scope:
A variable which is defined in the main body of a file is called a global variable. It will be
visible throughout the file, and also inside any file which imports that file.
The variable defined inside a function can also be made global by using the global
statement.
def function_name(args):
.............
global x #declaring global variable inside a function
..............
59
PYTHON PROGRAMMING III YEAR/II SEM MRCET
x = "global"
def f():
print("x inside :", x)
f()
print("x outside:", x)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
x inside : global
x outside: global
def f1():
y = "local"
print(y)
f1()
Output:
local
If we try to access the local variable outside the scope for example,
def f2():
y = "local"
f2()
print(y)
The output shows an error, because we are trying to access a local variable y in a global
scope whereas the local variable only works inside f2() or local scope.
x = "global"
def f3():
global x
y = "local"
x=x*2
print(x)
print(y)
f3()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
globalglobal
local
In the above code, we declare x as a global and y as a local variable in the f3(). Then,
we use multiplication operator * to modify the global variable x and we print
both x and y.
After calling the f3(), the value of x becomes global global because we used the x *
2 to print two times global. After that, we print the value of local variable y i.e local.
x=5
def f4():
x = 10
print("local x:", x)
f4()
print("global x:", x)
61
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
local x: 10
global x: 5
Function Composition:
Having two (or more) functions where the output of one function is the input for another. So
for example if you have two functions FunctionA and FunctionB you compose them by
doing the following.
FunctionB(FunctionA(x))
Here x is the input for FunctionA and the result of that is the input for FunctionB.
Example 1:
In the above program we tried to compose n functions with the main function created.
Example 2:
>>> colors=('red','green','blue')
>>> fruits=['orange','banana','cherry']
>>> zip(colors,fruits)
62
PYTHON PROGRAMMING III YEAR/II SEM MRCET
<zip object at 0x03DAC6C8>
>>> list(zip(colors,fruits))
Recursion:
We know that in Python, a function can call other functions. It is even possible for the
function to call itself. These type of construct are termed as recursive functions.
Factorial of a number is the product of all the integers from 1 to that number. For example,
the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
zero factorial 1
five factorial 120
----------------------
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
63
PYTHON PROGRAMMING III YEAR/II SEM MRCET
num = 4
print("The factorial of", num, "is", calc_factorial(num))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
The factorial of 4 is 24
Strings:
A string is a group/ a sequence of characters. Since Python has no provision for arrays,
we simply use strings. This is how we declare a string. We can use a pair of single or
>>> type("name")
<class 'str'>
>>> name=str()
>>> name
''
>>> a=str('mrcet')
>>> a
'mrcet'
>>> a=str(mrcet)
>>> a[2]
'c'
>>> fruit = 'banana'
>>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter. The
expression in brackets is called an index. The index indicates which character in the
sequence we want
String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0
in the beginning of the string and working their way from -1 at the end.
Slicing will start from index and will go up to stop in step of steps.
Default value of start is 0,
64
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Stop is last index of list
And for step default is 1
For example 1
Output:
Hello World!
llo
llo World!
Hello World!TEST
Example 2:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[Link]
'opt'
>>> x[3:]
65
PYTHON PROGRAMMING III YEAR/II SEM MRCET
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'
Immutability:
It is tempting to use the [] operator on the left side of an assignment, with the intention of
changing a character in a string.
For example:
Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator
66
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Note:
All the string methods will be returning either true or false as the result
1. isalnum():
67
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Isalnum() method returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
Syntax:
[Link]()
Example:
>>> string="123alpha"
>>> [Link]() True
2. isalpha():
isalpha() method returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
Syntax:
[Link]()
Example:
>>> string="nikhil"
>>> [Link]()
True
3. isdigit():
isdigit() returns true if string contains only digits and false otherwise.
Syntax:
[Link]()
Example:
>>> string="123456789"
>>> [Link]()
True
4. islower():
Islower() returns true if string has characters that are in lowercase and false otherwise.
Syntax:
68
PYTHON PROGRAMMING III YEAR/II SEM MRCET
[Link]()
Example:
>>> string="nikhil"
>>> [Link]()
True
5. isnumeric():
isnumeric() method returns true if a string contains only numeric characters and false
otherwise.
Syntax:
[Link]()
Example:
>>> string="123456789"
>>> [Link]()
True
6. isspace():
isspace() returns true if string contains only whitespace characters and false otherwise.
Syntax:
[Link]()
Example:
>>> string=" "
>>> [Link]()
True
7. istitle()
Syntax:
[Link]()
69
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Example:
>>> string="Nikhil Is Learning"
>>> [Link]()
True
8. isupper()
isupper() returns true if string has characters that are in uppercase and false otherwise.
Syntax:
[Link]()
Example:
>>> string="HELLO"
>>> [Link]()
True
9. replace()
replace() method replaces all occurrences of old in string with new or at most max
occurrences if max given.
Syntax:
[Link]()
Example:
>>> string="Nikhil Is Learning"
>>> [Link]('Nikhil','Neha')
'Neha Is Learning'
[Link]()
split() method splits the string according to delimiter str (space if not provided)
Syntax:
[Link]()
Example:
>>> string="Nikhil Is Learning"
>>> [Link]()
70
PYTHON PROGRAMMING III YEAR/II SEM MRCET
['Nikhil', 'Is', 'Learning']
[Link]()
count() method counts the occurrence of a string in another string Syntax:
[Link]()
Example:
>>> string='Nikhil Is Learning'
>>> [Link]('i')
3
[Link]()
Find() method is used for finding the index of the first occurrence of a string in another
string
Syntax:
Example:
>>> string="Nikhil Is Learning"
>>> [Link]('k')
2
[Link]()
converts lowercase letters in a string to uppercase and viceversa
Syntax:
Example:
>>> string="HELLO"
>>> [Link]()
'hello'
[Link]()
Determines if string or a substring of string (if starting index beg and ending index end are
given) starts with substring str; returns true if so and false otherwise.
71
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Syntax:
Example:
>>> string="Nikhil Is Learning"
>>> [Link]('N')
True
[Link]()
Determines if string or a substring of string (if starting index beg and ending index end are
given) ends with substring str; returns true if so and false otherwise.
Syntax:
Example:
>>> string="Nikhil Is Learning"
>>> [Link]('g')
True
String module:
This module contains a number of functions to process standard Python strings. In recent
versions, most functions are available as string methods as well.
-in module and we have to import it before using any of its constants and classes
Note:
help(string) --- gives the information about all the variables ,functions, attributes and classes
to be used in string module.
Example:
import string
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print([Link])
72
PYTHON PROGRAMMING III YEAR/II SEM MRCET
print([Link])
#print([Link])
print([Link])
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
=========================================
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Formatter
It behaves exactly same as [Link]() function. This class becomes useful if you want to
subclass it and define your own format string syntax.
Template
This class is used to create a string template for simpler string substitutions
Python arrays:
Array is a container which can hold a fix number of items and these items should be of the
same type. Most of the data structures make use of arrays to implement their algorithms.
Following are the important terms to understand the concept of Array.
Element
Index an array has a numerical index, which is used
to identify the element.
Array Representation
73
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Arrays can be declared in various ways in different languages. Below is an illustration.
Elements
Int array [10] = {10, 20, 30, 40, 50, 60, 70, 80, 85, 90}
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
Each element can be accessed via its index. For example, we can fetch an element at
index 6 as 70
Basic Operations
Typecode Value
b Represents signed integer of size 1 byte/td>
74
PYTHON PROGRAMMING III YEAR/II SEM MRCET
c Represents character of size 1 byte
Creating an array:
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)
Output:
>>>
RESTART: C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/[Link]
10
20
30
40
50
We can access each element of an array using the index of the element.
75
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Output:
RESTART: C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
10
30
Array methods:
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
76
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
Example:
>>> college=["mrcet","it","cse"]
>>> [Link]("autonomous")
>>> college
>>> [Link]("eee")
>>> [Link]("ece")
>>> college
>>> [Link]()
'ece'
>>> college
>>> [Link](4)
'eee'
>>> college
>>> [Link]("it")
>>> college
77
PYTHON PROGRAMMING III YEAR/II SEM MRCET
UNIT IV
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters, list comprehension; Tuples: tuple assignment, tuple as return value, tuple
comprehension; Dictionaries: operations and methods, comprehension;
List:
Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
----------------------
>>> x=list()
>>> x
[]
--------------------------
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
78
PYTHON PROGRAMMING III YEAR/II SEM MRCET
List operations:
These operations include indexing, slicing, adding, multiplying, and checking for
membership
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
Because lists are sequences, indexing and slicing work the same way for lists as they do for
strings.
79
PYTHON PROGRAMMING III YEAR/II SEM MRCET
L[-2] college Negative: count from the right
List slices:
>>> list1=range(1,6)
>>> list1
range(1, 6)
>>> print(list1)
range(1, 6)
>>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> list1[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[:1]
[1]
>>> list1[2:5]
[3, 4, 5]
>>> list1[:6]
[1, 2, 3, 4, 5, 6]
>>> list1[Link]
[2]
>>> list1[Link]
[2, 4, 6, 8]
List methods:
The list data type has some more methods. Here are all of the methods of list objects:
Del()
80
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Append()
Extend()
Insert()
Pop()
Remove()
Reverse()
Sort()
Delete: Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1]) #deletes the index position 1 in a list
>>> x
[5, 8, 6]
------------
>>> del(x)
>>> x # complete list gets deleted
Append: Append an item to a list
>>> x=[1,5,8,4]
>>> [Link](10)
>>> x
[1, 5, 8, 4, 10]
Extend: Append a sequence to a list.
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>> [Link](y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]
Insert: To add an item at the specified index, use the insert () method:
>>> x=[1,2,4,6,7]
81
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> [Link](2,10) #insert(index no, item to be inserted)
>>> x
[1, 2, 10, 4, 6, 7]
-------------------------
>>> [Link](4,['a',11])
>>> x
Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item.
>>> [Link]()
>>> x
[1, 2, 10, 4, 6]
-----------------------------------
>>> [Link](2)
10
>>> x
[1, 2, 4, 6]
Remove: The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>> [Link](33)
>>> x
82
PYTHON PROGRAMMING III YEAR/II SEM MRCET
[1, 2, 10, 4, 6]
>>> [Link](4)
>>> x
[1, 2, 10, 6]
>>> [Link]()
>>> x
[1, 2, 3, 4, 5, 6, 7]
-----------------------
>>> x=[10,1,5,3,8,7]
>>> [Link]()
>>> x
[1, 3, 5, 7, 8, 10]
List loop:
Loops are control structures used to repeat a given section of code a certain number of times
or until a particular condition is met.
#list of items
list = ['M','R','C','E','T']
83
PYTHON PROGRAMMING III YEAR/II SEM MRCET
i=1
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
college 1 is M
college 2 is R
college 3 is C
college 4 is E
college 5 is T
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
1
3
5
7
9
Method #3: using while loop
Mutability:
A mutable object can be changed after it is created, and an immutable object can't.
>>> x=[1,2,4,6,7]
85
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x
[1, 2, 10, 4, 6, 7]
-------------------------
>>> [Link](4,['a',11])
>>> x
Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item.
>>> [Link]()
>>> x
[1, 2, 10, 4, 6]
-----------------------------------
>>> [Link](2)
10
>>> x
[1, 2, 4, 6]
Remove: The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>> [Link](33)
>>> x
[1, 2, 10, 4, 6]
86
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> [Link](4)
>>> x
[1, 2, 10, 6]
>>> [Link]()
>>> x
[1, 2, 3, 4, 5, 6, 7]
-----------------------
>>> x=[10,1,5,3,8,7]
>>> [Link]()
>>> x
[1, 3, 5, 7, 8, 10]
Aliasing:
1. An alias is a second name for a piece of data, often easier (and more useful) than
making a copy.
2.
3. But if data can change, aliases can result in lot of hard to find bugs.
4.
For ex:
a = [81, 82, 83]
87
PYTHON PROGRAMMING III YEAR/II SEM MRCET
b = [81, 82, 83]
print(a == b)
print(a is b)
b=a
print(a == b)
print(a is b)
b[0] = 5
print(a)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
True
False
True
True
[5, 82, 83]
Because the same list has two different names, a and b, we say that it is aliased. Changes
made with one alias affect the other. In the example above, you can see that a and b refer to
the same list after executing the assignment statement b = a.
Cloning Lists:
If we want to modify a list and also keep a copy of the original, we need to be able to make a
copy of the list itself, not just the reference. This process is sometimes called cloning, to
avoid the ambiguity of the word copy.
The easiest way to clone a list is to use the slice operator. Taking any slice of a creates a new
list. In this case the slice happens to consist of the whole list.
Example:
print(a == b)
print(a is b)
b[0] = 5
print(a)
print(b)
88
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
True
False
[81, 82, 83]
[5, 82, 83]
Now we are free to make changes to b without worrying about a
List parameters:
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
Since lists are mutable, changes made to the elements referenced by the parameter change
the same list that the argument is referencing.
# for example, the function below takes a list as an argument and multiplies each element in
the list by 2:
def doubleStuff(List):
""" Overwrite each element in aList with double its value. """
List[position] = 2 * List[position]
things = [2, 5, 9]
print(things)
doubleStuff(things)
print(things)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/[Link] ==
[2, 5, 9]
89
PYTHON PROGRAMMING III YEAR/II SEM MRCET
List comprehension:
List:
List comprehensions provide a concise way to create lists. Common applications are to make
new lists where each element is the result of some operations applied to each member of
another sequence or iterable, or to create a subsequence of those elements that satisfy a
certain condition.
>>> list1=[]
[Link](x**2)
>>> list1
(or)
>>> list1
(or)
>>> list1
>>> a=5
>>> table = [[a, b, a * b] for b in range(1, 11)]
>>> for i in table:
print(i)
[5, 1, 5]
[5, 2, 10]
[5, 3, 15]
[5, 4, 20]
[5, 5, 25]
[5, 6, 30]
[5, 7, 35]
[5, 8, 40]
[5, 9, 45]
[5, 10, 50]
Tuples:
A tuple is a collection which is ordered and unchangeable. In Python tuples are written
with round brackets.
Supports all operations for sequences.
Immutable, but member objects may be mutable.
91
PYTHON PROGRAMMING III YEAR/II SEM MRCET
accidently being added, changed, or deleted.
Example:
>>> x=(1,2,3)
>>> print(x)
(1, 2, 3)
>>> x
(1, 2, 3)
-----------------------
>>> x=()
>>> x
()
----------------------------
>>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)
-----------------------------
>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)
92
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Access tuple items: Access tuple items by referring to the index number, inside square
brackets
>>> x=('a','b','c','g')
>>> print(x[2])
c
Change tuple items: Once a tuple is created, you cannot change its values. Tuples
are unchangeable.
>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
x[1]=10
TypeError: 'tuple' object does not support item assignment
>>> x
(2, 5, 7, '4', 8) # the value is still the same
Loop through a tuple: We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)
4
5
6
7
2
aa
Count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> [Link](2)
4
Index (): Searches the tuple for a specified value and returns the position of where it
was found
93
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> [Link](2)
1
(Or)
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=[Link](2)
>>> print(y)
1
Length (): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
12
Tuple Assignment
Python has tuple assignment feature which enables you to assign more than one variable at a
time. In here, we have assigned tuple 1 with the college information like college name, year,
etc. and another tuple 2 with the values in it like number (1, 2, 7).
For Example,
>>> print(tup1[0])
mrcet
>>> print(tup2[1:4])
(2, 3, 4)
Run the above code- It gives name mrcet for first tuple while for second tuple it gives
number (2, 3, 4)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/[Link]
mrcet college
20
def circleInfo(r):
""" Return (circumference, area) of a circle of radius r """
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)
print(circleInfo(10))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/[Link]
(62.8318, 314.159)
95