0% found this document useful (0 votes)
18 views77 pages

Unit 3

Uploaded by

selvaprabhu.t
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views77 pages

Unit 3

Uploaded by

selvaprabhu.t
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 77

UNIT-3

CONTROL FLOW, FUNCTION AND


STRINGS
 Boolean Values True and False
 Operatorsunit-2 already covered
 Conditions: (selection)
1. Conditional (if)
2. Alternative (if-else)
3. Chained Condition (if-elif-else)
4. Nested if else
 Iteration (looping, Repetition)
1. State
2. while
3. for
4. else (while, for)

 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:

Program to provide flat rs 500, if the purchase amount is


greater than 2000.

purchase=int(input(“enter your purchase amount”))


if(purchase>=2000):
purchase=purchase-500
print(“amount to pay”,purchase)
Alternative Execution :( if-else)
Output : yes
Chained Conditionals:
• The elif is short for else if.
• This is used to check more than one
condition.
• If the condition1 is False, it checks the
condition2 of the elif block. If all the
conditions are False, then the else part is
executed.
if….elif....else 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)

• Executes a sequence of statements multiple


times.
• If we want to execute some action for every
element present in some sequence (it may be
string or collection) then we should go for
for loop.
• Body will be executed for every element
present in the sequence.
Using range() function
• Syntax:
range(start, stop, step)
• Eg:

for value in range(5): for value in range(1, 10, 2):


print(value, end=“ ”) print(value, end=“ ”)
OUTPUT: OUTPUT:
0 1 2 3 4 1 3 5 7 9

for value in range(2, 10, 2): for value in range(5, 1, -1):


print(value, end=“ ”) print(value, end=“ ”)
OUTPUT: OUTPUT:
2 4 6 8 5 4 3 2
for
Syntax: Eg:
for letter in “python”:
for <iterating variable> in print(letter)
<sequence>:
body of the loop Output:
p
y
t
h
o
n
for
PROGRAM[ while example rewritten using for ]:
sum=0
for i in range(11):
sum=sum+i
print(“sum of first 10 natural numbers is ”,sum)

OUTPUT:
sum of first 10 natural numbers is 55
while with else

for with else 


Nested loops
Syntax: Eg:
for <iterating variable> in <sequence>: #for loop
for <iterating variable> in for i in range (2):
<sequence>: for j in range (5):
body of the inner loop print(j,end=" ")
body of the outer loop print(" ")

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

User Defined Built-in Function /


Functions Library Function
Built In Functions
• Predefined library function that is not required to be
written by the programmer again:
• abs()  Produces only positive values
• input()  reads user input
• int()  converts to integer datatype
• str()  converts to string datatype
• pow()  computes exponentiation
• sum()  adds all values inside it
• print()  displays the result
• float()  converts to float datatype
Function Syntax
Function Definition Syntax:
def function_name( parameters separated by commas):
Statement1
Statement2
...
return [expression or single variable]
Example:
#Function Definition #Function Call
def add(a): >>> add(5)
a=a+2 >>> 7
return a or within the same code:
print(add(5))
>>> Restart ….
>>> 7
Function Arguments
• There are four different types of formal arguments:

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

s=“Hello” Traceback error: Missing 1 required


positional argument: ‘s’
printme(s)
printme()
2. KeywordArguments
• These are the arguments that are given values inside the function
call.

• These parameters can be either skipped or placed out of order,


since the parameters are identified with the help of their name.

• 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.

• An (*) is placed before the variable-length argument.

• If no arguments are passed, this tuple remains empty.


Eg:
def printme(name, *vartuple):
OUTPUT:
print(name,end=“ ”)
a b c
for each in vartuple:
5 Monty Python Flying Circus
print(each, end=“ ”) 4
return

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

n=int(input(“Enter a number:”)) OUTPUT:


Enter a number: 5
print(square(n)) 25
Return Values
• Return value from a function can either be written as
a direct value or as a variable or even as an
expression.

• if you try to assign result of a void function to a


variable, you get a value called None
• The values that are returned by the function will go
back to the place from where it was called.
Sometimes it is useful to have multiple return
statements, one in each branch of a conditional
65==65
none
• Code that appears after a return statement, or any other place the
flow of execution can never reach, is called dead code.
Parameters
• The values / variables that are passed to one function.
• Also called as arguments.
• There are two types:
 Actual Parameters
 Formal Parameters
• Eg:
Formal
def square(x): Parameters
Actual Parameters
print(x*x) appears in Function Call
statement;
Whereas formal
n=int(input(“Enter a number:”)) parameters appears in
function definition
square(n) Actual
Parameters
Scope of a Variable
• Defines the lifetime and accessibility of a variable.
• There are two kinds of scope:
 Global Scope
 Local Scope
• Eg: Here, since fname is
def fruit(fname): passed to fruit function,
value of fname i.e. Apple
print(fname) is printed.

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.

• Instead these are treated as a string with length of 1.


• Eg:

>>> s=“ksriet” >>>s=‘A’


>>> type(s) >>> type(s)
<class, ‘str’> <class, ‘str’>
>>> s[0] >>> s[0]
‘s’ ‘A’
Strings are Immutable?
• Yes, the strings are immutable.
• i.e. Once a value have been assigned, the letters in it
cannot be changed.
• Eg:
>>> s=“Python”
>>> s[0]=“H”
Error: variable s is immutable
>>> s[-2]=“i”
Error: variable s is immutable
String indexing
Strings operations
Let a=“hello” b=“python”

Operator Description Example

+ Concatenation a+b  hellopython

* Repetition a*2  hellohello

[] Slicing a[1]  ‘e’

[:] Slicing the given Range a[1:4]  ‘ell’

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

% Format operator print(“My name is %s” %(“Zara”))


String Methods
String Methods
String methods
Finding Substrings:
We can use the following 4 methods
For forward direction:
1) find()
2) index()
For backward direction:
1) rfind()
2) rindex()
String Methods
import string
s="Monty Python Flying Circus"
print(s.upper()) OUTPUT :
print(s.capitalize()) MONTY PYTHON FLYING
CIRCUS
print(s.swapcase()) Monty python flying circus
print(s.title()) mONTY pYTHON fLYING cIRCUS
Monty Python Flying Circus
print(s.lower()) monty python flying circus
print(s.count('a')) 0
20
print(s.find('Circus')) 20
print(s.index('Circus')) Monty java Flying Circus
print(s.replace("Python", "java"))
List as array:
Array:
• Array is a collection of similar elements.
Elements in the array can be accessed by
index. Index starts with 0.
• Array can be handled in python by module named
array. To create array have to import array module
in the program.
Syntax :
import array
Syntax to create array:
Array_name=module_name.function_name(‘datatype’,
Example
Example:
a=array.array(‘i’,[1,2,3,4])
• a- array name
• array- module name
• i- integer datatype
Program to find sum of
array elements

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):

a=int(input("Enter first number: "))


b=int(input("Enter second number: "))
if(a<b):
min=a
else:
min=b
for i in range(1,min+1):
if((a%i==0)and (b%i==0)):
gcd=i
print("GCD of ",a," and ",b," is: ",gcd)
Program to find sum of
array elements

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")

# program execution starts from here


n=int(input("Enter number of elements inside the list: "))
inputlist=[]
for i in range(0,n):
element=int(input("Enter element :"))
inputlist.append(element)
search=int(input("Enter the element to be searched for: "))
print("Linear Search Results...")
linear search(inputlist, search)

You might also like