0% found this document useful (0 votes)
2 views82 pages

Unit II

Uploaded by

sanjucrypto1
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)
2 views82 pages

Unit II

Uploaded by

sanjucrypto1
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/ 82

Unit II -LOOPS, FUCTIONS AND

LISTS
LOOPS, FUCTIONS AND LISTS
Loop Structures/Iterative Statements –Loop
Control Statements – List – Adding Items to a
List – Finding and Updating an Item – Nested
Lists –List Concatenation – List Slices – List
Methods – List Loop – Mutability. Function Call
and Returning Values – Fruitful Function –
Parameter Passing – Local and Global Scope –
Recursive Functions.
ITERATION STATEMENTS

• An iteration statement allows a code block to be repeated a


certain number of times.
STATE:
• It is possible to have more than one assignment for the same
variable.
• The value which is assigned at the last is given to the variable.
• The new assignment replaces the old value with the new value.
Example
x=5
y=3
x=4
print(x)
print(y)
Output:
4
3
• The variable can also be updated as follows:
• Example:
x=5
x=x+2
print(x)
Output:
7
WHILE:

• A while loop repeatedly executes the statement(s) as long


as a given condition is true.
Syntax:
while expression:
statement(s)
• Here, statement(s) may be a single statement or a block of
statements.
• The condition may be any expression, and true is any
non-zero value. The loop iterates while the condition is true.
• When the condition becomes false, program control passes
to the line immediately following the loop.
Program:

count = 0
while (count < 9):
print ("The count is:", count)
count = count + 1
print ("Good bye!")
Output:
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:

• For statement iterates over the items of any


sequence (a list or a string), in the order that
they appear in the sequence.
Syntax:
for <variable> in <sequence>:
<statements>
else:
<statements>
• The items of the sequence object are assigned
one after the other to the loop variable.
• For each item in the sequence, the body of the
loop is executed.
Example 1:
languages = ["C", "C++", "Perl", "Python"]
for x in languages:
print(x)
Output
C
C++
Perl
Python
Example 2:
a = [’cat’, ’window’, ’house’]
for x in a:
print(x, len(x))
Output
cat 3
window 6
house 5
range() Function:

• The built-in function range() is used to iterate over a sequence of numbers.


Syntax:
(i) for variablename in range(startvalue, endvalue, increment/decrement
value):
statement(s)
Example 1:
for i in range(0, 10, 3):
print(i)
Output:
0
3
6
9
– displays the numbers from 0 to 10 by incrementing by 3
Example 2:
for i in range(-10, -100, -30) :
print(i)
Output:
-10
-40
-70
- displays the numbers from -10 to -100 by
decrementing by 30
(ii)for variablename in range(startvalue, endvalue):
statement(s)
Example
for i in range(5, 10):
print(i)
Output
5
6
7
8
9
– displays the numbers from 5 to 9
(iii) for variablename in range(endvalue):
statement(s)
Example
for i in range(5):
print(i)
Output
0
1
2
3
4
BREAK

• The break statement breaks out of the for,


while or if loop.
• The break statement breaks the loop
statement and transfers the flow of execution
to the statement immediately following the
loop.
Syntax:
• break
Working of break statement:
for variablename in sequence:
if condition:
break
statement(s) #Outside
Program
for val in “string”:
if val==”i”:
break
print(val)
print(“End”)
Output:
s
t
r
End
CONTINUE
• The continue statement causes the loop to skip the
statements after continue and the control is
transferred to the start of the loop.
Syntax:
continue
Working of continue statement:
for variablename in sequence:
if condition:
continue
statement(s)
Program:
for val in “string”:
if val==”i”:
continue
print(val)
print(“End”)
Output:
s
t
r
n
g
End
PASS
• The pass statement do nothing. It can be used when a statement is
required syntactically but the program requires no action.
• The pass statement can be used in places where the program code cannot
be left as blank, but that can be written in future.
Syntax:
pass
Program:
sequence={'p','a','s','s'}
for val in sequence:
pass
Output:
No output will be displayed
LIST

• A list is a sequence of values of any type.


• The values in a list are called elements or items.
• Example:
a=[2,3.14,True,'s']
List index
• Any integer expression can be used as an index.
• To read or write an element that does not exist, IndexError
will be displayed.
• If an index has a negative value, it counts backward from the
end of the list.
• Creation of list
• To create a list, the elements are enclosed in square
brackets ([ and ])
• A list that contains no elements is called an empty list.
This can be created with empty brackets [].
Syntax:
– [elements] or []
Example
['c',2,3.14,True] or list1=[]
A list within another list is nested.
Example: l=[1,[2,3,4],4.5]
Adding Items to a List
Methods to add elements to List in Python
• There are four methods to add elements to a List
in Python.
• append()- append the object to the end of the list.
• insert()- inserts the object before the given index.
• extend()- extends the list by appending elements
from the iterable.
• List Concatenation- We can use + operator to
concatenate multiple lists and create a new list.
Append Items
• To add an item to the end of the list, use
the append() method.
Example
list = ["apple", "banana", "cherry"]
list.append("orange")
print(list)
Output
['apple', 'banana', 'cherry', 'orange']
Insert Items

• To insert a list item at a specified index, use


the insert() method.
• The insert() method inserts an item at the
specified index.
Example
list 1= ["apple", "banana", "cherry"]
list1.insert(1, "orange")
print(list1)
Output
['apple', 'orange', 'banana', 'cherry']
Extend List

• To append elements from another list to the


current list, use the extend() method.
Example
list = ["apple", "banana", "cherry"]
list1 = ["mango", "pineapple", "papaya"]
list.extend(list1)
print(list)
Output
['apple', 'banana', 'cherry', 'mango', 'pineapple',
'papaya']
Add Any Iterable

• The extend() method does not have to


append lists, you can add any iterable object
(tuples, sets, dictionaries etc.)
Example
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)
Output
['apple', 'banana', 'cherry', 'kiwi', 'orange']
Finding and Updating an Item
Different ways to update Python List
Python list provides the following methods to
modify the data.
• list.append(value) # Append a value
• list.extend(iterable) # Append a series of values
• list.insert(index, value) # At index, insert value
• list.remove(value) # Remove first instance of value
• list.clear() # Remove all elements
Continued
list.append(value)
• If you like to add a single element to the python list
then list.append(value) is the best fit for you. The
list.append(value) always adds the value to the end of
existing list.
Example
list = [1, 2, 3, 4]
list.append(5)
print(list)
Output
[1, 2, 3, 4, 5]
Continued
list.extend(iterable)
The append and extend methods have a similar purpose:
to add data to the end of a list. The difference is that
the append method adds a single element to the end
of the list, whereas the extend method appends a
series of elements from a collection or iterable.
Example
list = [1, 2, 3, 4]
list.extend([5, 6, 7])
print(list)
Output
[1, 2, 3, 4, 5, 6, 7]
Continued
list.insert(index, value)
The insert() method similar to the append() method,
however insert method inserts the value at the given
index position, where as append() always add the
element at the end of the list.
Example
list = [10, 20, 40]
list.insert(2, 30 ) # At index 2, insert 30.
print(list)
Output
[10, 20, 30, 40]
Continued
• If the provided index out of range, then the
insert() method adds the new value at the end of
the list, and it inserts the new value to the
beginning of the list if the given index is too low.
Example
a_list = [10, 20, 30]
a_list.insert(100, 40)
print(a_list)
Output
[10, 20, 30, 40]
Continued
list.remove(value)
• The remove(value) method removes the first
occurrence of the given value from the list. There must
be one occurrence of the provided value, otherwise
the Python raises ValueError.
Example
a_list = [1, 2, 3, 4, 5, 4]
a_list.remove(4)
print(a_list)
Output
[1, 2, 3, 5, 4]
Removing min and max values from
the list
Example
a_list = [1, 2, 3, 4, 5, 4, 7, 9 , -1]
a_list.remove(max(a_list))
a_list.remove(min(a_list))
print(a_list)
Output
[1, 2, 3, 4, 5, 4, 7]
Continued
list.clear()
The clear() method used to remove all the elements
from the list. The same we can also do with del
list[:].
Example
a_list = [10, 20, 30, 40]
a_list.clear()
print(a_list)
Output
[]
Assigning List values to variables
• List values can be assigned by using listname.
Syntax:
listname=[list of values]
Example
>>>list1=['c',2,3.14,True]
>>>print(list1)
Output
['c',2,3.14,True]
Representation of List
Accessing Values in List
• List values can be accessed by using listname followed by index or
indices within square brackets.
• Syntax:
listname[index]
Example
>>>list1 = ['python', 'hello', 2017]
>>>print ("list1[0]: ", list1[0])
Output
list1[0]: python
Deleting elements in the List
• There are several ways to delete elements
from a list.
1. pop()
• pop() modifies the list and returns the
element that was removed. If an index is not
given, it deletes and returns the last element.
• If the index of the element is known, pop()
function can be used.
Syntax:
variablename=listname.pop(index)
Example:
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> t
['a', 'c']
>>> x
'b'
2.del :
• If the index is known and the removed value is not needed, del operator can be used
to delete
• the element at the given index.
Syntax:
del listname[index] Example:
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> t
['a', 'c']
• To remove more than one element, del with a slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> t
['a', 'f']
3.remove():
• If the element to be deleted is known and the
removed value is not needed, remove() can be used to
remove the given element.
Syntax:
listname.remove(element)
Example:
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> t
['a', 'c']
List Operations

The + operator concatenates lists:


>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> c
[1, 2, 3, 4, 5, 6]
• The * operator repeats a list a given number
of times:
>>> [0] * 4
[0, 0, 0, 0]
This repeats [0] four times.
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
This repeats the list [1, 2, 3] three times.
List Slices
• The slice operator also works on lists.
Syntax:
listname[startindex : endindex]
• The operator [n:m] returns the part of the string from
the “n-th” character to the “m-th” character, including
the first but excluding the last.
Example:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
• If the first index is omitted, the slice starts at the beginning.
>>> t[:4]
['a', 'b', 'c', 'd']
• If the second index is omitted, the slice goes to the end.
>>> t[3:]
['d', 'e', 'f']
• If both the indexes are omitted, the slice is a copy of the
whole list.
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
• A slice operator on the left side of an
assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print(t)
['a', 'x', 'y', 'd', 'e', 'f']
List Methods
• Python provides methods that operate on lists.
1.append()
– adds a new element to the end of a list:
Syntax:
listname.append(element)
Example
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> t
['a', 'b', 'c', 'd']
2. extend()
– takes a list as an argument and appends all of the elements:
Syntax:
listname1.extend(listname2)
Example
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> t1
['a', 'b', 'c', 'd', 'e']
This example leaves t2 unmodified
3. sort()
– arranges the elements of the list in ascending order
Syntax:
listname.sort()
Example
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> t
['a', 'b', 'c', 'd', 'e']
4. reverse()
– used to reverse the entire list.
- Syntax:
listname.reverse()
Example:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> t
['a', 'b', 'e', 'c', 'd']
5. count()
– returns the number of occurrences of the given
substring.
– Syntax:
listname.count(element)
Example
>>> t = ['d', 'c', 'a', 'e', 'b', 'a']
>>>t.count('a')
2
6. insert()
– used to insert the given element in the given position.
-Syntax:
listname.insert(index,element)
Example:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.insert(4,'f')
>>> t
['d', 'c', 'e', 'b', 'f', 'a']
7. pop()
removes and returns the last element in the list.
– Syntax:
listname.pop()
Example:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.pop()
'a'
• pop(index)
– removes and returns the element at given index in the
list.
– Syntax:
listname.pop(index)
Example:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.pop(2)
'e'
8. remove()
– If the element to be deleted is known and the removed
value is not needed, remove() can be used to remove the
given element.
Syntax:
listname.remove(element)
Example:
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> t
['a', 'c']
Traversing a list or List Loops

– The most common way to traverse the elements of a list is


with a for loop. This is used to read the elements of the list
– Syntax:
for variable in listname:
print(variablename)
Example:
list1 = ['python', 'hello', 2017]
for i in list1:
print(i)
Continued
• The built-in functions range and len can also be used.
• The function len returns the number of elements in
the list.
• The function range returns a list of indices from 0 to n
-1, where n is the length of the list.
Example:
numbers=[1,2,3,4]
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
print(numbers[i])
This loop traverses the list and updates each element.
Output
2
4
6
8
Continued
• A for loop over an empty list never runs the statements
inside the loop:
for x in []:
print('This never happens.')
• A list can contain another list, the nested list is counted
as a single element.
Example:
>>> l=['python',1,[20,35,40],4.5,True]
>>>print(len(l))
5
Mutability(Lists are mutable)

– Lists are mutable. This means the elements in the list can be modified.
– The syntax for accessing the elements is to use the index value inside the
square bracket.
– The index starts at 0 from the left end and -1 from the right end.:
– When the bracket operator appears on the left side of an assignment, it
identifies the element of the list that will be assigned.
>>> list1 = [25,10]
>>>print(list1)
[25,10]
>>>list1[1] = 5
>>> print(list1)
[25, 5]
Continued

Fig1: Mutability
FUNCTION CALL AND RETURNING VALUES

• Function composition is the ability to call one function from within


another function. It is the way of combining functions such that
the result of each function is passed as the argument of the next
function.
• The composition of two functions f and g is denoted by f(g(x)).
• x is the argument of g and the result of g(x) is the argument for f.
Example:
• Write a function that takes two points ie, the center of the circle(c)
and a point on the perimeter(p), and computes the area of the
circle.
Center point is (xc,yc)
Perimeter point is (xp,yp)
• The first step is to find the radius of the circle,
which is the distance between the two points.
radius = distance(xc, yc, xp, yp)
• The next step is to find the area of a circle with
that radius.
result = area(radius)
• By using the method of function composition, it
can be written as,
def circle_area(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))
Program:
import math
def distance(xc,yc,xp,yp):
dx=xp-xc
dy=yp-yc
radius=math.sqrt(dx**2+dy**2)
return radius
def area(radius):
return (math.pi*radius*radius)
xc=int(input("Enter xc"))
yc=int(input("Enter yc"))
xp=int(input("Enter xp"))
yp=int(input("Enter yp"))
a=area(distance(xc,yc,xp,yp))
print(“Area of circle:”,a)
(or)
import math
def distance(xc,yc,xp,yp):
dx=xp-xc
dy=yp-yc
radius=math.sqrt(dx**2+dy**2)
return radius
def area(radius):
return (math.pi*radius*radius)
a=area(distance(2,3,4,5))
print(“Area of circle:”,a)
FRUITFUL FUNCTIONS:

• Fruitful functions are functions in which the


return statements includes expressions.
RETURN VALUES:
• Calling the function generates a return value,
which will be assigned to a variable or use as part
of an expression.
Example: Find the area of a circle using radius. def
area(radius):
a = math.pi * radius**2
return a
• In the fruitful function, the return statement
includes an expression. This means “Return
immediately from this function and use the
following expression as a return value.”
• Above function can also written as follows:
def area(radius):
return math.pi * radius**2
On the other hand, temporary variables like a
can make debugging easier.
Sometimes it is useful to have multiple return statements, one in
each branch of a conditional:
def absolute_value(x):
if x < 0:
return -x
else:
return x
• Since these return statements are in an alternative conditional,
only one runs.
• As soon as a return statement runs, the function terminates.
• Code that appears after a return statement will never be executed.
This code is called as 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 when x happens to be 0, neither the
condition is True or False, and the function ends without hitting a
return statement. Then the return value will be None.
>>> print(absolute_value(0))
None
Program
import math
def circle(r):
return math.sqrt.pi*r*r
r=int(input(“Enter the radius”))
a=circle(r)
print(“Area of circle:”,a)
Output:
Enter the radius:3
Area of circle: 28.26
PARAMETERS AND ARGUMENTS:

• 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. The function that takes an argument is as follows:
def print_twice(bruce):
print(bruce)
print(bruce)
bruce=“bruce”
print_twice(bruce)
Output:
bruce
bruce
• This function assigns the argument to a parameter named
bruce.
• The value can also be used as argument. When the function
is called, it prints the value of the parameter twice.
Example:
>>> print_twice('Spam')
Spam
Spam
>>> 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('Spam'*4)
Spam Spam Spam Spam
Spam Spam Spam Spam
• Variable can also be used as an argument. Example:
>>> michael = 'Eric, the half a bee.'
>>> print_twice(michael)
Eric, the half a bee.
Eric, the half a bee.
LOCAL AND GLOBAL SCOPE:

– The usage of variables depends on the location of of declaration


statement.
– Scope of a variable determines the portion of the program where a
variable can be accessed.
– There are two Scopes
» Local Scope
» Global Scope
Local Variables
• Variables declared inside the function. Its lifetime
and scope is within a block/function.
• Cannot access outside the function.
• If try to access, then error will be displayed by
interpreter
Global Variables
• Variables declared in main function or above function definition.
• Its lifetime is within the full program.
Program
a=10 # Global Variable
b=5#Global Variable
def add():
print("a+b",(a+b))
def sub():
a=3 # Local Variable
b=2 #Local Variable
print("a-b", a-b)
RECURSION

• Recursion function is a function which calls


itself again and again until the condition is
true.
• It has a termination condition.
• Advantages
– Simplicity
– The length of the program can be reduced.
– A complex task can be broken into simpler subproblems using
recursion.
– Sequence generation is easier.
• Disadvantages
– The logic behind recursion is sometimes hard to understand.
– Recursive calls are inefficient as they take more memory and
time.
– Recursive functions are hard to debug.

• Examples of recursion
– Factorial
– Fibonacci Series
Program:
• To find the factorial of the given number
def fact(n):
if n==0:
return 1
else:
return n*fact(n-1)
n=int(input("Enter a number"))
print("The factorial is ",fact(n))
Output:
Enter a number: 5
The factorial is 120.
Program 2:
• To print the fibonacci series in the given range
def fib(n):
if(n==0):
return 0
elif(n==1):
return 1
else:
return fib(n-1)+fib(n-2)
n=int(input("Enter the range for fibonacci series:"))
print("Fibonacci Series")
for i in range(0,n):
print(fib(i))
Output:
Enter the range for fibonacci series:6
Fibonacci Series
0
1
1
2
3
5
Infinite recursion
• Infinite recursion happens when recursive
function call fails to stop. The program with
infinite recursion never terminates. Pyhton display
the error message on infinite recursion.
Example:
def display():
display()
display()

You might also like