BACSE101 – PROBLEM SOLVING USING PYTHON MODULE 2 Problem Solving Approaches and Constructs for Controlling Program Flow
TOPIC 1 – PROBLEM SOLVING APPROACHES: TOP-DOWN
In a top-down strategy , you start with the big picture , break it into major subproblems, and then drill down to detailed tasks. Define the overall goal or system Partition into high-level components or modules Refine each component into smaller units until they’re directly implementable May Be Overlapping
TOPIC 2 – PROBLEM SOLVING APPROACHES: BOTTOM-UP
Bottom-up begins with detailed elements , builds and tests them, then integrates into larger subsystems. Solve small , concrete problems first Combine working pieces into more complex modules Continue integration until the full system emerges
TOPIC 3 – PROBLEM SOLVING APPROACHES: DIVIDE AND CONQUER
Divide and conquer algorithm is a problem-solving strategy that involves. Divide : break the given problem into smaller non-overlapping problems. Conquer : solve smaller problems Combine : use the solutions of smaller problems to find the overall result. non-overlapping
TOPIC 4 – PROBLEM SOLVING APPROACHES: BACKTRACKING
Backtracking algorithms are like problem-solving strategies that help explore different options to find the best solution . They work by trying out different paths and if one doesn't work, they backtrack and try another until they find the right one. It's like solving a puzzle by testing different pieces until they fit together perfectly.
TOPIC 5 – CONDITIONAL STATEMENTS
Conditional statements in python are used to execute certain blocks of code based on specific conditions . These statements help control the flow of a program , making it behave differently in different situations.
If Conditional Statement in Python If statement is the simplest form of a conditional statement. It executes a block of code if the given condition is true.
a = 33 b = 200 if b > a: print ( "b is greater than a" ) Short Hand if - Short-hand if statement allows us to write a single-line if statement. age = 19 if age > 18: print("Eligible to Vote.")
If else Conditional Statements in Python Else allows us to specify a block of code that will execute if the condition(s) associated with an if or elif statement evaluates to false . Else block provides a way to handle all other cases that don't meet the specified conditions.
age = 15 if age <= 12 : print ( “Travel for free" ) else : print ( “Pay for ticket" ) Short Hand if-else - The short-hand if-else statement allows us to write a single-line if-else statement . marks = 45 res = "Pass" if marks >= 40 else "Fail" print( f"Result : {res}") This technique is known as ternary operators , or conditional expressions
One line if else statement, with 3 conditions: a = 330 b = 330 print ( "a" ) if a > b else print ( "=" ) if a == b else print ( "b" )
Elif statement in python stands for "else if." It allows us to check multiple conditions , providing a way to execute different blocks of code based on which condition is true. Using elif statements makes our code more readable and efficient by eliminating the need for multiple nested if statements. elif Statement
a = 33 b = 33 if b > a: print ( "b is greater than a" ) elif a == b: print ( "a and b are equal" )
Nested if..else Conditional Statements in Python Nested if..Else means an if-else statement inside another if statement. We can use nested if statements to check conditions within conditions.
x = 41 if x > 10 : print ( "above ten," ) if x > 20 : print ( "and also above 20!" ) else : print ( "but not above 20." )
AND The and keyword is a logical operator, and is used to combine conditional statements: a = 200 b = 33 c = 500 if a > b and c > a: print ( "both conditions are true" )
OR The or keyword is a logical operator, and is used to combine conditional statements: a = 200 b = 33 c = 500 if a > b or a > c: print ( "at least one of the conditions is true" )
Not The not keyword is a logical operator, and is used to reverse the result of the conditional statement: a = 33 b = 200 if not a > b: print ( "a is not greater than b" )
The pass Statement If statements cannot be empty , but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error. a = 33 b = 200 if b > a: pass
TASKS Write a program that takes an integer input and prints "positive number" only if the number is greater than 0. Write a program that checks if a given number is even or odd. Input: any integer Output: "Even" or "Odd“ 3. Write a program that takes a number between 0 and 100 and assigns a grade: 90 and above: Grade A 75 to 89: Grade B 50 to 74: Grade C Below 50: Grade F Use Short Hand, f-string
4. Write a program to check if a character input is a letter. If it’s a letter, check if it’s uppercase or lowercase else, print "not a letter“. isdigit (), isalpha (), isupper (), islower () 5. Write a program that checks whether a number is divisible by both 3 and 5. If yes, print "Divisible by both“ If only one matches, print "Divisible by 3" or "Divisible by 5“ If neither, print "Not divisible by 3 or 5" Use Short Hand, f-string
TOPIC 6 - BRANCHING
Branching in python refers to the use of conditional statements to control the flow of a program based on certain conditions. It allows the program to make decisions and execute specific blocks of code depending on the situation.
MATCH STATEMENT The match statement in python, introduced in python 3.10 , is a powerful feature for pattern matching . It allows you to write cleaner and more readable conditional logic compared to multiple if- elif -else statements.
Key Points match Keyword : Specifies the variable to be matched. case Keyword : Defines patterns to match against the variable. Wildcard _ : Acts as a default case if no other patterns match.
Example 1: Simple Matching
Example 2: Matching With Conditions
TASK Write a python program using the match statement to classify a number as: "positive" if the number is greater than 0, "negative" if the number is less than 0, or "zero" if the number is equal to 0.
TOPIC 7 - LOOPING
Loops in python are used to repeat actions efficiently. The main types are for loops (counting through items) and while loops (based on conditions). For loop in python For loops is used to iterate over a sequence such as a list, tuple, string or range. It allow to execute a block of code repeatedly, once for each item in the sequence. Syntax: for iterator_var in sequence: statements(s)
for x in "banana" : print (x)
fruits = [ "apple" , "banana" , "cherry" ] for x in fruits: print (x)
The range() function To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. for x in range ( 2 , 6 ): print (x)
The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3 ) : for x in range ( 2 , 30 , 3 ): print (x)
Printing in single row (with space) Printing in single row (without space)
Else in For Loop The else keyword in a for loop specifies a block of code to be executed when the loop is finished : for x in range ( 6 ): print (x) else : print ( "finally finished!" )
The break Statement With the break statement we can stop the loop before it has looped through all the items : fruits = [ "apple" , "banana" , "cherry" ] for x in fruits: print (x) if x == "banana" : break apple banana
Exit the loop when x is "banana ", but this time the break comes before the print: fruits = [ "apple" , "banana" , "cherry" ] for x in fruits: if x == "banana" : break print (x) apple
The else block will NOT be executed if the loop is stopped by a break statement. for x in range ( 6 ): if x == 3 : break print (x) else : print ( "finally finished!" )
The continue Statement With the continue statement we can stop the current iteration of the loop, and continue with the next : fruits = [ "apple" , "banana" , "cherry" ] for x in fruits: if x == "banana" : continue print (x) apple cherry
Nested Loops A nested loop is a loop inside a loop . The " inner loop" will be executed one time for each iteration of the "outer loop“.
adj = [ "red" , "big" , "tasty" ] fruits = [ "apple" , "banana" , "cherry" ] for x in adj: for y in fruits: print (x, y) red apple red banana red cherry big apple big banana big cherry tasty apple tasty banana tasty cherry
While Loop in Python In python, a while loop is used to execute a block of statements repeatedly until a given condition is satisfied . When the condition becomes false, the line immediately after the loop in the program is executed. Syntax: while expression: statement(s)
i = 1 1 2 3 4 5 while i < 6 : print (i) i += 1 With the break statement we can stop the loop even if the while condition is true: i = 1 while i < 6 : print ( i ) if i == 3 : break i += 1 1 2 3 4 5 1 2 3
With the continue statement we can stop the current iteration, and continue with the next: i = while i < 6 : i += 1 if i == 3 : continue print ( i ) 1 2 4 5 6
With the else statement we can run a block of code once when the condition no longer is true: i = 1 while i < 6 : print ( i ) i += 1 else : print ( " i is no longer less than 6" ) 1 2 3 4 5 i is no longer less than 6
NESTED WHILE LOOP The syntax for a nested while loop statement in the python programming language is as follows: while expression: while expression: statement(s) statement(s)
TASKS 1. Print numbers from 1 to 10 using a for loop hint: use range() and print() 2. Find the sum of all even numbers between 1 and 50 write a loop to check for even numbers and accumulate their total. 3. Create a right-angled triangle pattern using * characters example output: * ** *** **** *****
4. Print a multiplication table from 1 to 5 expected output: 1 x 1 = 1 1 x 2 = 2 ... 5 x 5 = 25 5. Keep asking the user to enter a number until they enter 0 Use a while loop and input() to repeat until the condition is met.
for i in range(1, 11): print( i ) for i in range(1, 11): print( i , end=" ") for i in range(1, 11): print( i , "\n") total = for i in range ( 1 , 51 ): if i % 2 == : # check if even total += i # add to total print ( "Sum of even numbers from 1 to 50 is:" , total) total = 0 i = 1 while i <= 50: if i % 2 == 0: # check if even total += i i += 1 # move to next number print("Sum of even numbers from 1 to 50 is:", total)
i = 1 while i <= 5: print("*" * i ) i += 1 for i in range(1, 6): # rows from 1 to 5 print("*" * i ) for i in range ( 1 , 6 ): for j in range ( 1 , 6 ): print ( f " { i } x {j} = { i * j} " ) i = 1 while i <= 5: j = 1 while j <= 5: print(f"{ i } x {j} = { i * j}") j += 1 i += 1
num = int ( input ( "Enter a number (0 to stop): " )) while num != : print ( f "You entered: {num} " ) num = int ( input ( "Enter a number (0 to stop): " )) print ( "You entered 0. Program stopped." ) for _ in iter(int, 1): # infinite loop trick