Unit II
Unit II
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
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:
– 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
• 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()