SlideShare a Scribd company logo
Module 3
SELECTION AND ITERATION USING
PYTHON
Syllabus
SELECTION AND ITERATION USING PYTHON:- if-else, elif, for loop, range, while
loop. Sequence data types in Python - list, tuple, set, strings, dictionary, Creating and
using Arrays in Python (using Numpy library).
DECOMPOSITION AND MODULARIZATION :- Problem decomposition as a strategy
for solving complex problems, Modularization, Motivation for modularization, Defining and
using functions in Python, Functions with multiple return values.
RECURSION:- Recursion Defined, Reasons for using Recursion, The Call Stack, Recursion
and the Stack, Avoiding Circularity in Recursion, Sample problems - Finding the nth Fibonacci
number, greatest common divisor of two positive integers, the factorial of a positive integer,
adding two positive integers, the sum of digits of a positive number.
if Statement
 To check conditions and change the behavior of the program accordingly.
if x > 0:
print("x is positive”)
• General Synatax:
if Condition:
FIRST STATEMENT
...
LAST
STATEMENT
 The first unintended statement marks the end of the block.
 A statement block inside a compound statement is called the body of
the statement.
 If there is no statements in the block, then use the pass statement, which
does nothing.
if Statement
 A second form of the if statement is alternative execution, in which
there are two possibilities and the condition determines which one gets
executed.
 The syntax looks like this:
if x%2 == 0:
print(x, "is even“)
else:
print(x, "is odd”)
The alternatives are called branches.
if…else Statement
 Sometimes there are more than two possibilities and we need more than two
branches.
if x < y:
print(x, "is less than", y)
elif x > y: #abbreviation of else if
print(x, "is greater than", y)
else:
print(x, "and", y, “are equal”)
elif Statement
Nested Conditionals
 One conditional can also be nested within another.
if x == y:
print(x, "and", y, “are equal”)
else:
if x < y:
print(x, "is less than", y)
else:
print(x, "is greater
than", y)
Example Questions
1. Write a program to check whether a candidate is eligible to vote or not
(Based on his age).
2. Write a program to find the largest of three numbers using logical operator
and without using logical operator.
3. Write a menu driven program to perform different mathematical operations.
4. Write a program to print the grade of a student based on the total marks
obtained from 3 subjects. Consider 10 marks for each subject (26 - 30:
Grade A, 21 – 25: Grade B, 16 – 20: Grade C, <=15: F).
The while Statement
 For repeating or looping identical tasks.
n = 10
while n > 0:
print(n)
n = n-1
print("Blastof
f!“)
The while Statement
 Here is the flow of execution for a while statement.
1. Evaluate the condition, yielding 0 or 1.
2. If the condition is false (0), exit the while statement and continue execution at
the next statement.
3. If the condition is true (1), execute each of the statements in the body and then
go back to step 1.
Example Questions
1. Write a program to print the sum of first ‘n’ numbers.
2. Write a program to print a multiplication table for a given number.
3. Write a program to print the odd numbers between two limits.
4. Write a program to check whether the given number is Armstrong number or
not.
5. Write a program to reverse the given number.
6. Write a program to check whether the given number is palindrome or not.
Nested Loop
 We can have a loop statement inside another loop.
Syntax:
while expression:
statement(s)
while
expression:
statement(s)
statement(s)
Nested Loop
 Example: To print the pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Nested Loop
 Answer: To print the pattern
n = int(input("Enter the number of rows"))
i = 1
j = 1
while i <= n:
j = 1
while j <= i:
print(j, ' ', end=' ')
j += 1
print(
) i +=
1
Definite Loops - 'for'
 Definite loops iterate through the members of a set.
num = int(input("Enter the limit: "))
sum = 0
for i in range(1, num + 1): #creates a list
sum = sum + i
print(sum)
Example Questions
1. Write a program to print the sum of squares of first ‘n’ numbers.
2. Write a program to print the Fibonacci series up to a given limit.
3. Write a program to check whether the given number is a prime number or
not.
4. Program to print all prime numbers up to a given limit.
 The else keyword in a for loop specifies a block of code to be
executed when the loop is finished:
 Print all numbers from 0 to 5, and print a message when the loop has ended
for x in range(6):
print(x)
else:
print("Finally
finished!")
for…else Statement
 To check whether a given number is prime or not:
num = int(input("Enter the num: "))
for i in range(2, (num//2)+1):
if num % i == 0:
print("It is not prime")
break
else:
print("Prime")
for…else Statement - Example
 The else keyword in a while loop specifies a block of code to be
executed when the loop is finished:
 Example
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is
no longer
less than
while…else Statement
The 'break' Statement
while True:
line = input("Enter: ")
if line == 'done':
break
print(line)
print 'Good Bye........'
The 'continue' Statement
while True:
line = input("Enter: ")
if line == '#':
continue
if line == 'done':
break
print (line)
print ('Good
Bye........‘)
Sequence Data Types
Strings
 Made up of smaller pieces of characters – Compound Data Types
 For example,
>>> fruit = "banana"
>>> letter = fruit[1]
>>> print(letter)
a
 The expression in brackets is called an index, which can be any
integer expression.
 Index always starts from zero.
String Length
 The len function returns the number of characters in a
string
>>> fruit = "banana"
>>> len(fruit)
6
 To get the last letter of
a string,
length = len(fruit)
last = fruit[length-1]
Or
fruit[-1]
Traversal & for Loop
 Processing a string one character at a time.
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
for char in fruit:
print(char)
Predict the Output
prefixes = "JKLMNOPQ"
suffix = "ack"
for letter in prefixes:
print(letter + suffix)
String Slices
 A segment of a string is called a slice.
 For example:
>>> s = "Peter, Paul, and Mary"
>>> print(s[0:5])
Peter
>>> print(s[7:11])
Paul
>>>
print(s[17:21])
Mary
String Slices
 If you omit the first index (before the colon), the slice starts at the beginning of
the string.
 If you omit the second index, the slice goes to the end of the string.
>>> fruit = "banana"
>>> fruit[:3]
’ban’
>>> fruit[3:]
’ana’
 What do you think s[:] means?
String Comparison
 The comparison operators (==, <, >) work on strings also.
word = “Zebra”
if word < "banana":
print(word+” comes before banana.”)
elif word > "banana":
print(word+” comes after banana.”)
if word == “banana”:
print(“Same...”)
 All the uppercase letters come before all the
lowercase letters.
Strings are Immutable
 Strings are immutable, which means we can’t change an existing string.
greeting = "Hello, world!"
greeting[0] = ’J’ #
ERROR! print(greeting)
Solution
greeting = "Hello, world!"
newGreeting = ’J’ + greeting[1:]
print(newGreeting)
Looping and Counting in a String
fruit = "banana"
count = 0
for char in fruit:
if char == ’a’:
count = count
+ 1 print(count)
The above program counts the occurrences of a particular character in
a given string.
The string module
 Python String module contains some constants, utility function, and classes for
string manipulation.
 It’s a built-in module and we have to import it before using any of its constants
and classes.
>>> import string
String Module Constants
import string
print(string.ascii_letters)
#abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.ascii_lowercas
e)
#abcdefghijklmnopqrstuvwxyz
print(string.ascii_uppercas
e)
#ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits) #0123456789
print(string.hexdigits) #0123456789abcdefABCDEF
print(string.whitespace) # ' tnrx0bx0c'
print(string.punctuation) #!"#$%&'()*+,-./:;?@[]^_`{|}~
Python String Methods
 All string methods returns new values. They do not change the original
string.
Method Description
find() or index()
Searches the string for a specified value and
returns the index
count()
Returns the number of times a specified
value occurs in a string
startswith()
Returns true if the string starts with
the specified value
endswith()
Returns true if the string ends with the
specified value
Python String Methods
isalnum()
Returns True if all characters in the string
are alphanumeric (Eg:- “hello123”)
isalpha()
Returns True if all characters in the string are
in the alphabet (Eg:- “hello”)
isdecimal()
Returns True if all characters in the string
are decimals (Eg:- 2, 10, 14, etc.)
isdigit()
Returns True if all characters in the string are
digits (Eg:- “1234”)
islower()
Returns True if all characters in the string
are lower case (Eg:- “hello”)
Python String Methods
isnumeric()
Returns True if all characters in the string
are numeric (Eg:- 2, 10, 14, etc.)
isupper()
Returns True if all characters in the string are
upper case (Eg:- “HELLO”)
lower() Converts a string into lower case (“HELLO”.lower())
upper() Converts a string into upper case (“hello”.upper())
Using 'in' as Operator
 The in keyword is used to check to see if one string is in another
string.
 It returns True or False and can be used with if statement.
>>> fruit = “banana”
>>> 'nan' in fruit
True
>>> 'man' in fruit
False
String Questions
1. Write a program to search a substring in a string. If yes, print the position index.
(Hint: use find function)
2. Write a program to replace a substring with another string. (Hint: use
replace function )
str.replace(“xyz”, “abc”), xyz will be replaced by abc
3. Write a program to delete a substring from a string. (Hint: use replace function)
str.replace(“xyz”, “”), xyz will be replaced by “”.
4. Write a program to check whether a given string is palindrome or
not.
(“malayalam”).
5. Write a program to check whether a given string is symmetrical or
not. (“khelokhelo”).
Lists
 Lists are used to store multiple items in a single variable.
 Lists are created using square brackets.
thislist = ["apple", "banana", "cherry"]
print(thislist)
 List items are ordered, changeable, and allow duplicate values.
 List items are indexed, the first item has index [0], the second
item has index
[1] etc.
 To create an empty list
e = []
The range Function
 Lists that contain consecutive integers are common, so Python provides
a simple way to create them:
>>> range(1, 5)
[1, 2, 3, 4]
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 10, 2)
[1, 3, 5, 7, 9]
Accessing Elements
 List items are indexed and you can access them by referring to the
index number:
>>> numbers = [2, 4, 8, 20]
>>> print(numbers[2])
8
 If an index has a negative value, it
counts backward from the end of
the list.
>>> numbers[-3]
4
Accessing Elements
sem = ["S1", "S3", "S5", "S7"]
i = 0
while i < 4:
print(sem[i])
i = i + 1
List Length
 The function len returns the length of a list.
sem = ["S1", "S3", "S5", "S7"]
i = 0
while i < len(sem):
print(sem[i])
i = i + 1
What will be the output of
len function for the
following list?
[’s3’, 1,
[’COLLEGE’,
List Membership
 The in keyword is used to check the membership of an element in
list.
 It returns True or False values.
>>> sem = ["S1", "S3", "S5", "S7"]
>>> 'S1' in sem
True
>>> 'S2' not in sem
True
Questions
1. Write a program to search an element in a list.
2. Write a program to swap the first and last elements of a list.
List & for Loop
sem = ["S1", "S3", "S5", "S7"]
for s in sem:
print(s)

Predict the output
for num in range(20):
if num % 2 == 0:
print(number)
List Operations
 The + operator concatenates
lists.
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
[1, 2, 3, 4, 5, 6]
List Operations
 The * operator repeats a list a given number of
times.
[0] * 4
[0, 0, 0, 0]
[1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
List Slices
 Same as string.
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3]
[’b’, ’c’]
>>> list[:4]
[’a’, ’b’, ’c’, ’d’]
>>> list[3:]
[’d’, ’e’, ’f’]
>>> list[:]
[’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
Lists are Mutable
 Unlike strings, lists are mutable, which means we can change their elements.
>>> fruit = ["banana", "apple", "quince"]
>>> fruit[0] = "pear"
>>> fruit[-1] = "orange"
>>> print(fruit)
[’pear’, ’apple’, ’orange’]
Lists are Mutable
 With the slice operator we can update several elements at once.
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3] = [’x’, ’y’]
>>> print(list)
[’a’, ’x’, ’y’, ’d’, ’e’, ’f’]
Lists are Mutable
 We can also remove elements from a list by assigning the empty list to them.
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3] = []
>>> print(list)
[’a’, ’d’, ’e’, ’f’]
Lists Deletion
 Using slices to delete list elements is error-prone.
 del method removes an element from a list
>>> a = [’one’, ’two’, ’three’]
>>> del a[1]
>>> print(a) # [’one’, ’three’]
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> del list[1:5]
>>> print(list) # [’a’, ’f’]
Lists Functions
>>> x = [1, 2, 3, 4]
>>> x.append(5) # [1, 2, 3, 4, 5]
>>> z = [4, 5, 6, 7]
>>> x.extend(z) #[1, 2, 3, 4, 5, 4, 5, 6, 7]
>>> x.count(4) # 2
>>> x.index(5) # 4
>>> x.pop() # 7 [1, 2, 3, 4, 5, 4, 5, 6]
>>> x.remove(4) # [1, 2, 3, 5, 4, 5, 6]
>>> x.insert(1, 8) # [1, 8, 2, 3, 5, 4, 5, 6]
>>> x.reverse() # [6, 5, 4, 5, 3, 2, 8, 1]
>>> x.sort() # [1, 2, 3, 4, 5, 5, 6, 8]
>>> x.sort(reverse = True) # [8, 6, 5, 5, 4, 3, 2, 1]
Questions
1. Write a program to find the smallest element in a list.
2. Write a Python program to print all the odd numbers and even numbers in a
list separately.
3. Write a program to list the common elements in two lists.
4. Write a program to rotate a given list.
5. Write a program to remove all vowels from a given string.
Tuples
Similar to a list except that it is immutable – Comma separated values.
For example,
>>> tuple = ’a’, ’b’, ’c’, ’d’, ’e’
Or
>>> tuple = (’a’, ’b’, ’c’, ’d’, ’e’)
To create a tuple with a single element, we have to include the final comma:
>>> t1 = (’a’,)
Tuples
The operations on tuples are the same as the operations on lists.
>>> tuple = (’a’, ’b’, ’c’, ’d’, ’e’)
>>> tuple[0]
’a’
And the slice operator selects a range of elements.
>>> tuple[1:3]
(’b’, ’c’)
>>> tuple[0] = ’A’
TypeError: object doesn’t support item assignment
Tuple Assignment
To swap two variables a and
b.
>>> temp = a
>>> a = b
>>> b = temp

Python provides an easy way to do this.
>>> a, b = b, a

The left side is a tuple of variables; the right side is a tuple of values.
Set
Set items can be of any data type or can contain different data types: String,
int and Boolean data types.
Example:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
set4 = {"abc", 34, True, 40, "male"}
The set() Constructor
The set() constructor is used to make a set
Example:
set1 = set(("apple","banana“,"cherry"))
print(set1)
O/P: {“apple","banana“,"cherry”}
Access Set Items
You cannot access items in a set by referring to an index.
You can loop through the set items using a for loop, or ask if a specified value
is present in a set, by using the in keyword.
Example:
set1 = {"apple", "banana", "cherry"}
for x in set1:
print(x)
Add Set Items
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set, use the add() method.
set1 = {"apple", "banana", "cherry"}
set1.add("orange")
To add items from another set into the current set, use the
update() method.
set1 = {"apple", "banana", "cherry"}
t = {"pineapple", "mango", "papaya"}
set1.update(t)
Add Set Items
The object in the update() method does not have to be a set, it can be
any iterable object (tuples, lists, dictionaries etc.).
set1 = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
set1.update(mylist)
print(set1)
O/P: {'banana', 'cherry',
'apple', 'orange', 'kiwi'}
Remove Set Items
To remove an item in a set, use the remove(), or the discard() method.
If theitemto remove does not exist, remove() will raise an
error.
discard() will NOT raise an error.
set1 = {"apple", "banana", "cherry"}
set1.remove("banana")
print(thisset) # {'apple',
'cherry'}
Remove Set Items
You can also use the pop() method to remove an item, but this method
will remove the last item.
Remember that sets are unordered, so you will not know what item that gets
removed.
The return value of the pop() method is the removed item.
set1 = {"apple", "banana", "cherry"}
x = set1.pop()
print(x)
print(set1)
# banana
# {'apple', 'cherry'}
Remove Set Items
The clear() method empties the set. The del keyword will delete the
set completely:
set1 = {"apple", "banana", "cherry"}
set1.clear()
print(set1) # set()
set1 = {"apple", "banana", "cherry"}
del set1
print(set1) # this will raise an error
because the set no longer exists
Join Sets
There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set containing all items
from both sets, or the update() method that inserts all the items from
one set into another.
Both union() and update() will exclude any duplicate items.
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
O/P: {2, 'b', 'c', 3,
1, 'a'}
Join Sets
The intersection_update() method will keep only the items that
are present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)
O/P: {'apple'}
Join Sets
The intersection() method will return a new set, that only contains
the items that are present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
O/P: {'apple'}
Join Sets
The symmetric_difference_update() method will keep only
the elements that are NOT present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)
O/P: {'google', 'banana',
'microsoft', 'cherry'}
Join Sets
The symmetric_difference() method will return a new set,
that contains only the elements that are NOT present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(x)
O/P: {'google', 'banana',
'microsoft', 'cherry'}
Dictionaries
Dictionaries are similar to other compound types except that they can use any
immutable type as an index.
>>> eng2ml = {}
>>> eng2ml[’one’] = ’Onnu’
>>> eng2ml[’two’] = ’Randu’
>>> print (eng2ml)
{’one’: ’Onnu’, ’two’: ’Randu’}
Ina dictionary, the indices are called keys, so the elements are called
key- value pairs.
Dictionaries
 Or we can create a dictionary like:
>>> eng2ml = {’one’: ’Onnu’,
’Moonnu’}
’two’: ’Randu’, ’three’:
 If we print the value of eng2ml again, we get a surprise:
>>> print (eng2ml)
{’one’: ’Onnu’, ’three’: ’Moonnu’, ’two’: ’Randu’}
# Not in order
>>> print (eng2ml[’two’])
’Randu’
Dictionary Operations
>>> stock = {’apples’: 430, ’bananas’: 312, ’oranges’: 525,
’pears’: 217}
>>> print(stock)
{’oranges’: 525, ’apples’: 430, ’pears’: 217, ’bananas’:
312}
 If someone buys all of the pears, we can remove the entry from the dictionary:
>>> del stock[’pears’]
>>> print(stock)
{’oranges’: 525, ’apples’: 430, ’bananas’: 312}
Dictionary Operations
>>> stock[’pears’] = 0
>>> print(stock)
{’oranges’: 525, ’apples’: 430, ’pears’: 0, ’bananas’:
312}
 The len function also works on dictionaries; it returns the number of
key- value pairs:
>>> len(stock)
4
Dictionary Methods
>>> eng2ml.keys()
[’one’, ’three’, ’two’]
>>> eng2ml.values()
[’Onnu’, ’Randu’, ’Moonnu’]
>>> eng2ml.items()
[(’one’,’Onnu’), (’three’,
’Randu’)] # List of tuples
’Moonnu’), (’two’,
Question
 Write a menu-driven program to perform all the operations in a dictionary
1. Insertion
2. Deletion
3. Updation
4. Searching
5. Display
 Write a Python program to create a dictionary that contains name of the
subjects in a course as keys and marks as values. Print the report card of
the student with marks of each subject and total marks.
 Fundamental package required for high performance scientific computing and data
analysis.
 This library consisting of multidimensional array objects and a collection of routines
for processing those arrays.
 Using NumPy, mathematical and logical operations on arrays can be performed.
 Using NumPy, a developer can perform the following operations:
 Mathematical and logical operations on arrays.
 Fourier transforms and routines for shape manipulation.
 Operations related to linear algebra. NumPy has in-built functions for
linear algebra and random number generation.
NumPy (Numerical Python)
 The most important object defined in NumPy is an N-dimensional array type called
ndarray.
 It describes the collection of items of the same type.
 Items in the collection can be accessed using a zero-based index.
 It is fast, flexible container for large data sets in Python.
 Every array has a shape (a tuple indicating the size of each dimension), and a dtype
(an object describing the data type of the array).
ndarray Object
pip install numpy
import numpy as np
 Use the array function np.array()
 This accepts any sequence-like object (including other arrays) and produces a new
NumPy array containing the passed data.
Creating ndarray
Creating ndarray
Creating ndarray
import numpy as np
a = np.array([1,2,3,4])
print(a) #[1,2,3,4]
b = np.array([(1,2,3),(4,5,6)], dtype =
float)
print(b) #[[1. 2. 3.]
[4. 5. 6.]]
c = np.array([(1,2,3),(4,5,6),(7,8,9)])
print(c) #[[1 2 3]
[4 5 6]
[7 8 9]]
 ndarray.ndim
 ndim represents the number of dimensions (axes).
 ndarray.shape
 a tuple of integers representing the size of the ndarray.
 ndarray.size
 the total number of elements in the ndarray. It is equal to the product of elements
of the shape.
 ndarray.dtype
 tells the data type of the elements of a NumPy array.
 ndarray.itemsize
 returns the size (in bytes) of each element.
ndarray Object - Attributes
ndarray Object - Attributes
import numpy as np
a = np.array([[[1,2,3],[4,3,5]],[[3,6,7],[2,1,0]]])
print("The dimension of array a is:" , a.ndim)
print("The size of the array a is: " , a.shape)
print("The total no: of elements in array a is: " , a.size)
print("The datatype of elements in array a is: " , a.dtype)
print("The size of each element in array a is: " , a.itemsize)
Output:
The dimension of array a is: 3
The size of the array a is: (2, 2, 3)
The total no: of elements in array a is: 12
The datatype of elements in array a is: int32
The size of each element in array a is: 4
1. using array()
2. using arange()
3. using linspace()
4. using zeros()
5. using ones()
Different ways of creating an Array
(1) Using array()
 Numpy arrays can be created very easily by passing a list to the
function numpy.array().
num_array = np.array([1,2,3,4)])
print(num_array)
(2) Using arange()
 The arange() function is one of the Numpy's most
used method for creating an end, step,
array within a specified range. Syntax: arange(start,
dtype)
 Among all of the arguments only end is mandatory and by default start=0 and
step=1.
Different ways of creating an Array
import numpy as np
a = np.arange(0,11,2)
print(a)
b =
np.arange(50,121,4)
print(b)
c = np.arange(15)
print(c)
Output:
[ 0 2 4 6 8 10]
[ 50 54 58 62 66 70 74
78 82 86 90 94 98 102
106 110 114 118]
Different ways of creating an Array
(3) Using linspace()
 With linspace() we can maintain a proper linear stepping or spacing
between array elements value while generating the array.
 linspace() function takes arguments: start index, end index and the
number of elements to be outputted.
 These number of elements would be linearly spaced in the range mentioned.
 Syntax:
linspace(start_index, end_index, num_of_elements)
Different ways of creating an Array
import numpy as np
a = np.linspace(15,75,10)
print(a)
b = np.linspace(1,10,10)
print(b)
Output:
[15. 21.66666667
68.33333333 75. ]
[1. 2. 3. 4. 5.
28.33333333 35. 41.66666667 48.33333333 55. 61.66666667
6. 7. 8. 9. 10.]
Different ways of creating an Array
(4) Using zeros(): returns a new array with zeros.
 Syntax: numpy.zeros(shape, dtype = float, order = 'C')
 shape: is the shape of the numpy zero array
 dtype: is the datatype in numpy zeros. It is optional. The default value is float64
 order: {‘C’, ‘F’}, optional, default: ‘C’. Whether to store data in row-major (C-
style) or column-major (F-style)
import numpy as np
a = np.zeros((2,2), dtype=int, ‘C’)
print(a) # [ [0 0]
[0 0]
]
Different ways of creating an Array
(5) Using ones(): used to create a matrix full of ones.
 Syntax: numpy.ones(shape, dtype = float, order = 'C’)
import numpy as np
a = np.zeros(shape = (2,3), order = 'C’ )
print(a) [ [0. 0. 0.]
[0. 0. 0.]
]
a=np.ones(shape=(3,3),dtype=int,order='C’)
print(a) [ [1 1 1]
[1 1 1]
[1 1 1 ] ]
Different ways of creating an Array
 The arithmetic operations with NumPy arrays perform element-wise operations.
 The operators are applied only between corresponding elements.
 Arithmetic operations are possible only if the array has the same structure
and dimensions.
Arithmetic Operations with NumPy Array
Basic operations: with scalars
import numpy as np import numpy as np Output:
a = np.array([1,2,3,4,5]) a = np.array([1,2,3,4,5])
b = a+1
print(b)
c = 2**a
print(c)
b = np.ones(5) + 1
c = a - b
print(c)
d =
(a*b)
print(d)
b[2 2 2 2 2]
[-1. 0. 1. 2. 3.]
[ 2. 4. 6. 8. 10.]
Output:
e = np.arange(5)
print(e)
[0 1 2 3 4]
[2 3 4 5 6]
[ 2 4 8 16 32]
1. NumPy add Function & add Operator:
• This function is used to add two arrays. If we add arrays having dissimilar
shapes, we get “Value Error”. We can also use the add operator “+” to
perform addition of two arrays.
2. NumPy subtract Function & subtract Operator:
• This function to output the difference of two arrays. If we subtract two arrays
having dissimilar shapes we get “Value Error”. We can also use the
subtract operator “-” to produce the difference of two arrays.
Functions and Operators to Perform Arithmetic
Operations
3. NumPy Multiply function & Multiply Operator:
• We use this function to output the multiplication of two arrays. We cannot
work with dissimilar arrays. We can also use the multiplication
operator “*” to get the product of two arrays.
4. NumPy Divide function & Divide Operator:
• We use this function to output the division of two arrays. We cannot divide
dissimilar arrays. We can also use the divide operator “/” to divide two arrays.
Functions and Operators to Perform Arithmetic Operations
Example
import numpy as np
a = np.array([7, 3, 4, 5, 1])
b = np.array([3, 4, 5, 6,
7]) print(a+b)
print(np.add(a, b))
print(" ")
print(a-b)
print(np.subtract(a, b))
print(" ")
print(np.multiply(a, b))
print(a*b)
print(" ")
print(np.divide(a, b))
print(a/b)
Output:
[10 7 9 11 8]
[10 7 9 11 8]
[ 4 -1 -1 -1 -6]
[ 4 -1 -1 -1 -6]
[21 12 20 30 7]
[21 12 20 30 7]
[2.33 0.75 0.8 0.83 0.14]
[2.33 0.75 0.8 0.83 0.14]
5. NumPy Mod and Remainder function:
• We use both the functions to output the remainder of the division of two arrays.
6. NumPy Power Function:
• This Function treats the first array as base and raises it to the
power of the elements of the second array.
7. NumPy Reciprocal Function:
• This Function returns the reciprocal of all the array elements.
Functions and Operators to Perform Arithmetic Operations
Example
import numpy as np
a = np.array([2, 10, 6, 5, 8])
b = np.array([3, 5, 2, 1, 7])
print(np.remainder(a, b))
print(np.mod(a, b))
print(" ")
print(np.power(a, b))
print("
")
print(np.reciprocal(a))
Output:
[2 0 0 0 1]
[2 0 0 0 1]
[ 8 100000 36 5 2097152]
[0 0 0 0 0]
 Comparing two NumPy arrays determines whether they are equivalent by checking if
every element at each corresponding index are the same.
 Use the == operator to compare two NumPy arrays to generate a new array object.
 Call ndarray.all() with the new array object as ndarray to return True if
the two NumPy arrays are equivalent.
Array Comparison
Example
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([1, 2, 3, 4])
print(“Element wise comparison: ")
print(a == b)
print("Result of whole comparison: ")
c = a == b
print(c.all())
OUTPUT
Element wisecomparison:
[True True True True]
Whole comparison:
True
 We can also use greater than, less than and equal to operators to compare.
To understand, have a look at the code below.
 Syntax : numpy.greater(x1, x2)
 Syntax : numpy.greater_equal(x1, x2)
 Syntax : numpy.less(x1, x2)
 Syntax : numpy.less_equal(x1, x2)
Array Comparison
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
Decomposition & Modularization
Breaking complex problems into more sub-problems that can be solved easily.
Problem Decomposition
Solving a complex problem may be difficult but finding the solution for every
sub-problem will be simple after which the sub-problems can be put
together for finding the full solution to the original problem.
It is a divide-and-conquer technique, something seen in various places outside
computing.
For Exampe: If you want to make a new game using computer programming
then, for making the game, you will write different functions for
different actions in the game and then those functions will act as the
subprograms or sub-tasks, after which these sub-tasks will be put together
to form a full game.
Problem Decomposition
Modularization, or modular programming, is a software design technique that
involves breaking a program into smaller, independent modules, each with its
own function.
What is a Module?
a module is a piece of software that has a specific functionality.
For example:
when building a game application, one module would be responsible for the
game logic, and another module would be responsible for drawing the
game on the screen.
Each module is a different file, which can be edited separately.
Modularization
 Modules in Python are simply Python files with a .py extension.
 The name of the module will be the name of the file.
 A Python module can have a set of functions, classes or variables defined and
implemented.
 Modules are imported from other modules using the import command.
Modularization
Easier to read: Each module deals with a single aspect of the
program's functionality, making it easier to understand the code.
Easier to test: Small functions are easier to test than large ones.
Easier to debug: When a bug occurs, it's easier to pinpoint the section of code
where the problem is happening.
Faster development: Developers can work on each module in parallel, saving
time.
Modules can be reused: Modules can be used in other applications, saving time
and money.
Motivation for Modularization
 Functions are self contained reusable programs or codes.
 It is a named sequence of statements that performs some useful operation.
 Functions may or may not take arguments and may or may not
produce a result.
 Functions are of two types:
 Built-in functions
 User defined functions
Defining and Using Functions
Built-in Functions
 Functions which does not require function definition.
 Definitions are already built-in.
 Examples are:
 int(), type(), id(), sin(), sqrt(), input(), etc.
 >>>type("32")
<type 'str'>
 >>>id(3)
134882108
 >>>int(3.5) #This is called Type
Conversion 3
Math Functions
(
(
Math Functions
 Some useful math functions in python are.
 math.log10(x) #log(x) is base 10
 math.sin(angle) #angle is in
radians
cos, tan, etc
are also available.
 For example:
>>> degrees = 45
>>> angle = degrees * 2 * math.pi / 360.0
>>> math.sin(angle)
0.707106781187
Math Functions
 math.sqrt(x)
 math.exp(x)
 math.pi
 Math.log(x) #log(x) is base e
 For example:
>>> math.sqrt(2) / 2.0
0.707106781187
User Defined Functions
 Functions that we define ourselves and use.
 We define a function using the def keyword.
 We call/invoke a function by using its name, parenthesis and arguments in an
expression.
 Syntax:
def NAME(LIST OF PARAMETERS):
STATEMENTS
User Defined Functions
 Example:
def message():
print (“Hello...”)
print(“We are S1 CSE students.“)
message()
print(“Welcome.”)
Output:
We are S1 CSE students.
Hello...
Welcome
Parameters and arguments
 Values that control how the function does its job.
 For example, Parameters
def add(x, y):
print(“Sum is: ”, x+y)
print(“Function Example.“)
add(10, 20)
Arguments
Parameters and arguments
 Variables and parameters are local.
• Variables created inside a function cannot be used outside
 For example:
def add(x, y):
c = x + y
a = 10, b = 20
add(a, b)
print(c)
Output:
NameError: name 'c' is not
defined
Functions with Return Values
 Functions with return values are otherwise known as fruitful functions.
import math
def area(radius):
temp = math.pi * radius**2
return temp
r = int(input(“Enter
radius: ”))
a = area(r)
print(“The area is:”, a)
Functions with Multiple Return Values
 Sometimes it is useful to have multiple return statements, one in each branch
of a conditional.
def absoluteValue(x):
if x < 0:
return -x
else:
return x
Code that appears after a return statement, or any other place the flow of execution can
never reach, is called dead code.
Questions
1. Program to check whether a given number is prime or not using a function.
2. Menu driven program to perform all arithmetic operations.
3. Menu driven Program to perform all list operations (traversal,
insertion, deletion, modification, search).
Recursive Functions
 It is legal for a function to call itself or same function.
– Otherwise called Circular definition
def countdown(n):
if n == 0:
print("Blastof
f!“)
else:
print(n)
countdown(n-1)
Recursive Functions
def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result
num = int(input(“Enter the number: ”))
fact = factorial(num)
print(“factorial is”, fact)
OR
return n*factorial(n-1)
Recursive Functions
To find the factorial of 3
Recursive Functions
 What happens if we call factorial and give it 1.5 as an argument?
>>> factorial (1.5)
RuntimeError: Maximum recursion depth exceeded
 Here the problem is that the values of n misses the base case.
• 1.5, 0.5, -0.5, -1.5, ....... Never become 0.
Recursive Functions
 Solution
def factorial (n):
if not isinstance(n, int):
print("Factorial is only defined for integers.“)
return -1
elif n < 0:
print("Factorial is only defined for positive integers.“)
return -1
elif n == 0:
return 1
else:
return n *
factorial
(n-1)
Questions
1. Program to find the sum of first n numbers using recursion.
2. Program to print Fibonacci numbers using recursion
3. Program to find nth Fibonacci number.

More Related Content

Similar to module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON (20)

PPTX
Python if_else_loop_Control_Flow_Statement
AbhishekGupta692777
 
PDF
gdscpython.pdf
workvishalkumarmahat
 
PPTX
Introduction to python programming ( part-3 )
Ziyauddin Shaik
 
PPT
python fundamental for beginner course .ppt
samuelmegerssa1
 
PDF
Python! An Introduction
Paul Bulkley-Logston
 
PPTX
Python Flow Control & use of functions.pptx
pandyahm47
 
PPT
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
RahulKumar812056
 
PPT
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
avishekpradhan24
 
PPTX
Python
MeHak Gulati
 
PDF
Introduction to python programming
Rakotoarison Louis Frederick
 
PDF
Slide 6_Control Structures.pdf
NuthalapatiSasidhar
 
PPTX
Introduction to python programming 1
Giovanni Della Lunga
 
PPTX
PYTHON PROGRAMMING
indupps
 
PPTX
Learn more about the concepts of Data Types in Python
PrathamKandari
 
PPTX
Lexture about strings, all examples and theoretical part is included
abzalbekulasbekov
 
PPTX
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
PPTX
module 2.pptx
mahendranaik18
 
PDF
Notes2
hccit
 
PDF
Python revision tour i
Mr. Vikram Singh Slathia
 
PPTX
Python basics
Hoang Nguyen
 
Python if_else_loop_Control_Flow_Statement
AbhishekGupta692777
 
gdscpython.pdf
workvishalkumarmahat
 
Introduction to python programming ( part-3 )
Ziyauddin Shaik
 
python fundamental for beginner course .ppt
samuelmegerssa1
 
Python! An Introduction
Paul Bulkley-Logston
 
Python Flow Control & use of functions.pptx
pandyahm47
 
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
RahulKumar812056
 
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
avishekpradhan24
 
Python
MeHak Gulati
 
Introduction to python programming
Rakotoarison Louis Frederick
 
Slide 6_Control Structures.pdf
NuthalapatiSasidhar
 
Introduction to python programming 1
Giovanni Della Lunga
 
PYTHON PROGRAMMING
indupps
 
Learn more about the concepts of Data Types in Python
PrathamKandari
 
Lexture about strings, all examples and theoretical part is included
abzalbekulasbekov
 
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
module 2.pptx
mahendranaik18
 
Notes2
hccit
 
Python revision tour i
Mr. Vikram Singh Slathia
 
Python basics
Hoang Nguyen
 

Recently uploaded (20)

PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PDF
Electrical Engineer operation Supervisor
ssaruntatapower143
 
PPT
Electrical Safety Presentation for Basics Learning
AliJaved79382
 
PPTX
Introduction to Basic Renewable Energy.pptx
examcoordinatormesu
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PPTX
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
PPTX
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PPTX
Thermal runway and thermal stability.pptx
godow93766
 
PPTX
MATLAB : Introduction , Features , Display Windows, Syntax, Operators, Graph...
Amity University, Patna
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PPTX
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PDF
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
Electrical Engineer operation Supervisor
ssaruntatapower143
 
Electrical Safety Presentation for Basics Learning
AliJaved79382
 
Introduction to Basic Renewable Energy.pptx
examcoordinatormesu
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
Knowledge Representation : Semantic Networks
Amity University, Patna
 
Thermal runway and thermal stability.pptx
godow93766
 
MATLAB : Introduction , Features , Display Windows, Syntax, Operators, Graph...
Amity University, Patna
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
Ad

module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON

  • 1. Module 3 SELECTION AND ITERATION USING PYTHON
  • 2. Syllabus SELECTION AND ITERATION USING PYTHON:- if-else, elif, for loop, range, while loop. Sequence data types in Python - list, tuple, set, strings, dictionary, Creating and using Arrays in Python (using Numpy library). DECOMPOSITION AND MODULARIZATION :- Problem decomposition as a strategy for solving complex problems, Modularization, Motivation for modularization, Defining and using functions in Python, Functions with multiple return values. RECURSION:- Recursion Defined, Reasons for using Recursion, The Call Stack, Recursion and the Stack, Avoiding Circularity in Recursion, Sample problems - Finding the nth Fibonacci number, greatest common divisor of two positive integers, the factorial of a positive integer, adding two positive integers, the sum of digits of a positive number.
  • 3. if Statement  To check conditions and change the behavior of the program accordingly. if x > 0: print("x is positive”) • General Synatax: if Condition: FIRST STATEMENT ... LAST STATEMENT
  • 4.  The first unintended statement marks the end of the block.  A statement block inside a compound statement is called the body of the statement.  If there is no statements in the block, then use the pass statement, which does nothing. if Statement
  • 5.  A second form of the if statement is alternative execution, in which there are two possibilities and the condition determines which one gets executed.  The syntax looks like this: if x%2 == 0: print(x, "is even“) else: print(x, "is odd”) The alternatives are called branches. if…else Statement
  • 6.  Sometimes there are more than two possibilities and we need more than two branches. if x < y: print(x, "is less than", y) elif x > y: #abbreviation of else if print(x, "is greater than", y) else: print(x, "and", y, “are equal”) elif Statement
  • 7. Nested Conditionals  One conditional can also be nested within another. if x == y: print(x, "and", y, “are equal”) else: if x < y: print(x, "is less than", y) else: print(x, "is greater than", y)
  • 8. Example Questions 1. Write a program to check whether a candidate is eligible to vote or not (Based on his age). 2. Write a program to find the largest of three numbers using logical operator and without using logical operator. 3. Write a menu driven program to perform different mathematical operations. 4. Write a program to print the grade of a student based on the total marks obtained from 3 subjects. Consider 10 marks for each subject (26 - 30: Grade A, 21 – 25: Grade B, 16 – 20: Grade C, <=15: F).
  • 9. The while Statement  For repeating or looping identical tasks. n = 10 while n > 0: print(n) n = n-1 print("Blastof f!“)
  • 10. The while Statement  Here is the flow of execution for a while statement. 1. Evaluate the condition, yielding 0 or 1. 2. If the condition is false (0), exit the while statement and continue execution at the next statement. 3. If the condition is true (1), execute each of the statements in the body and then go back to step 1.
  • 11. Example Questions 1. Write a program to print the sum of first ‘n’ numbers. 2. Write a program to print a multiplication table for a given number. 3. Write a program to print the odd numbers between two limits. 4. Write a program to check whether the given number is Armstrong number or not. 5. Write a program to reverse the given number. 6. Write a program to check whether the given number is palindrome or not.
  • 12. Nested Loop  We can have a loop statement inside another loop. Syntax: while expression: statement(s) while expression: statement(s) statement(s)
  • 13. Nested Loop  Example: To print the pattern 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
  • 14. Nested Loop  Answer: To print the pattern n = int(input("Enter the number of rows")) i = 1 j = 1 while i <= n: j = 1 while j <= i: print(j, ' ', end=' ') j += 1 print( ) i += 1
  • 15. Definite Loops - 'for'  Definite loops iterate through the members of a set. num = int(input("Enter the limit: ")) sum = 0 for i in range(1, num + 1): #creates a list sum = sum + i print(sum)
  • 16. Example Questions 1. Write a program to print the sum of squares of first ‘n’ numbers. 2. Write a program to print the Fibonacci series up to a given limit. 3. Write a program to check whether the given number is a prime number or not. 4. Program to print all prime numbers up to a given limit.
  • 17.  The else keyword in a for loop specifies a block of code to be executed when the loop is finished:  Print all numbers from 0 to 5, and print a message when the loop has ended for x in range(6): print(x) else: print("Finally finished!") for…else Statement
  • 18.  To check whether a given number is prime or not: num = int(input("Enter the num: ")) for i in range(2, (num//2)+1): if num % i == 0: print("It is not prime") break else: print("Prime") for…else Statement - Example
  • 19.  The else keyword in a while loop specifies a block of code to be executed when the loop is finished:  Example i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than while…else Statement
  • 20. The 'break' Statement while True: line = input("Enter: ") if line == 'done': break print(line) print 'Good Bye........'
  • 21. The 'continue' Statement while True: line = input("Enter: ") if line == '#': continue if line == 'done': break print (line) print ('Good Bye........‘)
  • 23. Strings  Made up of smaller pieces of characters – Compound Data Types  For example, >>> fruit = "banana" >>> letter = fruit[1] >>> print(letter) a  The expression in brackets is called an index, which can be any integer expression.  Index always starts from zero.
  • 24. String Length  The len function returns the number of characters in a string >>> fruit = "banana" >>> len(fruit) 6  To get the last letter of a string, length = len(fruit) last = fruit[length-1] Or fruit[-1]
  • 25. Traversal & for Loop  Processing a string one character at a time. index = 0 while index < len(fruit): letter = fruit[index] print(letter) index = index + 1 for char in fruit: print(char)
  • 26. Predict the Output prefixes = "JKLMNOPQ" suffix = "ack" for letter in prefixes: print(letter + suffix)
  • 27. String Slices  A segment of a string is called a slice.  For example: >>> s = "Peter, Paul, and Mary" >>> print(s[0:5]) Peter >>> print(s[7:11]) Paul >>> print(s[17:21]) Mary
  • 28. String Slices  If you omit the first index (before the colon), the slice starts at the beginning of the string.  If you omit the second index, the slice goes to the end of the string. >>> fruit = "banana" >>> fruit[:3] ’ban’ >>> fruit[3:] ’ana’  What do you think s[:] means?
  • 29. String Comparison  The comparison operators (==, <, >) work on strings also. word = “Zebra” if word < "banana": print(word+” comes before banana.”) elif word > "banana": print(word+” comes after banana.”) if word == “banana”: print(“Same...”)  All the uppercase letters come before all the lowercase letters.
  • 30. Strings are Immutable  Strings are immutable, which means we can’t change an existing string. greeting = "Hello, world!" greeting[0] = ’J’ # ERROR! print(greeting) Solution greeting = "Hello, world!" newGreeting = ’J’ + greeting[1:] print(newGreeting)
  • 31. Looping and Counting in a String fruit = "banana" count = 0 for char in fruit: if char == ’a’: count = count + 1 print(count) The above program counts the occurrences of a particular character in a given string.
  • 32. The string module  Python String module contains some constants, utility function, and classes for string manipulation.  It’s a built-in module and we have to import it before using any of its constants and classes. >>> import string
  • 33. String Module Constants import string print(string.ascii_letters) #abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.ascii_lowercas e) #abcdefghijklmnopqrstuvwxyz print(string.ascii_uppercas e) #ABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.digits) #0123456789 print(string.hexdigits) #0123456789abcdefABCDEF print(string.whitespace) # ' tnrx0bx0c' print(string.punctuation) #!"#$%&'()*+,-./:;?@[]^_`{|}~
  • 34. Python String Methods  All string methods returns new values. They do not change the original string. Method Description find() or index() Searches the string for a specified value and returns the index count() Returns the number of times a specified value occurs in a string startswith() Returns true if the string starts with the specified value endswith() Returns true if the string ends with the specified value
  • 35. Python String Methods isalnum() Returns True if all characters in the string are alphanumeric (Eg:- “hello123”) isalpha() Returns True if all characters in the string are in the alphabet (Eg:- “hello”) isdecimal() Returns True if all characters in the string are decimals (Eg:- 2, 10, 14, etc.) isdigit() Returns True if all characters in the string are digits (Eg:- “1234”) islower() Returns True if all characters in the string are lower case (Eg:- “hello”)
  • 36. Python String Methods isnumeric() Returns True if all characters in the string are numeric (Eg:- 2, 10, 14, etc.) isupper() Returns True if all characters in the string are upper case (Eg:- “HELLO”) lower() Converts a string into lower case (“HELLO”.lower()) upper() Converts a string into upper case (“hello”.upper())
  • 37. Using 'in' as Operator  The in keyword is used to check to see if one string is in another string.  It returns True or False and can be used with if statement. >>> fruit = “banana” >>> 'nan' in fruit True >>> 'man' in fruit False
  • 38. String Questions 1. Write a program to search a substring in a string. If yes, print the position index. (Hint: use find function) 2. Write a program to replace a substring with another string. (Hint: use replace function ) str.replace(“xyz”, “abc”), xyz will be replaced by abc 3. Write a program to delete a substring from a string. (Hint: use replace function) str.replace(“xyz”, “”), xyz will be replaced by “”. 4. Write a program to check whether a given string is palindrome or not. (“malayalam”). 5. Write a program to check whether a given string is symmetrical or not. (“khelokhelo”).
  • 39. Lists  Lists are used to store multiple items in a single variable.  Lists are created using square brackets. thislist = ["apple", "banana", "cherry"] print(thislist)  List items are ordered, changeable, and allow duplicate values.  List items are indexed, the first item has index [0], the second item has index [1] etc.  To create an empty list e = []
  • 40. The range Function  Lists that contain consecutive integers are common, so Python provides a simple way to create them: >>> range(1, 5) [1, 2, 3, 4] >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1, 10, 2) [1, 3, 5, 7, 9]
  • 41. Accessing Elements  List items are indexed and you can access them by referring to the index number: >>> numbers = [2, 4, 8, 20] >>> print(numbers[2]) 8  If an index has a negative value, it counts backward from the end of the list. >>> numbers[-3] 4
  • 42. Accessing Elements sem = ["S1", "S3", "S5", "S7"] i = 0 while i < 4: print(sem[i]) i = i + 1
  • 43. List Length  The function len returns the length of a list. sem = ["S1", "S3", "S5", "S7"] i = 0 while i < len(sem): print(sem[i]) i = i + 1 What will be the output of len function for the following list? [’s3’, 1, [’COLLEGE’,
  • 44. List Membership  The in keyword is used to check the membership of an element in list.  It returns True or False values. >>> sem = ["S1", "S3", "S5", "S7"] >>> 'S1' in sem True >>> 'S2' not in sem True
  • 45. Questions 1. Write a program to search an element in a list. 2. Write a program to swap the first and last elements of a list.
  • 46. List & for Loop sem = ["S1", "S3", "S5", "S7"] for s in sem: print(s)  Predict the output for num in range(20): if num % 2 == 0: print(number)
  • 47. List Operations  The + operator concatenates lists. a = [1, 2, 3] b = [4, 5, 6] c = a + b print(c) [1, 2, 3, 4, 5, 6]
  • 48. List Operations  The * operator repeats a list a given number of times. [0] * 4 [0, 0, 0, 0] [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
  • 49. List Slices  Same as string. >>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’] >>> list[1:3] [’b’, ’c’] >>> list[:4] [’a’, ’b’, ’c’, ’d’] >>> list[3:] [’d’, ’e’, ’f’] >>> list[:] [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
  • 50. Lists are Mutable  Unlike strings, lists are mutable, which means we can change their elements. >>> fruit = ["banana", "apple", "quince"] >>> fruit[0] = "pear" >>> fruit[-1] = "orange" >>> print(fruit) [’pear’, ’apple’, ’orange’]
  • 51. Lists are Mutable  With the slice operator we can update several elements at once. >>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’] >>> list[1:3] = [’x’, ’y’] >>> print(list) [’a’, ’x’, ’y’, ’d’, ’e’, ’f’]
  • 52. Lists are Mutable  We can also remove elements from a list by assigning the empty list to them. >>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’] >>> list[1:3] = [] >>> print(list) [’a’, ’d’, ’e’, ’f’]
  • 53. Lists Deletion  Using slices to delete list elements is error-prone.  del method removes an element from a list >>> a = [’one’, ’two’, ’three’] >>> del a[1] >>> print(a) # [’one’, ’three’] >>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’] >>> del list[1:5] >>> print(list) # [’a’, ’f’]
  • 54. Lists Functions >>> x = [1, 2, 3, 4] >>> x.append(5) # [1, 2, 3, 4, 5] >>> z = [4, 5, 6, 7] >>> x.extend(z) #[1, 2, 3, 4, 5, 4, 5, 6, 7] >>> x.count(4) # 2 >>> x.index(5) # 4 >>> x.pop() # 7 [1, 2, 3, 4, 5, 4, 5, 6] >>> x.remove(4) # [1, 2, 3, 5, 4, 5, 6] >>> x.insert(1, 8) # [1, 8, 2, 3, 5, 4, 5, 6] >>> x.reverse() # [6, 5, 4, 5, 3, 2, 8, 1] >>> x.sort() # [1, 2, 3, 4, 5, 5, 6, 8] >>> x.sort(reverse = True) # [8, 6, 5, 5, 4, 3, 2, 1]
  • 55. Questions 1. Write a program to find the smallest element in a list. 2. Write a Python program to print all the odd numbers and even numbers in a list separately. 3. Write a program to list the common elements in two lists. 4. Write a program to rotate a given list. 5. Write a program to remove all vowels from a given string.
  • 56. Tuples Similar to a list except that it is immutable – Comma separated values. For example, >>> tuple = ’a’, ’b’, ’c’, ’d’, ’e’ Or >>> tuple = (’a’, ’b’, ’c’, ’d’, ’e’) To create a tuple with a single element, we have to include the final comma: >>> t1 = (’a’,)
  • 57. Tuples The operations on tuples are the same as the operations on lists. >>> tuple = (’a’, ’b’, ’c’, ’d’, ’e’) >>> tuple[0] ’a’ And the slice operator selects a range of elements. >>> tuple[1:3] (’b’, ’c’) >>> tuple[0] = ’A’ TypeError: object doesn’t support item assignment
  • 58. Tuple Assignment To swap two variables a and b. >>> temp = a >>> a = b >>> b = temp  Python provides an easy way to do this. >>> a, b = b, a  The left side is a tuple of variables; the right side is a tuple of values.
  • 59. Set Set items can be of any data type or can contain different data types: String, int and Boolean data types. Example: set1 = {"apple", "banana", "cherry"} set2 = {1, 5, 7, 9, 3} set3 = {True, False, False} set4 = {"abc", 34, True, 40, "male"}
  • 60. The set() Constructor The set() constructor is used to make a set Example: set1 = set(("apple","banana“,"cherry")) print(set1) O/P: {“apple","banana“,"cherry”}
  • 61. Access Set Items You cannot access items in a set by referring to an index. You can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword. Example: set1 = {"apple", "banana", "cherry"} for x in set1: print(x)
  • 62. Add Set Items Once a set is created, you cannot change its items, but you can add new items. To add one item to a set, use the add() method. set1 = {"apple", "banana", "cherry"} set1.add("orange") To add items from another set into the current set, use the update() method. set1 = {"apple", "banana", "cherry"} t = {"pineapple", "mango", "papaya"} set1.update(t)
  • 63. Add Set Items The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.). set1 = {"apple", "banana", "cherry"} mylist = ["kiwi", "orange"] set1.update(mylist) print(set1) O/P: {'banana', 'cherry', 'apple', 'orange', 'kiwi'}
  • 64. Remove Set Items To remove an item in a set, use the remove(), or the discard() method. If theitemto remove does not exist, remove() will raise an error. discard() will NOT raise an error. set1 = {"apple", "banana", "cherry"} set1.remove("banana") print(thisset) # {'apple', 'cherry'}
  • 65. Remove Set Items You can also use the pop() method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed. The return value of the pop() method is the removed item. set1 = {"apple", "banana", "cherry"} x = set1.pop() print(x) print(set1) # banana # {'apple', 'cherry'}
  • 66. Remove Set Items The clear() method empties the set. The del keyword will delete the set completely: set1 = {"apple", "banana", "cherry"} set1.clear() print(set1) # set() set1 = {"apple", "banana", "cherry"} del set1 print(set1) # this will raise an error because the set no longer exists
  • 67. Join Sets There are several ways to join two or more sets in Python. You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another. Both union() and update() will exclude any duplicate items. set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set3 = set1.union(set2) print(set3) O/P: {2, 'b', 'c', 3, 1, 'a'}
  • 68. Join Sets The intersection_update() method will keep only the items that are present in both sets. x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.intersection_update(y) print(x) O/P: {'apple'}
  • 69. Join Sets The intersection() method will return a new set, that only contains the items that are present in both sets. x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.intersection(y) print(z) O/P: {'apple'}
  • 70. Join Sets The symmetric_difference_update() method will keep only the elements that are NOT present in both sets. x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.symmetric_difference_update(y) print(x) O/P: {'google', 'banana', 'microsoft', 'cherry'}
  • 71. Join Sets The symmetric_difference() method will return a new set, that contains only the elements that are NOT present in both sets. x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.symmetric_difference(y) print(x) O/P: {'google', 'banana', 'microsoft', 'cherry'}
  • 72. Dictionaries Dictionaries are similar to other compound types except that they can use any immutable type as an index. >>> eng2ml = {} >>> eng2ml[’one’] = ’Onnu’ >>> eng2ml[’two’] = ’Randu’ >>> print (eng2ml) {’one’: ’Onnu’, ’two’: ’Randu’} Ina dictionary, the indices are called keys, so the elements are called key- value pairs.
  • 73. Dictionaries  Or we can create a dictionary like: >>> eng2ml = {’one’: ’Onnu’, ’Moonnu’} ’two’: ’Randu’, ’three’:  If we print the value of eng2ml again, we get a surprise: >>> print (eng2ml) {’one’: ’Onnu’, ’three’: ’Moonnu’, ’two’: ’Randu’} # Not in order >>> print (eng2ml[’two’]) ’Randu’
  • 74. Dictionary Operations >>> stock = {’apples’: 430, ’bananas’: 312, ’oranges’: 525, ’pears’: 217} >>> print(stock) {’oranges’: 525, ’apples’: 430, ’pears’: 217, ’bananas’: 312}  If someone buys all of the pears, we can remove the entry from the dictionary: >>> del stock[’pears’] >>> print(stock) {’oranges’: 525, ’apples’: 430, ’bananas’: 312}
  • 75. Dictionary Operations >>> stock[’pears’] = 0 >>> print(stock) {’oranges’: 525, ’apples’: 430, ’pears’: 0, ’bananas’: 312}  The len function also works on dictionaries; it returns the number of key- value pairs: >>> len(stock) 4
  • 76. Dictionary Methods >>> eng2ml.keys() [’one’, ’three’, ’two’] >>> eng2ml.values() [’Onnu’, ’Randu’, ’Moonnu’] >>> eng2ml.items() [(’one’,’Onnu’), (’three’, ’Randu’)] # List of tuples ’Moonnu’), (’two’,
  • 77. Question  Write a menu-driven program to perform all the operations in a dictionary 1. Insertion 2. Deletion 3. Updation 4. Searching 5. Display  Write a Python program to create a dictionary that contains name of the subjects in a course as keys and marks as values. Print the report card of the student with marks of each subject and total marks.
  • 78.  Fundamental package required for high performance scientific computing and data analysis.  This library consisting of multidimensional array objects and a collection of routines for processing those arrays.  Using NumPy, mathematical and logical operations on arrays can be performed.  Using NumPy, a developer can perform the following operations:  Mathematical and logical operations on arrays.  Fourier transforms and routines for shape manipulation.  Operations related to linear algebra. NumPy has in-built functions for linear algebra and random number generation. NumPy (Numerical Python)
  • 79.  The most important object defined in NumPy is an N-dimensional array type called ndarray.  It describes the collection of items of the same type.  Items in the collection can be accessed using a zero-based index.  It is fast, flexible container for large data sets in Python.  Every array has a shape (a tuple indicating the size of each dimension), and a dtype (an object describing the data type of the array). ndarray Object
  • 80. pip install numpy import numpy as np  Use the array function np.array()  This accepts any sequence-like object (including other arrays) and produces a new NumPy array containing the passed data. Creating ndarray
  • 82. Creating ndarray import numpy as np a = np.array([1,2,3,4]) print(a) #[1,2,3,4] b = np.array([(1,2,3),(4,5,6)], dtype = float) print(b) #[[1. 2. 3.] [4. 5. 6.]] c = np.array([(1,2,3),(4,5,6),(7,8,9)]) print(c) #[[1 2 3] [4 5 6] [7 8 9]]
  • 83.  ndarray.ndim  ndim represents the number of dimensions (axes).  ndarray.shape  a tuple of integers representing the size of the ndarray.  ndarray.size  the total number of elements in the ndarray. It is equal to the product of elements of the shape.  ndarray.dtype  tells the data type of the elements of a NumPy array.  ndarray.itemsize  returns the size (in bytes) of each element. ndarray Object - Attributes
  • 84. ndarray Object - Attributes import numpy as np a = np.array([[[1,2,3],[4,3,5]],[[3,6,7],[2,1,0]]]) print("The dimension of array a is:" , a.ndim) print("The size of the array a is: " , a.shape) print("The total no: of elements in array a is: " , a.size) print("The datatype of elements in array a is: " , a.dtype) print("The size of each element in array a is: " , a.itemsize) Output: The dimension of array a is: 3 The size of the array a is: (2, 2, 3) The total no: of elements in array a is: 12 The datatype of elements in array a is: int32 The size of each element in array a is: 4
  • 85. 1. using array() 2. using arange() 3. using linspace() 4. using zeros() 5. using ones() Different ways of creating an Array
  • 86. (1) Using array()  Numpy arrays can be created very easily by passing a list to the function numpy.array(). num_array = np.array([1,2,3,4)]) print(num_array) (2) Using arange()  The arange() function is one of the Numpy's most used method for creating an end, step, array within a specified range. Syntax: arange(start, dtype)  Among all of the arguments only end is mandatory and by default start=0 and step=1. Different ways of creating an Array
  • 87. import numpy as np a = np.arange(0,11,2) print(a) b = np.arange(50,121,4) print(b) c = np.arange(15) print(c) Output: [ 0 2 4 6 8 10] [ 50 54 58 62 66 70 74 78 82 86 90 94 98 102 106 110 114 118] Different ways of creating an Array
  • 88. (3) Using linspace()  With linspace() we can maintain a proper linear stepping or spacing between array elements value while generating the array.  linspace() function takes arguments: start index, end index and the number of elements to be outputted.  These number of elements would be linearly spaced in the range mentioned.  Syntax: linspace(start_index, end_index, num_of_elements) Different ways of creating an Array
  • 89. import numpy as np a = np.linspace(15,75,10) print(a) b = np.linspace(1,10,10) print(b) Output: [15. 21.66666667 68.33333333 75. ] [1. 2. 3. 4. 5. 28.33333333 35. 41.66666667 48.33333333 55. 61.66666667 6. 7. 8. 9. 10.] Different ways of creating an Array
  • 90. (4) Using zeros(): returns a new array with zeros.  Syntax: numpy.zeros(shape, dtype = float, order = 'C')  shape: is the shape of the numpy zero array  dtype: is the datatype in numpy zeros. It is optional. The default value is float64  order: {‘C’, ‘F’}, optional, default: ‘C’. Whether to store data in row-major (C- style) or column-major (F-style) import numpy as np a = np.zeros((2,2), dtype=int, ‘C’) print(a) # [ [0 0] [0 0] ] Different ways of creating an Array
  • 91. (5) Using ones(): used to create a matrix full of ones.  Syntax: numpy.ones(shape, dtype = float, order = 'C’) import numpy as np a = np.zeros(shape = (2,3), order = 'C’ ) print(a) [ [0. 0. 0.] [0. 0. 0.] ] a=np.ones(shape=(3,3),dtype=int,order='C’) print(a) [ [1 1 1] [1 1 1] [1 1 1 ] ] Different ways of creating an Array
  • 92.  The arithmetic operations with NumPy arrays perform element-wise operations.  The operators are applied only between corresponding elements.  Arithmetic operations are possible only if the array has the same structure and dimensions. Arithmetic Operations with NumPy Array
  • 93. Basic operations: with scalars import numpy as np import numpy as np Output: a = np.array([1,2,3,4,5]) a = np.array([1,2,3,4,5]) b = a+1 print(b) c = 2**a print(c) b = np.ones(5) + 1 c = a - b print(c) d = (a*b) print(d) b[2 2 2 2 2] [-1. 0. 1. 2. 3.] [ 2. 4. 6. 8. 10.] Output: e = np.arange(5) print(e) [0 1 2 3 4] [2 3 4 5 6] [ 2 4 8 16 32]
  • 94. 1. NumPy add Function & add Operator: • This function is used to add two arrays. If we add arrays having dissimilar shapes, we get “Value Error”. We can also use the add operator “+” to perform addition of two arrays. 2. NumPy subtract Function & subtract Operator: • This function to output the difference of two arrays. If we subtract two arrays having dissimilar shapes we get “Value Error”. We can also use the subtract operator “-” to produce the difference of two arrays. Functions and Operators to Perform Arithmetic Operations
  • 95. 3. NumPy Multiply function & Multiply Operator: • We use this function to output the multiplication of two arrays. We cannot work with dissimilar arrays. We can also use the multiplication operator “*” to get the product of two arrays. 4. NumPy Divide function & Divide Operator: • We use this function to output the division of two arrays. We cannot divide dissimilar arrays. We can also use the divide operator “/” to divide two arrays. Functions and Operators to Perform Arithmetic Operations
  • 96. Example import numpy as np a = np.array([7, 3, 4, 5, 1]) b = np.array([3, 4, 5, 6, 7]) print(a+b) print(np.add(a, b)) print(" ") print(a-b) print(np.subtract(a, b)) print(" ") print(np.multiply(a, b)) print(a*b) print(" ") print(np.divide(a, b)) print(a/b) Output: [10 7 9 11 8] [10 7 9 11 8] [ 4 -1 -1 -1 -6] [ 4 -1 -1 -1 -6] [21 12 20 30 7] [21 12 20 30 7] [2.33 0.75 0.8 0.83 0.14] [2.33 0.75 0.8 0.83 0.14]
  • 97. 5. NumPy Mod and Remainder function: • We use both the functions to output the remainder of the division of two arrays. 6. NumPy Power Function: • This Function treats the first array as base and raises it to the power of the elements of the second array. 7. NumPy Reciprocal Function: • This Function returns the reciprocal of all the array elements. Functions and Operators to Perform Arithmetic Operations
  • 98. Example import numpy as np a = np.array([2, 10, 6, 5, 8]) b = np.array([3, 5, 2, 1, 7]) print(np.remainder(a, b)) print(np.mod(a, b)) print(" ") print(np.power(a, b)) print(" ") print(np.reciprocal(a)) Output: [2 0 0 0 1] [2 0 0 0 1] [ 8 100000 36 5 2097152] [0 0 0 0 0]
  • 99.  Comparing two NumPy arrays determines whether they are equivalent by checking if every element at each corresponding index are the same.  Use the == operator to compare two NumPy arrays to generate a new array object.  Call ndarray.all() with the new array object as ndarray to return True if the two NumPy arrays are equivalent. Array Comparison
  • 100. Example import numpy as np a = np.array([1, 2, 3, 4]) b = np.array([1, 2, 3, 4]) print(“Element wise comparison: ") print(a == b) print("Result of whole comparison: ") c = a == b print(c.all()) OUTPUT Element wisecomparison: [True True True True] Whole comparison: True
  • 101.  We can also use greater than, less than and equal to operators to compare. To understand, have a look at the code below.  Syntax : numpy.greater(x1, x2)  Syntax : numpy.greater_equal(x1, x2)  Syntax : numpy.less(x1, x2)  Syntax : numpy.less_equal(x1, x2) Array Comparison
  • 106. Breaking complex problems into more sub-problems that can be solved easily. Problem Decomposition
  • 107. Solving a complex problem may be difficult but finding the solution for every sub-problem will be simple after which the sub-problems can be put together for finding the full solution to the original problem. It is a divide-and-conquer technique, something seen in various places outside computing. For Exampe: If you want to make a new game using computer programming then, for making the game, you will write different functions for different actions in the game and then those functions will act as the subprograms or sub-tasks, after which these sub-tasks will be put together to form a full game. Problem Decomposition
  • 108. Modularization, or modular programming, is a software design technique that involves breaking a program into smaller, independent modules, each with its own function. What is a Module? a module is a piece of software that has a specific functionality. For example: when building a game application, one module would be responsible for the game logic, and another module would be responsible for drawing the game on the screen. Each module is a different file, which can be edited separately. Modularization
  • 109.  Modules in Python are simply Python files with a .py extension.  The name of the module will be the name of the file.  A Python module can have a set of functions, classes or variables defined and implemented.  Modules are imported from other modules using the import command. Modularization
  • 110. Easier to read: Each module deals with a single aspect of the program's functionality, making it easier to understand the code. Easier to test: Small functions are easier to test than large ones. Easier to debug: When a bug occurs, it's easier to pinpoint the section of code where the problem is happening. Faster development: Developers can work on each module in parallel, saving time. Modules can be reused: Modules can be used in other applications, saving time and money. Motivation for Modularization
  • 111.  Functions are self contained reusable programs or codes.  It is a named sequence of statements that performs some useful operation.  Functions may or may not take arguments and may or may not produce a result.  Functions are of two types:  Built-in functions  User defined functions Defining and Using Functions
  • 112. Built-in Functions  Functions which does not require function definition.  Definitions are already built-in.  Examples are:  int(), type(), id(), sin(), sqrt(), input(), etc.  >>>type("32") <type 'str'>  >>>id(3) 134882108  >>>int(3.5) #This is called Type Conversion 3
  • 114. Math Functions  Some useful math functions in python are.  math.log10(x) #log(x) is base 10  math.sin(angle) #angle is in radians cos, tan, etc are also available.  For example: >>> degrees = 45 >>> angle = degrees * 2 * math.pi / 360.0 >>> math.sin(angle) 0.707106781187
  • 115. Math Functions  math.sqrt(x)  math.exp(x)  math.pi  Math.log(x) #log(x) is base e  For example: >>> math.sqrt(2) / 2.0 0.707106781187
  • 116. User Defined Functions  Functions that we define ourselves and use.  We define a function using the def keyword.  We call/invoke a function by using its name, parenthesis and arguments in an expression.  Syntax: def NAME(LIST OF PARAMETERS): STATEMENTS
  • 117. User Defined Functions  Example: def message(): print (“Hello...”) print(“We are S1 CSE students.“) message() print(“Welcome.”) Output: We are S1 CSE students. Hello... Welcome
  • 118. Parameters and arguments  Values that control how the function does its job.  For example, Parameters def add(x, y): print(“Sum is: ”, x+y) print(“Function Example.“) add(10, 20) Arguments
  • 119. Parameters and arguments  Variables and parameters are local. • Variables created inside a function cannot be used outside  For example: def add(x, y): c = x + y a = 10, b = 20 add(a, b) print(c) Output: NameError: name 'c' is not defined
  • 120. Functions with Return Values  Functions with return values are otherwise known as fruitful functions. import math def area(radius): temp = math.pi * radius**2 return temp r = int(input(“Enter radius: ”)) a = area(r) print(“The area is:”, a)
  • 121. Functions with Multiple Return Values  Sometimes it is useful to have multiple return statements, one in each branch of a conditional. def absoluteValue(x): if x < 0: return -x else: return x Code that appears after a return statement, or any other place the flow of execution can never reach, is called dead code.
  • 122. Questions 1. Program to check whether a given number is prime or not using a function. 2. Menu driven program to perform all arithmetic operations. 3. Menu driven Program to perform all list operations (traversal, insertion, deletion, modification, search).
  • 123. Recursive Functions  It is legal for a function to call itself or same function. – Otherwise called Circular definition def countdown(n): if n == 0: print("Blastof f!“) else: print(n) countdown(n-1)
  • 124. Recursive Functions def factorial(n): if n == 0: return 1 else: recurse = factorial(n-1) result = n * recurse return result num = int(input(“Enter the number: ”)) fact = factorial(num) print(“factorial is”, fact) OR return n*factorial(n-1)
  • 125. Recursive Functions To find the factorial of 3
  • 126. Recursive Functions  What happens if we call factorial and give it 1.5 as an argument? >>> factorial (1.5) RuntimeError: Maximum recursion depth exceeded  Here the problem is that the values of n misses the base case. • 1.5, 0.5, -0.5, -1.5, ....... Never become 0.
  • 127. Recursive Functions  Solution def factorial (n): if not isinstance(n, int): print("Factorial is only defined for integers.“) return -1 elif n < 0: print("Factorial is only defined for positive integers.“) return -1 elif n == 0: return 1 else: return n * factorial (n-1)
  • 128. Questions 1. Program to find the sum of first n numbers using recursion. 2. Program to print Fibonacci numbers using recursion 3. Program to find nth Fibonacci number.