0% found this document useful (0 votes)
13 views21 pages

Python Control Flow Basics

Uploaded by

mckels443
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)
13 views21 pages

Python Control Flow Basics

Uploaded by

mckels443
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

Fundamentals of Programming

Full Set of Exercises - 2

Objectives
By the end of this module, you should be able to:

• Implement conditional statements using if, elif, and else.


• Use loops (for, while) to repeat tasks effectively.
• Control the flow of loops with break, continue.
• Apply nesting (placing one control structure inside another).

Expected Outcomes
- Write simple Python programs using the concepts above.
- Understand how control flow works in Python.
- Debug basic syntax and logical errors.

Theory Summary
1. Conditional Statements in Python

Conditional Statements in Python performs different computations or actions depending on


conditions.

In python, the following are conditional statements

• if

• if – else

• if – elif –else

Indentation in Python:

For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.

Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.
Indentation is the most used part of the python language since it declares the block of code. All
the statements of one block are intended at the same level indentation.

If statement in Python

The if statement is used to test a specific condition. If the condition is true, a block of code (if-
block) will be executed.

if expression:

statement

Example:

a = 33
b = 200
if b > a:
print ("b is greater than a")
Output:

b is greater than a
If – else statement in Python

The if-else statement provides an else block combined with the if statement which is executed in
the false case of the condition.
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

if expression:
#block of statements
else:
#another block of statements
Example:

age = int (input("Enter your age : "))


if age >= 18:
print("You are eligible to vote !!")
else:
print("Sorry! you have to wait !!")
Output:

Enter your age: 19


You are eligible to vote!!
If – elif - else statement in Python

The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them.
We can have any number of elif statements in our program depending upon our need. However,
using elif is optional.

if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example:

marks = int(input("Enter the marks :"))


if marks > 85 and marks <= 100:
print("Congrats! you scored grade A..")
elif marks > 60 and marks <= 85:
print("You scored grade B + ..")
elif marks > 40 and marks <= 60:
print("You scored grade B ..")
elif (marks > 30 and marks <= 40):
print("You scored grade C ..")
else:
print("Sorry you are fail ?")
Output:

Enter the marks: 70


You scored grade B +.
Example:

a=int(input("Enter a value : "))


b=int(input("Enter b value : "))
c=int(input("Enter c value : "))
if (a>b) and (a>c):
print("Maximum value is :",a)
elif (b>c):
print("Maximum value is :",b)
else:
print("Maximum value is :",c)
Output:

Enter a value: 10
Enter b value: 14
Enter c value: 9
Maximum value is: 14

2. Loop Statements in Python


Sometimes we may need to alter the flow of the program. If the execution of a specific code
may need to be repeated several numbers of times then we can go for loop statements.

For this purpose, the python provide various types of loops which are capable of repeating some
specific code several numbers of times. Those are,
• while loop
• for loop
while loop in Python
With the while loop we can execute a set of statements as long as a condition is true. The while
loop is mostly used in the case where the number of iterations is not known in advance.

while expression:
Statement(s)
Example:

i=1
while i<=3:
print(i)
i=i+1
Output:

1
2
3

Using else with while loop


Python enables us to use the while loop with the else block also. The else block is executed when
the condition given in the while statement becomes false.

while expression:
Statements
else:
Statements

Example:

i=1
while i<=3:
print (i)
i=i+1
else: print("The while loop terminated")

Output:

1
2
3
The while loop terminated
The for loop in Python is used to iterate the statements or a part of the program several times. It is
frequently used to traverse the data structures like list, tuple, or dictionary.

for iterating_var in sequence:


statement(s)
Example:

i=1
n=int(input("Enter n value : "))
for i in range(i,n+1):
print(i,end = ' ')
Output:

Enter n value: 5
12345

Python allows us to use the else statement with the for loop which can be executed only when all
the iterations are exhausted. Here, we must notice that if the loop contains any of the break
statement then the else statement will not be executed.

for iterating_var in sequence:


statements
else:
statements
Example:

for i in range(0,5):
print(i)
else:
print("for loop completely exhausted")
Output:

0
1
2
3
4
for loop completely exhausted
Note
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.

Example:

range(6) means the values from 0 to 5.


range(2,6) means the values from 2 to 5.

Example:

i=1;
num = int(input("Enter a number:"));
for i in range(1,11):
print("%d X %d = %d"%(num,i,num*i))

Output:

Enter a number: 10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100

Nested for loop in python

Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n
number of times for every iteration of the outer loop.

Syntax:
for iterating_var1 in sequence:

for iterating_var2 in sequence:


#block of statements

Example:

n = int(input("Enter the [Link] rows you want to print : "))


for i in range(0,n):
for j in range(0,i+1):
print("*",end="")
print()
Output:

Enter the [Link] rows you want to print: 4


*
**
***
****

Break & Continue statements in Python

break statement:
The break is a keyword in python which is used to bring the program control out of the loop. The
break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner
loop first and then proceeds to outer loops. In other words, we can say that break is used to abort
the current execution of the program and the control goes to the next line after the loop.

Syntax:
break

Example:

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output:

1
2
3
Example:

nsum = 0
count = 0
for count in range(10):
nsum = nsum + count
if count== 6:
break
print("Sum of first 6 Numbers is: ", nsum)
Output:

Sum of first 6 Numbers is: 21


continue statement:

The continue statement skips the remaining lines of code inside the loop and start with the next
iteration. It is mainly used for a particular condition inside the loop so that we can skip some
specific code for a particular [Link] other words, The continue statement in python is used
to bring the program control to the beginning of the loop.

Syntax:
continue

Example:

str1 = input("Enter any String : ")


for i in str1:
if i == 'h':
continue;
print(i,end=" ");
Output:

Enter any String: python


pyton
Example:

num = 0
print("Odd numbers in between 1 to 10")
while(num < 10):
num = num + 1
if (num % 2) == 0:
continue
print(num)
Output:

Odd numbers in between 1 to 10


1
3
5
7
9
Practical Exercises
1) Password Strength Audit (loops, break/continue, nesting)
Problem
Read a password string. Classify as 'STRONG' if it has length ≥ 12, and contains at least one
lowercase, one uppercase, one digit, and one symbol from !@#$%^&*_.
If any criterion is missing, print which are missing. Use loops with break/continue and nested ifs.

Algorithmic Solution
Initialize four booleans: lowercase/uppercase/digit/symbol. Keep symbols set/string for O(1)
membership.
Scan once with for ch in pwd:
• Use nested ifs to test categories; after a match, continue to avoid extra checks for that
character.
After loop, construct a list of missing criteria:
• length ≥ 12, and each category flag.
If the list is empty → STRONG; else WEAK: <missing...>.

Why continue: cuts unnecessary checks per char, demonstrating control flow.

Edge cases: empty string, Unicode letters outside ASCII ranges (your checks target ASCII),
repeated symbols, very long input.

Complexity: O(n).

Python Code
pwd = input("Password: ")

has_low = has_up = has_digit = has_sym = False


symbols = "!@#$%^&*_"
for ch in pwd:
if 'a' <= ch <= 'z':
has_low = True
continue
if 'A' <= ch <= 'Z':
has_up = True
continue
if '0' <= ch <= '9':
has_digit = True
continue
if ch in symbols:
has_sym = True

missing = []
if len(pwd) < 12:
[Link]("length>=12")
if not has_low: [Link]("lowercase")
if not has_up: [Link]("uppercase")
if not has_digit: [Link]("digit")
if not has_sym: [Link]("symbol")

if not missing:
print("STRONG")
else:
print("WEAK: ".join(missing))

2) The Password Retry Gatekeeper


Problem
A secure system requires users to enter a password to gain access. However, to prevent brute-
force attacks, the system only allows three attempts. If the correct password is entered within
those attempts, access is granted. Otherwise, the system locks the user out.
The correct password is "OpenSesame".

Algorithmic Solution
• Set the correct password.
• Initialize an attempt counter to 0.
• While the number of attempts is less than 3:
o Prompt the user to enter a password.
o If the password is correct → print "Access granted" and break the loop.
o Else → print "Incorrect password" and increment the attempt counter.
• If the loop ends without success → print "Account locked".

Python Code

correct_password = "OpenSesame"
attempts = 0

while attempts < 3:


entered = input("Enter password: ")
if entered == correct_password:
print("Access granted.")
break
else:
print("Incorrect password.")
attempts += 1
if attempts == 3:
print("Account locked.")
3) The Prime Number Finder in a Range
Problem

A mathematician is studying prime numbers and wants a tool that can find all the prime numbers
within a given range. The user will input two integers: a starting number and an ending number.
The program should then print all the prime numbers in that range.

To determine if a number is prime, the program must check if it is divisible by any number other
than 1 and itself. This requires a nested loop: one loop to iterate through the range, and another to
check for divisibility.

Algorithmic Solution
• Read the starting and ending numbers.
• For each number n in the range from start to end:
o If n is less than 2 → skip (not prime).
o Else:
▪ Use a loop to check if n is divisible by any number from 2 to n-1.
▪ If divisible → not prime.
▪ If not divisible by any → prime.
• Print all prime numbers found.

Python Code

start = int(input("Enter start of range: "))


end = int(input("Enter end of range: "))
print("Prime numbers in the range:")
for n in range(start, end + 1):
if n < 2:
continue
is_prime = True
for i in range(2, n):
if n % i == 0:
is_prime = False
break
if is_prime:
print(n)

4) The ATM Withdrawal Simulator


Problem

An ATM allows users to withdraw money from their account, but only if they have enough
balance. The user can make multiple withdrawals until they either run out of money or choose to
stop.
The ATM starts with a balance of €500.
Algorithmic Solution
- Set the initial balance to 500.
- While the balance is greater than 0:
o Ask the user how much they want to withdraw.
o If the amount is greater than the balance → print "Insufficient funds".
o Else → subtract the amount and print the new balance.
o Ask if the user wants to continue. If not, break the loop.
- If balance reaches 0 → print "No funds remaining".

Python Code

balance = 500
while balance > 0:
amount = float(input("Enter withdrawal amount: "))
if amount > balance:
print("Insufficient funds.")
else:
balance -= amount
print(f"New balance: €{balance:.2f}")

cont = input("Do you want to continue? (yes/no): ").strip().lower()


if cont != "yes":
break
if balance == 0:
print("No funds remaining.")

5) The Student Score Tracker with Statistics


Problem

A teacher wants to track the scores of students in a class. The number of students is not known in
advance. The teacher will enter scores one by one, and when finished, will type -1 to stop. The
program should then calculate and display:

• The total number of students


• The highest score
• The lowest score
• The average score

Only valid scores between 0 and 100 should be accepted. If an invalid score is entered, the
program should display an error and ask again.

Algorithmic Solution
Initialize variables: count, total, max_score, min_score.
While True:
- Read a score.
- If score is -1 → break the loop.
- If score is not in [0, 100] → print error and continue.
- Else:
- Add to total.
- Increment count.
- Update max and min if needed.
After the loop:
- If count > 0 → compute and print average, max, min, and count.
- Else → print "No valid scores entered".

Python Code
count = 0
total = 0
max_score = None
min_score = None
while True:
score = int(input("Enter student score (0–100) or -1 to finish: "))
if score == -1:
break
if score < 0 or score > 100:
print("Invalid score. Please enter a value between 0 and 100.")
continue
total += score
count += 1
if max_score is None or score > max_score:
max_score = score
if min_score is None or score < min_score:
min_score = score
if count > 0:
average = total / count
print(f"Total students: {count}")
print(f"Highest score: {max_score}")
print(f"Lowest score: {min_score}")
print(f"Average score: {average:.2f}")
else:
print("No valid scores entered.")

6) Pascal's Triangle
Problem

A teacher wants to display Pascal’s Triangle up to n rows. Each number is the sum of the two
numbers directly above it. Write a program that prints Pascal’s Triangle using nested loops
Algorithmic Solution
1. Read the number of rows n.
2. Use a loop to generate each row.
3. Use a nested loop to compute binomial coefficients using factorials.
4. Print each row with proper spacing.

Python Code

import math
n = int(input("Enter number of rows: "))
for i in range(n):
row = []
for j in range(i+1):
val = [Link](i, j)
[Link](str(val))
print(" "*(n-i) + " ".join(row))

7) Word Frequency Counter


Problem

A linguist wants to analyze the frequency of each word in a paragraph. Write a program that reads
a paragraph and prints each word and its frequency using a for-each loop.

Algorithmic Solution:

1. Read a paragraph and split it into words.


2. Use a dictionary to count occurrences.
3. Use a for-each loop to iterate over the words.
4. Print each word and its count.

Python Code:

text = input("Enter a paragraph: ")


words = [Link]().split()
freq = {}
for word in words:
freq[word] = [Link](word, 0) + 1

for word, count in [Link]():


print(f"{word}: {count}")

8) Matrix Transposition
Problem
A data scientist wants to transpose a matrix (swap rows and columns). Write a program that reads
a matrix and prints its transpose using nested loops.

Algorithmic Solution:

1. Read matrix dimensions and elements.


2. Store the matrix in a list of lists.
3. Use nested loops to print the transposed matrix.

Python Code:

rows = int(input("Enter number of rows: "))


cols = int(input("Enter number of columns: "))
matrix = []
for i in range(rows):
row = list(map(int, input(f"Enter row {i+1}: ").split()))
[Link](row)

print("Transposed matrix:")
for j in range(cols):
for i in range(rows):
print(matrix[i][j], end=" ")
print()

9) Elevator Simulator (if/elif/else, loop state)


Problem
Simulate an elevator given commands on separate lines until 'STOP'. Commands: UP n, DOWN
n, OPEN, CLOSE. Elevator cannot move with doors OPEN. Track current floor (start 0), door
state, and the highest floor reached. Print final floor, door state, and highest floor. Use while with
nested conditionals.

Algorithmic Solution:

State: floor=0, door_open=False, highest=0.


Read commands until "STOP".
Parse each line:
• OPEN → door_open=True
• CLOSE → door_open=False
• UP n / DOWN n:
o If door_open: ignore move (continue) to model invalid action.
o Else apply floor += n or floor -= n.
o After UP, update highest = max(highest, floor).
• Unknown command: ignore (or log).
Why nested conditionals: validate move only under correct door state.
Edge cases: negative n, fractional n (reject/parse int), downward movement below a minimum
floor (decide whether allowed).
Python Code
floor = 0
door_open = False
highest = 0

while True:
cmd = input().strip()
if cmd == "STOP":
break
parts = [Link]()
if not parts:
continue
verb = parts[0]
if verb == "OPEN":
door_open = True
elif verb == "CLOSE":
door_open = False
elif verb == "UP" and len(parts) == 2:
n = int(parts[1])
if door_open:
# cannot move
continue
floor += n
if floor > highest: highest = floor
elif verb == "DOWN" and len(parts) == 2:
n = int(parts[1])
if door_open:
continue
floor -= n
else:
# unknown command
pass
print(floor)
print("OPEN" if door_open else "CLOSE")
print(highest)

10) CSV Field Validator (loops, continue)


Problem
Read a single line of comma-separated fields. A field is valid if it's non-empty and has no spaces
at ends. Print the count of valid fields and the index (0-based) of the first invalid field, or -1 if all
valid.

Algorithmic Solution:

• Split on commas to fields.


• Initialize valid_count=0, first_invalid=-1.
• For each field f with index i:
• If f == "": set first_invalid if not set; continue.
• If f != [Link](): leading/trailing spaces → mark invalid; continue.
• Otherwise increment valid_count.
• After loop, print the count and first_invalid.
Why continue: once a field is known invalid, skip further checks cleanly.

Edge cases: consecutive commas (empty fields), trailing comma, fields containing internal
spaces (allowed).

Complexity: O(total chars).

Python Code
line = input("csv: ")
fields = [Link](',')
valid_count = 0
first_invalid = -1

for i, f in enumerate(fields):
if f == "":
first_invalid = i if first_invalid == -1 else first_invalid
continue
if f != [Link]():
first_invalid = i if first_invalid == -1 else first_invalid
continue
valid_count += 1

print(valid_count)
print(first_invalid)

11) Greedy Coin Change (descending for-loop, break)


Problem
Given an amount in cents, compute the minimum number of coins using denominations [100, 50,
20, 10, 5, 2, 1]. Use a descending for-loop over denominations, with division and remainder, and
break early if remainder becomes 0. Print total coins and counts per denomination.

Algorithmic Solution:

Denominations sorted desc: [100, 50, 20, 10, 5, 2, 1].


Remainder rem = amount. For each denom d:
• Take cnt = rem // d, store counts[i] = cnt.
• Update rem %= d.
• If rem == 0: break to avoid extra work.
Sum counts for total coins; print per-denomination counts for transparency.
Why greedy works: this set is canonical; greedy yields optimal solution.

Edge cases: amount = 0, negative amounts (reject), very large amounts.


Complexity: O(#denoms) ≈ O(1).

Python Code
amount = int(input("amount (cents): "))
denoms = [100, 50, 20, 10, 5, 2, 1]
counts = [0]*len(denoms)
rem = amount
for i, d in enumerate(denoms):
if rem == 0:
break
cnt = rem // d
counts[i] = cnt
rem = rem % d

print(sum(counts))
print(" ".join(str(x) for x in counts))

12) Sliding Window Average (while, two pointers)


Problem
Read a list of integers and a window size k. Compute the maximum average of any contiguous
window of size k. Use a while-loop maintaining a running sum with two pointers (start/end). Print
the best average.

Algorithmic Solution:

Validate 1 ≤ k ≤ n.
Compute sum of first k elements; set it as best.
Maintain window with two pointers: start (leaving element) and end (next entering index).
While end < n:
o cur_sum -= arr[start]
o cur_sum += arr[end]
o Update best if cur_sum > best
o start += 1, end += 1
Final answer is best / k.
Why two pointers + while: constant-time updates per step; demonstrates pointer movement.

Edge cases: negative numbers (works), k=1 (max element), k=n (average of entire array).

Complexity: O(n).

Python Code
arr = [int(x) for x in input("nums: ").split()]
k = int(input("k: "))
n = len(arr)
if k <= 0 or k > n:
print("Invalid k")
else:
cur_sum = 0
for i in range(k):
cur_sum += arr[i]
best = cur_sum
start = 0
end = k
while end < n:
cur_sum -= arr[start]
cur_sum += arr[end]
if cur_sum > best:
best = cur_sum
start += 1
end += 1
print(best / k)

13) Temperature Converter


Problem
You are building a temperature converter. By default, it converts Celsius to Fahrenheit. But the
user can choose to convert Fahrenheit to Celsius instead.

Algorithmic Solution:

• Define a function convert_temp(value, to_celsius=False).


• If to_celsius is True, convert using (F - 32) * 5/9.
• Else, convert using C * 9/5 + 32.

Python Code

def convert_temp(value, to_celsius=False):


if to_celsius:
return (value - 32) * 5 / 9
else:
return value * 9 / 5 + 32

print("C to F:", convert_temp(25))


print("F to C:", convert_temp(77, to_celsius=True))

14) Matrix Multiplication

Problem

In linear algebra, multiplying two matrices is a fundamental operation with applications in


computer graphics, machine learning, and data analysis. For two matrices A of size m × n and B
of size n × p, their product C = A × B will be a matrix of size m × p. The element at position
C[i][j] is computed as the dot product of the i-th row of A with the j-th column of B.
The operation is only valid if the number of columns of A equals the number of rows of B.

Algorithmic Solution

1. Input the dimensions and elements of matrix A (m × n).


2. Input the dimensions and elements of matrix B (n × p).
3. Verify that the number of columns of A equals the number of rows of B; otherwise, the
multiplication is invalid.
4. Initialize a result matrix C of size m × p with zeros.
5. For each row index i in A (0 to m−1):
o For each column index j in B (0 to p−1):
▪ Initialize sum = 0.
▪ For each index k from 0 to n−1:
▪ Multiply A[i][k] * B[k][j] and add to sum.
▪ Store the computed sum in C[i][j].
6. Output the resulting matrix C.

Python Code

# Matrix Multiplication in Python


# Input dimensions
m = int(input("Enter number of rows of Matrix A: "))
n = int(input("Enter number of columns of Matrix A: "))
p = int(input("Enter number of columns of Matrix B: "))

# Matrix A input
print("Enter elements of Matrix A row by row:")
A = []
for i in range(m):
row = []
for j in range(n):
val = int(input(f"A[{i+1}][{j+1}]: "))
[Link](val)
[Link](row)

# Matrix B input
print("Enter elements of Matrix B row by row:")
B = []
for i in range(n):
row = []
for j in range(p):
val = int(input(f"B[{i+1}][{j+1}]: "))
[Link](val)
[Link](row)

# Check validity
if len(A[0]) != len(B):
print("Matrix multiplication not possible. Columns of A must equal
rows of B.")
else:
# Initialize result matrix with zeros
C = [[0 for _ in range(p)] for _ in range(m)]
# Perform multiplication
for i in range(m):
for j in range(p):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]

# Display result
print("\nResultant Matrix C (A × B):")
for row in C:
print(row)

You might also like