0% found this document useful (0 votes)
2 views56 pages

Computer Programming: Conditionals & Iterations

python

Uploaded by

workubikila765
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 views56 pages

Computer Programming: Conditionals & Iterations

python

Uploaded by

workubikila765
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

Computer Programming

Conditionals and Iterations

Eyob S.

SITE, AAiT

April 23, 2025

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 1 / 56


Table of Contents

1 Algorithm

2 Boolean Expressions

3 Types of Program Execution

4 Conditionals

5 Iterations

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 2 / 56


Algorithm

Algorithm

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 3 / 56


What is an Algorithm?

An algorithm is a set of well-defined instructions that, when followed


step-by-step, solves a specific problem or accomplishes a task.

It provides a clear and concise recipe for achieving a desired outcome.

Key characteristics of algorithms: Finiteness, Unambiguity, Effective-


ness, Generality

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 4 / 56


What is an Algorithm? (continued...

Finiteness: The algorithm has a finite number of steps.

Unambiguity: Each step has a clear and unambiguous meaning.

Effectiveness: The algorithm can be followed to complete the task


in a finite amount of time.

Generality: The algorithm can be applied to a range of inputs within


the intended problem domain.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 5 / 56


Algorithm Representation: Natural Language

Describing an algorithm in natural language uses plain, everyday


language.

It is the least formal representation and is intended for easy understand-


ing by non-technical audiences.

Exercise: Write an algorithm to find the Maximum Number in a List


using Natural Language.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 6 / 56


Example

1. Start by assuming the first number in the list is the largest.

2. Look at each number in the list one by one.

3. If you find a number that is larger than your current largest number,
update the largest number.

4. After checking all the numbers, the current largest number is the
maximum.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 7 / 56


Algorithm Representation: Pseudocode

Pseudocode: is a high-level description of an algorithm using the


structural conventions of programming languages.

It focuses on the algorithm’s logic without delving into language-specific


syntax.

Pseudocode is easy to read and understand, making it a good bridge


between human logic and programming code.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 8 / 56


Example

Algorithm FindMax(A)
1. max_value := A[0]
2. for each element num in A do
3. if num > max_value then
4. max_value := num
5. return max_value

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 9 / 56


Algorithm Representation: Flowchart

A flowchart is a graphical representation of an algorithm.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 10 / 56


Algorithm Practice Questions

Write an algorithm that will solve the following problems using a flowchart.

1. Determine if a given number is even or odd.

2. Check if a given number is a prime number.

3. Find the sum of all numbers in a given list.

4. Calculate the factorial of a given number

5. Find the maximum number in a given list of numbers.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 11 / 56


Algorithm Practice Questions

Write an algorithm that will solve the following problems using a flowchart.

6. Generate the first n numbers in the Fibonacci sequence.

7. Reverse a given string.

8. Find the GCD of two given numbers using Euclid’s algorithm.

9. Calculate the average of numbers in a given list.

10. Count the number of vowels in a given string.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 12 / 56


Assignment

Write an algorithm that will solve the following problems using a flowchart.

1. Convert a temperature from Celsius to Fahrenheit.

2. Check if a given string is a palindrome.

3. Calculate the power of a number given the base and exponent.

4. Find the smallest number in a given list of numbers.

5. Count the number of consonants in a given string.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 13 / 56


Boolean Expressions

Boolean Expressions

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 14 / 56


Boolean Expressions

A boolean expression is an expression that is either true or false.

True and False are special values that belong to the type bool; they
are not strings:

type(True), type(False)

Some languages use 0 or 1, Others have a data type

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 15 / 56


Comparison Operators in Python

Operator Description Example


== Equal to x == y
!= Not equal to x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Table: Comparison Operators

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 16 / 56


Logical Operators in Python

Operator Description Example


and Logical AND x and y
or Logical OR x or y
not Logical NOT not x
Table: Logical Operators

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 17 / 56


Operator Precedence in Python

Precedence Operator
1 **
2 +x, -x, ~x
3 *, /, //, %
4 +, -
5 ==, !=, >, <, >=, <=
6 not
7 and
8 or
Table: Operator Precedence in Python

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 18 / 56


Examples

2 < 3 ⇒ ???

7 - 1 >= 2 * 3 ⇒ ???

3 == 4 + 4 ⇒ ???

2 != 3 ⇒ ???

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 19 / 56


Truth Table for Logical Operators

A B A or B A and B
A not A true true true true
true false true false true false
false true false true true false
false false false false
Table: Truth Table for Logical Operators

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 20 / 56


Examples

2 < 3 and 4 > 5 ⇒ ???

2 < 3 and True ⇒ ???

False or True and False ⇒ ???

3 >= -1 or 8*2 > 2**4 and 9 !=3 ⇒ ???

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 21 / 56


Examples

-2**2 ⇒ ???

4 % 2 == 0 ⇒ ???

4 % 3 == 1 ⇒ ???

0 and False ⇒ ???

0 and True ⇒ ???

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 22 / 56


Examples

1 and True ⇒ ???

1 and False ⇒ ???

5 and True ⇒ ???

5 and False ⇒ ???

0 or True ⇒ ???

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 23 / 56


Examples

0 or False ⇒ ???

1 or True ⇒ ???

1 or False ⇒ ???

4 or False ⇒ ???

4 or True ⇒ ???

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 24 / 56


Examples

1 == True ⇒ ???

2 == True ⇒ ???

-1 == True ⇒ ???

0 == False ⇒ ???

-0 == False ⇒ ???

1 == False ⇒ ???

5 == False ⇒ ???

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 25 / 56


Types of Program Execution

Types of Program Execution

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 26 / 56


Types of Program Execution

There are three main types of program execution:

Sequential

Branching (Conditional)

Repetition (Looping)

Understanding these types helps in structuring and writing efficient


programs.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 27 / 56


Sequential Execution

In sequential execution, statements are executed one after another in


the order they appear.

Each statement is executed exactly once.

Example:
x = 5
y = 10
z = x + y
print(z)

The output of the above code will be 15.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 28 / 56


Branching

Branching allows the program to make decisions and execute different


code paths based on conditions.

Uses conditional statements like ‘if‘, ‘else if‘, and ‘else‘.

Example:
if x > y:
print("x is greater than y")
elif x < y:
print("x is less than y")
else:
print("x is equal to y")

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 29 / 56


Repetition

Repetition allows the program to execute a block of code multiple


times.

Uses loops like ‘for‘ and ‘while‘.

Example:
for i in range(5):
print(i)

This will print numbers 0 to 4.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 30 / 56


Conditionals

Conditionals

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 31 / 56


Conditional Statements

Conditional statements allow the program to make decisions based on


certain conditions.

Basic syntax uses ‘if‘, ‘elif‘, and ‘else‘.

if condition:
# execute this block if the condition is true

if condition:
# execute this block if condition is true
else:
# execute this block if condition is false

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 32 / 56


Practice Questions

1. Check if a number is positive.

2. Check if a first number is divisible by a second number.

3. Determine if a character in a string is a vowel.

4. Check if a number is even or odd.

5. Determine if a person is eligible to vote (age 18 or older).

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 33 / 56


Chained Conditionals

Chained conditionals use multiple ‘if‘, ‘elif‘, and ‘else‘ statements to


handle multiple conditions.

if x > y:
print("x is greater than y")
elif x < y:
print("x is less than y")
else:
print("x is equal to y")

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 34 / 56


Practice Questions

1. Classify a number as positive, negative, or zero.

2. Determine the grade of a student based on their score:

A for 90-100
B for 80-89
C for 70-79
D for 60-69
F for below 60

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 35 / 56


Nested Conditionals

Nested conditionals are conditionals within other conditionals.

Useful for complex decision-making.

Indentation is important to maintain clarity and correctness.

if x > 0:
if x > y:
print("x is positive & greater than y")
else:
print("x is positive & less than or equal to y")
else:
print("x is not positive")

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 36 / 56


Practice Questions

1. Write a program to determine if a given year is a leap year.


Hint: A year is a leap year if the year is divisible by 4. However, if
the year is divisible by 100, it is not a leap year unless the year is
also divisible by 400.

2. Check if a point (x, y ) lies in the first, second, third, or fourth


quadrant of a coordinate system.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 37 / 56


Common Errors

if((Value > 0) or (Value <= 10)):


print(Value)

if((Value > 0) and (Value <= 10)):


print(Value)

if((Value < 0) and (Value > 10)):


print(Value)

if((1.11 - 1.10) == (2.11 - 2.10)):


print('done')

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 38 / 56


Iterations

Iterations

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 39 / 56


Iterations in Programming

Iterations allow the execution of a block of code multiple times.

There are different types of loops used for iteration:

For Loops

While Loops

Nested Loops

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 40 / 56


For Loops

For loops are used to iterate over a sequence (e.g., list, tuple, range,
string).

Syntax:

for variable in sequence:


# execute this block

Example:
for i in range(5):
print(i)

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 41 / 56


While Loops

While loops are used to execute a block of code as long as a condition


is true.

Syntax:

while condition:
# execute this block

Example:
count = 0
while count < 5:
print(count)
count += 1

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 42 / 56


Nested Loops

Nested loops are loops within loops.

Each time the outer loop is executed, the inner loop runs to completion.

Example:
for i in range(3):
for j in range(2):
print(i, j)

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 43 / 56


Practice Questions: For Loops

1. Print the first 10 natural numbers.

2. Calculate the sum of all elements in a list.

3. Print each character of a string on a new line.

4. Find the factorial of a given number.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 44 / 56


Practice Questions: While Loops

1. Print numbers from 1 to 10 using a while loop.

2. Keep accepting user input until they enter ’exit’.

3. Calculate the sum of digits of a given number.

4. Find the greatest common divisor (GCD) of two numbers.

5. Simulate a countdown from 10 to 0.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 45 / 56


Practice Questions: Nested Loops

Print a 5x5 multiplication table.

Print the following pattern:

*
**
***
****
*****
******

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 46 / 56


Break Statement

The ‘break‘ statement is used to exit a loop prematurely.

It can be used in both ‘for‘ and ‘while‘ loops.

for i in range(10):
if i == 5:
break
print(i)

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 47 / 56


Continue Statement

The ‘continue‘ statement skips the current iteration of a loop and


moves to the next iteration.

It can be used in both ‘for‘ and ‘while‘ loops.

for i in range(10):
if i % 2 == 0:
continue
print(i)

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 48 / 56


Pass Statement

The ‘pass‘ statement is a null operation; nothing happens when it


executes.

It is used as a placeholder in loops, functions, classes, or conditionals.

for i in range(10):
if i % 2 == 0:
pass # Placeholder for future code
else:
print(i)

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 49 / 56


Infinite Loops

An infinite loop runs indefinitely because the terminating condition is


never met.

Use with caution to avoid unintentional infinite execution.

while True:
print("This is an infinite loop")
# Use break statement to exit the loop

Press ‘Ctrl+C‘ to stop the execution manually.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 50 / 56


Unintentional Infinite Loops

x = 10
while(x > 0):
x += 1

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 51 / 56


Off-By-One Error

An Off-By-One Error (OBOE) occurs when an iterative loop iterates


one more time or one less time.

Commonly occurs in loops when the loop counter or index is off by


one.

Often happens in:

Array indexing
Loop boundaries (e.g., starting at 0 instead of 1 or vice versa)
Calculating lengths (e.g., forgetting to include or exclude the last
element)

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 52 / 56


Off-By-One Error

# Incorrect loop
for i in range(1, 11):
print(i)

# Correct loop
for i in range(10):
print(i)

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 53 / 56


Sentinel Loop

A Sentinel Loop continues to process data until a special value, known


as a sentinel value, is encountered.

The sentinel value is not a valid data value but is used to signal the
end of the loop.

Commonly used in scenarios where the number of iterations is not


known in advance.

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 54 / 56


Sentinel Loop

sentinel = -1
number = 0
sum = 0

while number != sentinel:


number = int(input("Enter a number (-1 to stop): "))
if number != sentinel:
sum += number

print(f"Sum of numbers: {sum}")

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 55 / 56


END

Thank You!!!

Eyob S. (SITE, AAiT) Computer Programming April 23, 2025 56 / 56

You might also like