0% found this document useful (0 votes)
5 views

Unit 3

This document covers various concepts in Python programming, focusing on control flow, functions, and string handling. It explains the use of functions like len(), recursion, and the difference between global and local scope, as well as file operations and iteration techniques such as for and while loops. Additionally, it discusses branching statements, fruitful functions, and string manipulation methods with examples.

Uploaded by

anitha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit 3

This document covers various concepts in Python programming, focusing on control flow, functions, and string handling. It explains the use of functions like len(), recursion, and the difference between global and local scope, as well as file operations and iteration techniques such as for and while loops. Additionally, it discusses branching statements, fruitful functions, and string manipulation methods with examples.

Uploaded by

anitha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

UNIT-III CONTROL FLOW, FUNCTIONS, STRINGS

PART-A

1.What is len() function? Give example for how is used on strings.

The len() function in Python is used to determine the number of items in an object.
It can be applied to various data types such as strings, lists, tuples, dictionaries, and more.
Example:
string = "Hello, World!"
print(len(string))
Output: 13

2. Compare return values and composition.


Return Values: Directly provide the result of a function’s computation.
Example:
def add(a, b):
return a + b
Function Composition: Combine multiple functions to create a new function, where the
output of one function is the input to another.
Example:
def add(a, b):
c=a+b
return c
def square(c)
return (c**2)
print(“Square of”,c,”is”,square(add(10,20)))
Output Square of 30 is 900
3. Define string immutability.
We can’t exchange the characters of the string. This is called as immutable.
>>> greeting = ‘Hello, world!’
>>> greeting[0] = ‘J
TypeError: ‘str’ object does not support item assignment
4. What is the purpose of break and continue statement in python.
The continue statement rejects all the remaining statements in the current iteration of the
loop and moves the control back to the top of the loop.
Break statement is used to break the loop.
Eg:
for number in range(1,5):
if(number==3):
continue
print(number)
Output:
1
2
4
for number in range(1,5):
if(number==3):
break
print(number)
Output:
1
2
3
5. Write the syntax for opening a file to write in binary mode.
Python has a built-in function open() to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
Syntax:
>>> f = open(“test.txt”)
Eg:
f = open(“pec.dat”,”w”)
f.write(“Welcome to PEC”)
f.close()
Eg:
Text=f.read()
Print text
6. What are the different modules in python?
Python Module is a file that contains built-in functions, classes,its and variables.
There are two types of modules in Python, they are built-in modules and user-defined
modules.

Few examples of built-in modules are:


➢ math module
➢ os module
➢ random module
➢ datetime module
7. List any four file operations
In Python, a file operation takes place in the following order.
1. Open a file
2. Read
3.Write (perform operation)
4. Close the file
8. Write a python program to count words in a sentence using split() function.
test_string=input(“Enter string:”)
l=[]
l=test_string.split()
wordfreq=[l.count(p) for p in l]
print(dict(zip(l,wordfreq)))
Output:
Enter string: All is Well All is Well
{‘All’: 2, ‘is’: 2, ‘Well’: 2}
9. What is recursion?
Recursion is a technique of solving a problem by breaking it down into smaller and
smaller sub problems until you get to a small enough problem that it can be easily solved.
Recursion is a process by which a function calls itself repeatedly until some specified
condition has been satisfied.
10. Explain global and local scope.
Variables that are defined inside a function body are called as local scope variables.
Variables that are defined outside a function body are called as global scope variables.
Eg: total = 0; # This is global variable.
def sum( arg1, arg2 ):
total = arg1 + arg2; # Here total is local variable
11. Write a for loop that prints numbers from 0 to 57 using range function in a python.
for i in range(58):
print(i)
12. What is the fruitful function in python?

Functions which returns a value is called as fruitful function.


Example
def sum(c,d):
e=c+d
return (e)
print(sum(2,3)
13. What are the purposes of pass statement in python?
It is used when a statement is required syntactically but you do not want any command or
code to execute. The pass statement is a null operation; nothing happens when it executes.
Eg:
for letter in ‘Python’:
if letter == ‘h’:
pass
14. What is Linear Search?
Linear search is one of the simplest search algorithms. It works by checking each element
in a list one by one until it finds the target value or reaches the end of the list.
PART-B

1. Explain in detail about the branching statements in python.


Conditional Statements are statements in Python that provide a choice for the control flow
based on a condition. It means that the control flow of the Python program will be decided
based on the outcome of the condition.
Types of Conditional Statements
1. If Conditional Statement
2. If else Conditional Statements
3. Nested if..else Conditional Statements
4. If-elif-else Conditional Statements
5.Nested if statements

If Conditional Statement in Python


If the simple code of block is to be performed if the condition holds then the if statement is
used. Here the condition mentioned holds then the code of the block runs otherwise not.

Syntax of If Statement:

if condition:
# Statements to execute if
# condition is true

Example:
if 10 > 5:
print("10 greater than 5")
print("Program ended")

Output:
10 greater than 5
Program ended

If else Conditional Statements in Python


In a conditional if Statement the additional block of code is merged as an else statement which
is performed when if condition is false.

Syntax of Python If-Else:

if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

Example:
x=3
if x == 4:
print("Yes")
else:
print("No")
Output
No

Nested if..else Conditional Statements in Python


Nested if..else means an if-else statement inside another if statement. Or in simple words
first, there is an outer if statement, and inside it another if – else statement is present and such
type of statement is known as nested if statement. We can use one if or else if statement inside
another if or else if statements.

Example
letter = "A"

if letter == "B":
print("letter is B")

elif letter == "C":


print("letter is C")

elif letter == "A":


print("letter is A")

else:
print("letter isn't A, B or C")

Output
letter is A

Nested if statements:
You can nest if statements within another if or else block to create complex decision trees.

Syntax:
if (condition1):
# executes when condition is True
if (condition2):
# executes when condition is True
Example:
i = -15;
if i != 0:
if i > 0:
print("Positive")
if i < 0:
print("Negative")

Output:
Negative

2. Explain in detail about the iteration in python.


ITERATION
Iteration is repeating a set of instructions and controlling their execution for a
particular number of times. Iteration statements are also called as loops.

State
A new assignment makes an existing variable refer to a new value (and stop
referring to the old value).
>>> x = 5
>>> x
5
>>> x = 7
>>> x
7
The first time we display x, its value is 5; the second time, its value is 7. Python uses the equal
sign (=) for assignment. First, equality is a symmetric relationship and assignment is not.
For example, in mathematics, if a = 7 then 7 = a. But in Python, the statement a = 7 is legal
and 7 = a is not. Also, in mathematics, a proposition of equality is either true or false for all
time. If a =b now, then a will always equal b. In Python, an assignment statement can make
two variables equal.
>>> a = 5
>>> b = a # a and b are now equal
>>> a = 3 # a and b are no longer equal
>>> b
5
The third line changes the value of ―a but does not change the value of ―b , so they are no
longer equal. A common kind of reassignment is an update, where the new value of the
variable depends on the old.
>>> x = x + 1
This means ―get the current value of x, add one, and then update x with the new value. If we
try to update a variable that doesn‘t exist, you get an error, because Python evaluates the right
side before it assigns a value to x:
>>> x = x + 1
NameError: name ‘x’ is not defined, Before you can update a variable, you have to initialize
it, usually with a simple assignment:
>>>x = 0
>>>x = x + 1
Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement.

While loop
Repeats a statement or block of statements while a given condition is TRUE.
Tests the condition before executing the body of loop.

A while statement is an iterative control statement that repeatedly executes a set of


statements based on a provided Boolean expression (condition).
Syntax of While Loop:
while condition:
statements
Example:
while n > 0:
print(n)
n=n–1
Control Flow, Functions 3.11
The above while statement prints the value of n a number of times until n is
greater than zero.
The flow of execution for a while statement:
1. Determine whether the condition is true or false.
2. If false, exit the while statement and continue execution at the next statement.
3. If the condition is true, run the body and then go back to step 1

The body of the loop should change the value of one or more variables so that the
condition becomes false eventually and the loop terminates. Otherwise the loop will repeat
forever, which is called an infinite loop. In the case of countdown, we can prove that the loop
terminates: if n is zero or negative, the loop never runs. Otherwise, n gets smaller each time
through the loop, so eventually we have to get to 0. For some other loops, it is not so easy to
tell

Program
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
print(“The sum is”, sum) # print the sum
Output:
The sum is 55

In the above program, the test condition will be True as long as our counter
variable i is less than or equal to n. We need to increase the value of counter variable in the
body of the loop. This is very important (and mostly forgotten). Failing to do so will result in
an infinite loop (never ending loop). Finally the result is displayed.

For Loop
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects. Iterating over a sequence is called traversal. The for loops are used to construct
definite loops.
Syntax of FOR LOOP:
for val in sequence:
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.
Example 1:
for k in [4, 2 ,3, 1]:
print (k)
Output:
4
2
3
1

Break
Break statement is used to break the loop. For example, suppose you want to take input
from the user until they type done
Break statements can alter the flow of a loop. It terminates the current loop and executes
the remaining statement outside the loop.
If the loop has else statement, that will also gets terminated and come out of the loop
completely.
Syntax:
Break
Example
for i in "welcome":
if(i=="c"):
break l
print(i)
Output
w
e
l

CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax:
Continue
Example
for i in "welcome":
if(i=="c"):
continue
print(i)
Output
w
e
l
o
m
e

PASS
It is used when a statement is required syntactically but you don’t want any code to
execute.
It is a null statement, nothing happens when it is executed.
Syntax:
pass
Example
for i in "welcome":
if(i=="c"):
pass
print(i)
Output
w
e
l
c
o
m
e
3. Explain in detail about the fruitful function with examples.
A function that returns a value is called fruitful function.
Example:Root=sqrt (25)
Example: def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)
Void Function
A function that perform action but don’t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()
Return values:
The built-in functions we have used, such as abs, pow, and max, have produced
results.
Calling each of these functions generates a value, which we usually assign to a variable or use
as part of an expression.
But so far, none of the functions we have written has returned a value. In this
chapter, we are going to write functions that return values, which we will call fruitful
functions, for want of a
better name. The first example is area, which returns the area of a circle with the given radius:
Example:
def area(radius):
temp = 3.14159 * radius**2
return temp

We have seen the return statement before, but in a fruitful function the return
statement includes a return value. This statement means: Return immediately from this
function and use the following expression as a return value. The expression provided can be
arbitrarily complicated, so we could have written this function more concisely:
Example:
def area(radius):
return 3.14159 * radius**2
On the other hand, temporary variables like temp often make debugging easier.
Sometimes it is useful to have multiple return statements, one in each branch of a conditional.
We have already seen the built-in abs, now we see how to write our own:
Example:
def absolute_value(x):
if x < 0:
return -x
else:
return x
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2 variables
return a+b– return expression
return 8– return value

4. Describe the string handling function with an example.


STRINGS
A string is a sequence of characters. You can access the characters one at a time
with the bracket operator:
>>> fruit = ‘banana’
letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter.
The expression in brackets is called an index. The index indicates which character in the
sequence you want (hence the name).But you might not get what you expect:
>>> letter
‘a’
Example
>>> i = 1
>>> fruit[i]
‘a’
But the value of the index has to be an integer. Otherwise you get:
>>> letter = fruit[1.5]
TypeError: string indices must be integers

String slices
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
Example
>>> s = ‘Monty Python’
>>> s[0:5]
‘Monty’
The operator [n:m] returns the part of the string from the ―n-eth character to the ―m-eth
character, including the first but excluding the last. This behavior is counter intuitive, butit might
help to imagine the indices pointing between the characters. 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’
If the first index is greater than or equal to the second the result is an empty string,
represented by two quotation marks:
>>> fruit = ‘banana’
>>> fruit[3:3]
‘’
An empty string contains no characters and has length 0, but other than that, it is the same
as any other string.
Immutability
It is tempting to use the [] operator on the left side of an assignment, with the intention of
changing a character in a string.
For example:
>>> greeting = ‘Hello, world!’
>>> greeting[0] = ‘J’
TypeError: ‘str’ object does not support item assignment
The ―object in this case is the string and the ―item is the character you tried to assign. The
reason for the error is that strings are immutable, which means you can‘t change an existing string.
The best you can do is create a new string that is a variation on the original:
>>> greeting = ‘Hello, world!’
>>> new_greeting = ‘J’ + greeting[1:]
>>> new_greeting
‘Jello, world!’
This example concatenates a new first letter onto a slice of greeting. It has no effect on the
original string.
Length
The len function, when applied to a string, returns the number of characters in a string:
>>> fruit = “banana”
>>> len(fruit)
6
The index starts counting form zero. In the above string, the index value in from 0 to 5.
To get the last character, we have to subtract 1 from the length of fruit:
size = len(fruit)
last = fruit[size-1]
Alternatively, we can use negative indices, which count backward from the end of the string.
The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.
Syntax to access the method
Stringname.method()

S.No Syntax Example Description

1 a.capitalize() >>> a.capitalize() capitalize only the first letter in a string


‘Happy birthday’
2 a.upper() >>> a.upper() change string to upper case
'HAPPY
BIRTHDAY’
3 a.lower() >>> a.lower() change string to lower case
' happy birthday’
4 a.title() >>> a.title() change string to title case first characters of all
the words are capitalized.
' Happy Birthday '
5 a.swapcase() >>> a.swapcase() change lowercase characters to uppercase and
vice versa
'HAPPY BIRTHDAY
6 a.split() >>> a.split() returns a list of words separated by space
['happy', 'birthday']

5. Explain in detail about recursion with proper syntax and program in python.
Recursion
Recursion is a technique of solving a problem by breaking it down into smaller and
smaller sub problems until you get to a small enough problem that it can be easily solved.
Usually, recursion involves a function calling itself until a specified a specified condition is
met/ A function calling itself till it reaches the base value - stop point of function call.

Example: factorial of a given number using recursion


Algorithm for factorial using recursion
Step 1 : Start
Step 2 : Input number as n
Step 3 : Call factorial(n)
Step 4 : End

Factorial(n)
Step 1 : Set f=1
Step 2: IF n==1 then return 1
ELSE
Set f=n*factorial(n-1)
Step 3 : print f
Factorial of n
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
n=eval(input("enter no. to find fact:"))
fact=fact(n)
print("Fact is",fact)

Output
enter no. to find fact:5
Fact is 120

You might also like