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

UNIT 3 (1)

Uploaded by

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

UNIT 3 (1)

Uploaded by

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

GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT III CONTROL FLOW, FUNCTIONS


Conditionals: Boolean values and operators, conditional (if), alternative (if-else),chained
conditional (if-elif- else); Iteration: state, while, for, break, continue, pass; Fruitful functions:
return values, parameters, scope: local and global, composition ,recursion; Strings: string slices,
immutability, string functions and methods, string module; Lists as arrays. Illustrative
programs: square root, gcd, exponentiation, sum the array of\numbers, linear search, binary
search.
3.1 Decision Making
 Decision making constructs begins with a Boolean expression, an expression that returns either
True or False.
 Decision Making structures are necessary to perform an action or a calculation only when a
certain condition is met.
 Zero and null values are assumed as false in python Programming.
 A boolean expression is an expression that is either true or false.
The operator ==, which compares two operands and produces True if they are equal and False otherwise:
>>> 5 == 5
True
>>> 5 == 6
False
True and False are special values that belong to the type bool; they are not strings.

Types of Decision making statements


if statements
if..else statements
elif statements
Nested if..elif..else statements
inline if

Conditional (if):
 Conditional if statements starts with a Boolean expression (condition) followed by a statement or a
group of statements, which evaluates the ‘if’ expression and executes the body of the program only
if the evaluation is TRUE.
 If the Boolean expression (condition) evaluates to FALSE, then the next code after the end of if
statement will be executed.
 Body of if statements were indicated by the indentation.
syntax:

Flowchart:

1
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Alternative (if-else):
 An if-else statement block first evaluates the ‘if expression’.
 If the test condition is TRUE, Python executes statements in the body of the ‘if statement’.
 If the test condition is FALSE, Python executes the statements in the else block.
syntax:

Flowchart:

Examples:
1. odd or even number
2. positive or negative number
3. leap year or not

odd or even number Output


n=int(input("enter a number")) enter a
if(n%2==0): number 4
print("even even number
number") else:
print("odd number")
positive or negative number Output

2
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
n=int(input("enter a number")) enter a
if(n>=0): number8
print("positive positive
number") else: number
print("negative number")
leap year or not Output
y=int(input("enter a year")) enter a
if(y%4==0): year2000 leap
print("leap year
year") else:
print("not leap year")

Chained conditionals (if-elif-else)


 An elif (else if) statement can be used when there is a need to check or evaluate multiple
expression.
 An if..elif..else structure first checks if the ‘if statement’ is True.
 If it is True, then Python executes the statements in the if block. If it is False, it tests the
condition in the elif block.
 If the elif statement s is evaluated as True, Python executes the statements in the elif block.
 Otherwise control passes to the else block.
syntax

Flowchart

3
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Examples:
1. student mark system
2. traffic light system

Nested conditionals
 Nested conditional statements are used whenever there is a need to check for another condition
after the first condition has been evaluated as True.
Syntax

4
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Example:
1. greatest of three numbers

Inline if statements
An inline if statement is a simpler form of if statement and is more convenient, if we need to
perform a simple task.
Syntax:
do Task A if condition is true else do Task B

3.2 Iteration or Control Statements.


state
while
for
break
continue
pass

State
Transition from one process to another process under specified condition with in a time is called State

Iterations:

while loop
 While loop is used when we need to repeatedly execute a statement or group statements, while
the test condition is True.
 When the test condition is no longer true, program control passes to the line after the loop.

5
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Examples:
1. Program to find sum of n numbers
2. Program to find factorial of a number
3. Program to find sum of digits of a number
4. Program to reverse the given number
5. Program to find number is Armstrong number or not
6. Program to check the number is palindrome or not

6
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

For loop
 Executes a sequence of statements that allows a code to be repeated a certain number of times
using the “range” and “xrange” functions.

7
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
 Iterates over a sequence that may have different data types such as list, tuple and string.
 For in loop repeats a given block of codes by specified number of times.

 range()- produces the list iterates of numbers starting with start and generate numbers with
one less than the number end.
 step()- It is the difference between each number in the sequence. It can be both negative and
positive, but not zero.
 If start is not given, the numbers will start from zero. If step is not specified, a list of
consecutive numbers will be generated.

For in sequence
 The for loop in Python is used to iterate over a sequence (list, tuple, string).
 Iterating over a sequence is called traversal.
 Loop continues until we reach the last element in the sequence.
 The body of for loop is separated from the rest of the code using indentation.
Syntax

8
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Nested Loops
 Nesting is defined as the placing of one loop inside the body of another loop.
 When we nest two loops, the outer loop takes the control of the number of complete repetitions of the
inner loop.
 Can have nested loops for both while and for loops.
Syntax for nested for loop:
for <iterating_variable> in <sequence>:
for <iterating_variable> in <sequence>:
statements

9
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
statements

Syntax for nested while loop:


while(test_expression):
while(test_expression):
statements
statements

Loop Control Structures


break
 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 get terminated and come out of the loop completely.

continue
 It terminates the current iteration and transfer the control to the next iteration in the loop.

10
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

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.

Difference between break and continue

11
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
else statements in loops
else in for loop:
 If else statement is used in for loop, the else statement is executed when the loop has reached the
limit.
 The statements inside for loop and statements inside else will also execute.

else in while loop:


 If else statement is used within while loop , the else part will be executed when the condition become
false.
 The statements inside for loop and statements inside else will also execute.

Infinite Loop
 A loop becomes infinite loop if a condition never becomes false. This results in a loop that never
ends. Such a loop is called as an infinite loop.
 The infinite loop is formed with the while statement.
 When the specified test condition is always true, we get an infinite loop.

Eg:
while(True):
n=int(input(“ Enter an integer
“)) print(“ The double of “,n,”
is “,2*n)
o/p:
Enter an integer :
3 The double of 3
is 6 Enter an
integer : 5 The
double of 5 is 10
Enter an integer :
6 The double of 6
is 12

12
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

3.3 Fruitful function


 A function that returns a value is called fruitful function.
 A function is a building block of structured, reusable code that is used to carry out a particular,
interconnected action.
 A group of related statements to perform a specific task.
 It can also be termed as subroutines, routines, procedures, methods or subprograms.
 It offers improved modularity for various applications.
 Has an elevated amount of code reusing.
 It enhances the comprehensibility and quality of the program.
 It also lowers the cost for development and maintenance of the software.
 Types of function: 1. Built-in functions 2. User-Defined functions
 Built-in functions- Functions that are built into Python
 User-defined functions- Functions defined by the users themselves.

Defining a Function
 Function blocks start with the keyword def followed by the function name and a pair of parentheses
().
 A function name is used to distinctively identify it.
 A colon (:) is used to spot the end of function header.
 The values are passed to the function with the help of parameters or arguments. Any input parameters
or arguments are to be placed inside these parentheses, not compulsory.
 Documentation string (docstring) is optional.
 The function body consists of one or more valid python statements. Statements should have similar
indentation level (usually 4 spaces).
 A return statement is used to return a value from the function. The statement return [expression]
leaves a function, optionally by passing back an expression to the caller.
 A return statement with no arguments is same as return None.
Syntax:
def function_name(parameters):
statements

Function Call
 A function can be called by simply type the function name with suitable arguments.
 Once a function has been defined, it is feasible to call it from another function.
Syntax:
function_name(parameters)

Return values:
 return keywords are used to return the values from the function.
 A function may or may not return a value.
 If a function does not have a return keyword, it will send None
Syntax:
return [expression] // This statement can contain expression which gets evaluated and the value
is returned.
example:
return(a) – return 1 variable
return (a,b)– return 2 variables
return (a+b)– return expression
return(8)– return value

13
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Example:
def add():
a=10
b=20
c=a+b
return c
d=add()
print(d)

Void Function
A function that perform action but don’t return any value.
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()

Function Composition:
 Function Composition is the ability to call one function from within another function
 It is a way of combining functions such that the result of each function is passed as the argument of
the next function.
 In other words the output of one function is given as the input of another function is known as
function composition.

3.4 Recursion
 Recursion is the process of calling the same function itself again and again until some condition
is satisfied.
 In order to write a recursive program, the user must satisfy the following:
 The problem must be analyzed and written in recursive form.
 The problem must have the stopping condition.
Syntax:
function1():
function1():

14
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Advantages of Recursion
 Recursive functions make the code look clean and elegant.
 A larger problem can be broken down into simpler sub-problems using recursion.

Disadvantages of Recursion
 The recursive functions are rigid to debug.
 Recursive calls are exclusive as they acquire up a lot of memory and time

3.5 Strings
 A String is a sequence of characters.
 Strings are identified as a contiguous set of Unicode characters which may consist of letters, numbers,
special symbols or a combination of these types represented within the quotation marks.
 It is an immutable data type, which means it can no longer be able to modify the string once it is
created.
 It permits the use of single(‘),double(“) and triple(’’’ or ”””) quotes to represent a string literal.
Eg: ‘c’,’ Hello World’ , “ Hello World “
 You can access the characters one at a time with the bracket operator:
>>> fruit = 'banana'
>>> letter = fruit[1]
>>> print(letter)
o/p: a
 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).
>>> letter = fruit[1.5]
TypeError: string indices must be integers, not float
 Strings are continous series of characters delimited by single or double quotes.

15
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship

16
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

string built in functions and methods:

 A method is a function that “belongs to” an object.


Syntax to access the method
Stringname.method()

17
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
a=”happy birthday”
here, a is the string name.

String modules:
 A module is a file containing Python definitions, functions, statements.
 Standard library of Python is extended as modules.
 To use these modules in a program, programmer needs to import the module.
 Once we import a module, we can reference or use to any of its functions or variables in our code.
 There is large number of standard modules also available in python.
 Standard modules can be imported the same way as we import our user-defined modules.

18
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

3.6 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’,[elements])

example:
a=array.array(‘i’,[1,2,3,4])
a- array name
array- module name
i- integer datatype

19
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

Convert list into array:


fromlist() function is used to append list to array. Here the list is act like a array.

Syntax:
arrayname.fromlist(list_name)

Methods of an array

20
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING
ILLUSTRATIVE PROBLEMS

21
GE3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

22

You might also like