Unit 3
Unit 3
Transfer statements
1. break
2. continue
3. pass
Fruitful Function
1. Return values
2. Parameters
3. Local and global scope
4. Function composition
5. Recursion
String
1. String Slices
2. Immutability
3. String functions
4. Methods
5. String module
List as array
Illustrative problem Square root, gcd, exponentiation
,sum an array of number, Linear search, Binary search.
Boolean values:
• Boolean data types have two values.
>>> type(True)
They are 0 and 1. <type 'bool'>
• 0 represents False >>> type(False)
<type 'bool'>
• 1 represents True >>> 3==5
False
• True and False are keywords. >>> 6==6
True
operator ==, which compares two >>> True+True
operands 2
>>> False+True
1
>>> False*True
0
Operator :(refer unit-2)
• Logical operators in Python are used for
conditional statements are true or false.
• Logical operators in Python are AND, OR and
NOT.
• For logical operators following condition are
applied.
• For AND operator – It returns TRUE if both
the operands (right side and left side) are true
• For OR operator- It returns TRUE if either of
the operand (right side or left side) is true
• For NOT operator- returns TRUE if operand
is false
Control flow
CONDITIONAL (IF): Conditional Execution
• Condition part is true, one part of the
program statement will be executed(inside
block of code), otherwise outside statement is
executed.
Example program :
if statement:
Syntax: Eg:
if(condition 1 is true): mark=96
True statement1 if(mark>90):
elif(Condition 2 is true): print(“S Grade”)
elif(mark>80):
True Statement 2
print(“A Grade”)
elif(Condition 3 is true):
elif(mark>70):
True Statement 3 print(“B Grade”)
else: elif(mark>60):
False Statement print(“D Grade”)
elif(mark>50):
print(“E Grade”)
else:
Nested if...else statement:
Syntax: Eg:
if(condition 1 is true): a=75; b=60; c=90
if(condition 2 is true): if(a>b):
True Statement 2 if(a>c):
else: print(“a is greater”)
False Statement2 else:
else: print(“c is greater”)
False Statement 1 else:
if(b>c):
print(“b is greater”)
else:
print(“c is greater”)
Sample Programs
• Program to provide bonus mark if the category is
sports
• Odd or even number
• Leap year or not
• Greatest of 2 nos.
• Greatest of 3 nos.
• Eligibility for voting
• Traffic light system
• Positive negative or zero
ITERATION:
• They are perfect for processing repetitive
programming tasks
• With indefinite iteration(while loop), the
number of times the loop is executed isn’t
specified explicitly in advance. Rather, the
designated block is executed repeatedly as
long as some condition is met.
• With definite iteration(for loop) , the
number of times the designated block will
be executed is specified explicitly at the
time the loop starts.
WHILE STATEMENT: (infinite and endless
loop)
• Repeats a statement or group of
statements while a given condition is
TRUE.
while statement
Syntax: Eg:
i=1; sum=0
while(Condition): while(i<=10):
body of the loop sum=sum+i
i=i+1
print(“sum of first 10 natural
numbers is”, sum)
Output:
sum of first10 natural
numbers is 55
else with while
Syntax: eg:
i=1
while(i<=5):
while(Condition):
print(i)
body of the loop i=i+1
else: else:
Statements print(i,‘ exceeded 5’)
Output:
1
Note: 2
#else would be executed once 3
after the failure of while 4
condition 5
FOR LOOP:(finite loop)
OUTPUT:
sum of first 10 natural numbers is 55
while with else
while(Condition1):
while(Condition2): Output:
body of the inner loop 01234
body of the outer loop 01234
Sample programs
• program to find sum of n numbers
• program to find factorial of a number
• program to find sum of digits of a number
• program to reverse the given number
• program to find number is armstrong number or not
• program to check the number is palindrome or not
• Program to check given no. prime or not
• Fibonacci Series
Loop Control Statements
1. Break statement: 2. Continue statement: •Pass statement:
• Used to come out • Used to suspend the current It is a null statement,
from the loop flow and starts the next nothing happens when it is
executed.
• Eg: iteration
• Eg: Eg:
for i in "welcome": for i in "welcome": for i in “welcome”:
if(i=="c"): if(i=="c"): if (i == “c”):
continue pass
break
print(i)
print(i) print(i)
Output:
Output: w
• Output
e
• w • w l
• e • e c
• l • l o
m
• o
e
• m
• e
FUNCTIONS
Function
• A function is a block of organized, reusable code
that is used to perform a single, related action.
• Produces modularity.
Functions
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable-Length Arguments
1. Required Arguments
• These are the arguments that are passed to a function in
correct positional order.
• Here, the number of arguments in the function call should
match exactly with the function definition.
Eg:
def printme(ss):
print(ss)
OUTPUT:
return Hello
• Since the parameters are identified with their names, these names
act as keywords.
Eg:
def printme(name, type): or def printme(type, name):
print(name, “ ”, type)
return OUTPUT:
Python Language
printme(name=“Python”, type=“Language”))
3. Default Arguments
• These argument assumes a default value, if its value is not
provided in the function call.
Eg:
def printme(name, type=“Scripting”):
OUTPUT:
print(name, “ ”, type) Python Scripting
return Python Language
printme(name=“Python”)
printme(name=“Python”, type=“Language”))
4. Variable-Length Arguments
• When the number of arguments passed on to the function is not known
beforehand, we can use the variable-length arguments concept.
print(‘a’,’b’,’c’)
printme(5,”Monty”,”Python”,”Flying”,”Circus”)
printme(4)
Fruitful Functions
• The functions that returns back some value are
called as fruitful functions.
• Eg: sq.py
def square(n):
return n*n
fname=“Apple”
fruit(fname)
OUTPUT:
Apple
Global Scope
• Eg:
def fruit():
print(fname)
Here, eventhough fname is not passed to
fruit function, the value of fname i.e. Apple
fname=“Apple” is printed.
This is because the variable fname is
fruit() defined outside the function. This is called
as global scope.
OUTPUT:
Apple
Local Scope
• Eg:
def fruit():
fname=“Apple”
print(fname) Here, the variable fname is defined only
inside the function. Hence the fruit
function alone knows the value of fname
and not outside [Shown using Error].
fruit() This is called as local scope.
print(fname)
OUTPUT:
Apple
Error: variable fname undefined
Global vs Local Scope
• Eg:
def fruit():
fname=“Mango”
print(fname) Here, the variable fname is defined only
inside the function. Hence the fruit
function alone knows the value of fname
and not outside [Shown using Error].
fname=“Apple” This is called as local scope.
fruit()
print(fname)
OUTPUT:
Mango
Apple
Making Local Variable as Global
• Eg:
def fruit():
global fname
fname=“Mango”
print(fname) Use “global” keyword
fruit()
print(fname)
OUTPUT:
Mango
Mango
Function Composition
• A function can be called from another function. This is
called as composition.
Eg:
def inner():
print(“Hello!!! I am inside inner function now!!!”)
def outer():
inner() # Function Composition
print(“Hai, I came out of inner function and now I am in
outer function”)
outer()
Recursion
• A function that calls itself or some other function again and
again are called as recursion.
• Eg:
def fact(n):
if(n==1 or n==0):
return 1
else:
return n*fact(n-1)
n=int(input(“Enter a value: ”))
print(fact(n))
OUTPUT:
Enter a value: 5
120
Recursion Example
def countdown(n):
if n <= 0:
print("Blastoff!")
else:
print(n)
countdown(n-1)
countdown(10)
Strings
• String is defined as sequence of characters
represented in quotation marks (either single
quotes ( ‘ ) or double quotes ( “ ).
• An individual character in a string is accessed
using a index.
• The index should always be an integer
(positive or negative).
• A index starts from 0 to n-1.
• Strings are immutable i.e. the contents of the
string cannot be changed after it is created.
Definition
• A string is a collection of characters stored and
accessed in sequence.
• Eg:
>>> s=“Python” must be given within ‘ ’ or “ ”.
s[0] P s[-6]
s[1] y s[-5]
s[2] t s[-4] This is called as indexing
s[3] h s[-3]
s[4] o s[-2]
s[5] n s[-1]
Character Data type
• Python does not support a char data type.
h in a 1
in Membership operator
s in a 0
h not in a 0
not in Membership operator
s not in a 1
import array
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
Illustrative Programs
Greatest Common Divisor (GCD):
import array
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
Program to find Square Root
import math
n=int(input("enter the value of n:"))
s= math.sqrt(n)
print("The square root of ",n," is: ",s)
Program to find Exponentiation of Given
Number
b = int(input("Enter the base value: "))
p = int(input("Enter the power value: "))
val = 1
for i in range(1, p+1):
val = val * b (val=b**p)
print("The value of ", b ," power ", p , " is : ", val)
MAXIMUM OF A LIST OF NUMBERS
n = int(input("Enter total number of elements: "))
list=[]
for i in range(0, n):
element = int(input("Enter element:"))
list.append(element)
max = list[0]
for i in range(1, n):
if(list[i] > max):
max = list[i]
def linear search(inputlist, search):
flag=0 Linear
for i in range(0, len(inputlist)):
if(search == inputlist[i]):
Search
print("Element ",inputlist[i]," is found at ",i," position")
flag=1
break
if(flag==0):
print("Element ",search," is not found in the list")