0% found this document useful (0 votes)
4 views38 pages

Lecture3 Object Oriented Programming Python

The document provides an overview of Object Oriented Programming in Python, focusing on control structures such as conditional statements, loops, and branching statements. It explains various control flow constructs like if, if-else, elif, nested if statements, and loops (for and while), along with practical examples. Additionally, it covers logical operators and exercises for practical understanding, including a leap year checker and palindrome checker.

Uploaded by

sog.gregoy
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)
4 views38 pages

Lecture3 Object Oriented Programming Python

The document provides an overview of Object Oriented Programming in Python, focusing on control structures such as conditional statements, loops, and branching statements. It explains various control flow constructs like if, if-else, elif, nested if statements, and loops (for and while), along with practical examples. Additionally, it covers logical operators and exercises for practical understanding, including a leap year checker and palindrome checker.

Uploaded by

sog.gregoy
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

Object Oriented Programming(Python)

Emmanuel Ali(PhD)

March 22, 2026

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 1 / 38


Outline

1 Control Structures

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 2 / 38


Control structures

Control structures are used to dictate the flow of execution in a


program. These structures include conditional statements (if, else-if,
else), looping statements (for, while) and branching statements(break,
continue).

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 3 / 38


Conditional statements

if Statement: An if statement is a control structure that allows you


to execute a block of code conditionally, based on a boolean expression.
The basic syntax of an if statement is as follows:
if boolean_express ion :
// code block to be executed
// if b oolean_e xpression is true

If the boolean expression evaluates to true, the code block within the
curly braces will be executed. If the boolean expression evaluates to
false, the code block will be skipped, and the program will continue
executing the next statement after the if statement.

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 4 / 38


Example if

x = 10
if x > 0:
print ( " x is positive " )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 5 / 38


Conditional statements

if-else Statement: The if-else statement is a control flow construct


that allows you to execute different blocks of code based on a
condition. It consists of an if statement followed by an optional else
statement. The else statement serves as the default.
The condition is a boolean expression that is evaluated. If the condition
is true, the code block inside the if statement is executed. If the
condition is false, the code block inside the else statement is executed.
if ( condition ) :
// code to be executed if condition is true
else :
// code to be executed if condition is false

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 6 / 38


Example if-else

x = 10
if x >= 10:
print ( " x is greater than or equal to 10 " )
else :
print ( " x is less than 10 " )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 7 / 38


Conditional statements

elif Statement: The elif statement is an extension of the if-else


statement. It allows you to check multiple conditions and execute
different code blocks based on those conditions. It allows for chaining
multiple conditions to be checked sequentially. The else if statement is
typically used when you have more than two possible conditions to
check.
if ( condition1 ) :
// code to be executed if condition1 is true
elif ( condition2 ) :
// code to be executed if condition2 is true
else :
// code to be executed if none of the conditions are true

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 8 / 38


Example elif

x = 0
if x > 0:
print ( " x is positive " )
elif x < 0:
print ( " x is negative " )
else :
print ( " x is zero " )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 9 / 38


Example elif

num = 42

if num < 0:
print ( " Number is negative " )
elif num == 0:
print ( " Number is zero " )
elif num % 2 == 0:
print ( " Number is even " )
else :
print ( " Number is odd " )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 10 / 38


Conditional statements

Nested if-statement: Nested ‘if‘ statements are ‘if‘ statements that are
contained inside another ‘if‘ or ‘else‘ statement’s code block. Nested ‘if‘
statements are used when you need to check for multiple conditions and
perform different actions based on those conditions.
if ( condition1 ) :
// code block 1
if ( condition2 ) :
// code block 2
else :
// code block 3
else :
// code block 4

Nested ‘if‘ statements can be useful when you have multiple conditions to
check, and the outcome of one condition depends on the outcome of another
condition. However, it’s important to use them judiciously, as deeply nested
‘if‘ statements can make your code difficult to read and maintain.

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 11 / 38


Example nested if

x = 10
if x > 5:
if x < 15:
print ( " x is between 5 and 15 " )
else :
print ( " x is greater than or equal to 15 " )
else :
print ( " x is less than or equal to 5 " )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 12 / 38


Conditional statements

Ternary operator: The ternary operator is a shorthand way to write an


if-else statement in a single line. It’s a compact and efficient way to express
conditional logic.
ex pression_if_tr ue if condition else expression_if_false

1. condition: This is a boolean expression that evaluates to either true or


false.
2. expression if true: This is the expression that gets evaluated and returned
if the ‘condition‘ is true.
3. expression if false: This is the expression that gets evaluated and returned
if the ‘condition‘ is false.

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 13 / 38


Example Ternary operator

age = 18
is_adult = " Yes " if age >= 18 else " No "
print ( is_adult )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 14 / 38


Loops

for Loop: The ‘for‘ loop is a control flow statement that is used to
execute a block of code a specified number of times. It is widely used
when you know the number of iterations beforehand.
for item in sequence :
# code block to be executed

It executes a block of code a fixed number of times.

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 15 / 38


Example for

fruits = [ " apple " , " banana " , " cherry " ]
for fruit in fruits :
print ( fruit )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 16 / 38


Example for

for i in range (5) :


print ( i )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 17 / 38


Comprehension

List comprehension is a concise and readable way to create lists in


Python. It allows you to generate a new list by applying an expression
to each item in an iterable (such as a list, tuple, or range) and
optionally applying a filter to include only certain items.
List comprehensions are not only more concise but often more efficient
than traditional for loops for creating lists in Python. They make your
code more readable and expressive when you need to transform or filter
data into a new list.

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 18 / 38


Comprehension

The basic syntax of a list comprehension looks like this:


new-list = [ expression for item in iterable if condition]
Here’s what each part of the list comprehension does:
expression: This is the value you want to include in the new list for
each item in the iterable that satisfies the condition. You can use
an expression to transform or manipulate the item in some way.
item: This is a variable that represents each element in the
iterable. You can choose any valid variable name you like.
condition (optional): This part is optional. It allows you to
include only the items that meet a specific condition. If you omit
the condition, all items from the iterable will be included in the
new list.

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 19 / 38


Comprehension Examples
Example 1: Creating a list of squares
numbers = [1 , 2 , 3 , 4 , 5]
squares = [ x **2 for x in numbers ]
print ( squares ) # Output : [1 , 4 , 9 , 16 , 25]

Example 2: Filtering even numbers


numbers = [1 , 2 , 3 , 4 , 5]
even - numbers = [ x for x in numbers if x % 2 == 0]
print ( even - numbers ) # Output : [2 , 4]

Example 3: Combining letters from two lists


fruits = [ ' apple ' , ' banana ' , ' cherry ']
colors = [ ' red ' , ' yellow ' , ' red ']
fruit - colors = [ fruit + ' is ' + color for fruit , color
in zip ( fruits , colors ) ]
print ( fruit - colors )
# Output : [ ' apple is red ', ' banana is yellow ', ' cherry
is red ']

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 20 / 38


Loops

while Loop: The ‘while‘ loop is a control flow statement that


repeatedly executes a block of code as long as a given condition is true.
It is used when you don’t know the exact number of iterations
beforehand, but you have a condition that determines when the loop
should terminate.
while condition :
# code block to be executed

However, it’s important to ensure that the condition in the ‘while‘ loop
will eventually become false to prevent an infinite loop. An infinite loop
occurs when the condition always remains true, causing the loop to run
indefinitely and potentially causing the program to hang or crash.

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 21 / 38


Example while

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

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 22 / 38


Branching statements

break Statement: The ‘break‘ statement is used to terminate a loop


(for, while) statement prematurely. When the ‘break‘ statement is
encountered within a loop or switch, the program control jumps out of
the statement immediately and continues execution with the statement
following the loop or switch.
break ;

for num in range (10) :


if num == 5:
break
print ( num )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 23 / 38


Branching statements

continue Statement: The ‘continue‘ statement is used to control the


flow within loops (for, while). It’s specifically designed to skip the
remaining code in the current iteration and proceed directly to the
next iteration.
When encountered inside a loop, ‘continue‘ forces an immediate jump
to the beginning of the next iteration. Any code following the
‘continue‘ statement in the current iteration is skipped.
continue ;

for num in range (10) :


if num % 2 == 0:
continue
print ( num )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 24 / 38


Branching statements

pass Statement: The pass statement is a null operation. It is used


when a statement is syntactically required but you want to do nothing.
pass ;

x = 10
if x > 5:
pass
else :
print ( " x is less than or equal to 5 " )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 25 / 38


Logical operators

Logical operators are used to combine or negate Boolean expressions.


These operators allow you to perform logical operations on one or more
conditions, and they return a Boolean value (‘True‘ or ‘False‘) based on
the result of the operation.

and Operator: The ‘and‘ operator returns ‘True‘ if both operands are
‘True‘, and ‘False‘ otherwise. It follows the principle of short-circuit
evaluation, meaning that the second operand is evaluated only if the
first operand is ‘True‘.
x = 5
y = 10
if x > 0 and y > 0:
print ( " Both x and y are positive " )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 26 / 38


Logical operators

or Operator: The ‘or‘ operator returns ‘True‘ if at least one of the


operands is ‘True‘, and ‘False‘ otherwise. Like the ‘and‘ operator, it
follows short-circuit evaluation, where the second operand is evaluated
only if the first operand is ‘False‘.
x = 5
y = 0
if x > 0 or y > 0:
print ( " At least one of x or y is positive " )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 27 / 38


Logical operators

not Operator: The ‘not‘ operator is a unary operator that negates


the Boolean value of its operand. If the operand is ‘True‘, it returns
‘False‘, and if the operand is ‘False‘, it returns ‘True‘.
x = 5
if not x == 0:
print ( " x is not zero " )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 28 / 38


Logical operators

These logical operators can be combined to create more complex


logical expressions. For example:
x = 10
y = 5
z = 20

if x > 0 and ( y < 10 or z > 15) :


print ( " The condition is True " )
else :
print ( " The condition is False " )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 29 / 38


Example

Leap Year Checker


Write a program that asks the user for a year and determines if it is a
leap year. A year is a leap year if:
It is divisible by 4 but not divisible by 100, or
It is divisible by 400.

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 30 / 38


Example

# Get user input


year = 2033

# Check if it 's a leap year


if ( year % 4 == 0 and year % 100 != 0) or ( year % 400 == 0) :
print ( f " { year } is a leap year . " )
else :
print ( f " { year } is not a leap year . " )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 31 / 38


Exercise

Collatz Conjecture
The Collatz conjecture is as follows: take any positive integer n. If n is
even, divide it by 2; if n is odd, multiply it by 3 and add 1. Repeat this
process until n becomes 1. Write a program that takes a number n
from the user and prints the sequence of numbers generated by the
Collatz conjecture until it reaches 1.

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 32 / 38


Exercise

Palindrome Checker
Ask the user to enter a word and determine if it’s a palindrome (reads
the same forwards and backwards).
Hint: Use slicing [::-1] to reverse the word and compare it to the
original.

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 33 / 38


Exercise

Number Pyramid
Write a program that asks the user for a positive integer n and prints a
right-aligned triangle of numbers as shown below (example for n = 4):

1
12
123
1234

Use nested loops to build each row, and ensure each row is
right-padded to align the triangle correctly.

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 34 / 38


Exercise

Simple ATM Machine


Simulate a basic ATM session. Start with a balance of N1000.
Repeatedly present the user with a menu:
1 Check balance
2 Deposit money
3 Withdraw money
4 Exit
Use a while loop to keep the session running until the user selects
Exit. For withdrawals, use a conditional to reject the transaction if the
requested amount exceeds the current balance.

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 35 / 38


Exercise

Password Checker
Create a program that asks the user to enter a password and allows up
to three attempts. If the user enters the correct password within three
tries, print ”Access Granted.” Otherwise, print ”Access Denied.”

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 36 / 38


Exercise
Write a program that generates a random number between 1 and 100. The
user keeps guessing until they guess the correct number. The game should
follow these rules:
1. Print an introduction to the game, explaining that the player has to guess
a number between 1 and 100.
2. Allow the player to enter their guess.
3. If the player’s guess is correct, print a congratulatory message and the
number of attempts it took to guess the number correctly.
4. If the player’s guess is too low, print ”Too low. Try again.”
5. If the player’s guess is too high, print ”Too high. Try again.”
6. Repeat steps 2-5 until the player guesses the correct number or reaches a
maximum number of attempts (e.g., 10 attempts).
7. If the player reaches the maximum number of attempts without guessing
the correct number, print a message revealing the secret number and
indicating that the player has run out of attempts.
8. After the game is over (either the player guessed correctly or ran out of
attempts), ask the player if they want to play again. If yes, repeat the game.
If no, exit the program.
Emmanuel Ali(PhD) 2nd Semester March 22, 2026 37 / 38
Hint

Use this for random number generation


import random

# Generate a random integer between 1 and 10


random_number = random . randint (1 , 10)
print ( random_number )

Emmanuel Ali(PhD) 2nd Semester March 22, 2026 38 / 38

You might also like