05 20241010 ControlStructures OOP
05 20241010 ControlStructures OOP
and OOP
Types:
Conditional Statements, Loops.
Python Control Structures
Conditional Statements Overview
• Conditional statements allow decision-making
based on conditions.
– if
– elif
– else
Python Control Structures
Conditional Statements Overview
• If Statement
Syntax
if condition:
# Code block to execute if condition is true
Example
x=5
if x > 0:
print("x is positive")
Python Control Structures
Conditional Statements Overview
• If-Else Statement
Syntax
if condition:
# Code block to execute if condition is true
else:
# Code block to execute if condition is false
Example
x = -3
if x > 0:
print("x is positive")
else:
print("x is negative")
Python Control Structures
Conditional Statements Overview
• If-Elif-Else Statement
Syntax
if condition1:
# Code block to execute if condition1 is true
elif condition2:
# Code block to execute if condition2 is true
else:
# Code block to execute if no conditions are true
Example
x=0
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
Python Control Structures
Loops Overview
Loops are used to execute a block of code repeatedly.
Two types:
• for loop
• while loop
Python Control Structures
Loops Overview
• For Loop
Syntax
for variable in sequence:
# Code block to repeat for each item in the sequence
Example
for i in range(5):
print(i)
Python Control Structures
Loops Overview
• While Loop
Syntax
while condition:
# Code block to execute while the condition is true
Example
count = 0
while count < 5:
print(count)
count += 1
Python Control Structures
Break, Continue, and Pass
break: Exits the loop early.
Example
for i in range(10):
if i == 5:
break
print(i)
Python Control Structures
Break, Continue, and Pass
• Continue
Example
for i in range(10):
if i == 5:
continue
print(i)
Python Control Structures
Break, Continue, and Pass
• Pass
Example
for i in range(5):
if i == 3:
pass
print(i)
Python Control Structures
Nested Control Structures
• Control structures can be nested within each other.
Example
for i in range(3):
if i % 2 == 0:
print(f"{i} is even")
else:
print(f"{i} is odd")
Conditional Branching
What is Conditional Branching?
Definition:
• Conditional branching allows a program to make
decisions based on conditions.
Key Idea:
• A condition is an expression that evaluates to True or
False. Based on the result, different blocks of code
are executed.
Conditional Branching
Conditional Branching - The 'if' Statement
Syntax
if condition:
# Code to execute if the condition is True
Example
x = 10
if x > 5:
print("x is greater than 5")
Output
x is greater than 5
Conditional Branching
Conditional Branching - The ‘else' Statement
• The else statement is used to define an alternate block of
code when the if condition is False.
Syntax
if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is False
Example
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
Output
x is not greater than 5
Conditional Branching
Conditional Branching - The ‘elif' Statement
• elif stands for "else if" and is used to check multiple
conditions in sequence.
Syntax
if condition1:
# Code for condition1
elif condition2:
# Code for condition2
else:
# Code if all conditions are False
Example Output
x=8 x is greater than 5 but
if x > 10: less than or equal to 10
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
else:
print("x is 5 or less")
Conditional Branching
Conditional Branching - Logical Operators
• Logical operators like and, or, and not allow you to combine
multiple conditions.
Syntax
if condition1 and condition2:
# Code if both conditions are True
if condition1 or condition2:
# Code if at least one condition is True
if not condition:
# Code if condition is False
Example
x=7
if x > 5 and x < 10:
print("x is between 5 and 10")
Output
x is between 5 and 10
Conditional Branching
Conditional Branching - Nested 'if' Statements
• Nested conditions are if statements inside other if
statements.
Example
x = 10
if x > 5:
if x < 15:
print("x is between 5 and 15")
else:
print("x is 15 or more")
else:
print("x is 5 or less")
Output
x is between 5 and 15
Conditional Branching
Conditional Branching - Comparison Operators
List of common comparison operators:
== : Equals
!= : Not equals
> : Greater than
< : Less than
>= : Greater than or equal to
<= : Less than or equal to
Conditional Branching
Conditional Branching - Comparison Operators
Common comparison operators:
Example
x = 20
if x == 20:
print("x is equal to 20")
Output
x is equal to 20
Conditional Branching
Conditional Branching - Comparison Operators
Real-World Example: Grading System
Problem: Create a grading system that assigns a letter grade based on a student's score.
score = 85
Output
The grade is B
Conditional Branching
Conditional Branching - Comparison Operators
Real-World Example: Traffic Light System
Problem: Create a program to simulate a traffic light controller.
light = "green"
if light == "green":
print("Go!")
elif light == "yellow":
print("Slow down!")
else:
print("Stop!")
Output
Go!
Conditional Branching
Conditional Branching - Comparison Operators
Real-World Example: Password Validation
Problem: Check if the entered password meets specific conditions.
password = "secret123"
if len(password) >= 8:
if any(char.isdigit() for char in password):
print("Valid password")
else:
print("Password must contain at least one number")
else:
print("Password must be at least 8 characters long")
Output
Valid password
Conditional Branching
Conditional Branching - Short-Hand 'if'(Ternary Operator)
Ternary operator allows writing an if-else condition in a single
line.
Syntax
value_if_true if condition else value_if_false
Example
age = 18
status = "Adult" if age >= 18 else "Minor"
print(status)
Output
Adult
Conditional Branching
Conditional Branching - Short-Hand 'if'(Ternary Operator)
Real-World Example: Simple ATM System
Problem: Simulate an ATM system for withdrawing cash.
balance = 1000
withdrawal_amount = 500
Output
Withdrawal successful!
New balance: 500
Conditional Branching
Conditional Branching - Short-Hand 'if'(Ternary Operator)
Best Practices for Conditional Branching
Syntax
for variable in sequence:
# Code block to repeat
Example
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output
apple
banana
cherry
Looping
The 'for' Loop
• Using range() in a for Loop
• range() function: Generates a sequence of numbers.
Syntax
for i in range(start, stop, step):
# Code block to repeat
Example
for i in range(1, 6):
print(i)
Output
1
2
3
4
5
Looping
The 'while' Loop
Syntax
while condition:
# Code block to repeat
Example
count = 0
while count < 5:
print(count)
count += 1
Output
0
1
2
3
4
Looping
The 'break' Loop
• break: Exits the loop prematurely when a condition is met.
Example
for i in range(10):
if i == 5:
break
print(i)
Output
0
1
2
3
4
Looping
The 'continue' Loop
• continue: Skips the rest of the loop body for the current iteration.
Example
for i in range(5):
if i == 2:
continue
print(i)
Output
0
1
3
4
Looping
The 'else' Clause with Loops
• else: Executes a block of code after the loop finishes unless break is
encountered.
Syntax
for/while loop:
# Code block
else:
# Code after loop ends
Example
for i in range(5):
print(i)
else:
print("Loop finished successfully")
Output
0
1
2
3
4
Loop finished successfully
Looping
Nested Loops
• Nested Loops: Loops inside loops allow you to perform more complex
iterations.
Example
for i in range(3):
for j in range(2):
print(f"i = {i}, j = {j}")
Output
i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1
Looping
Nested Loops
• Real-World Example: Sum of Numbers
Output
Sum: 55
Looping
Nested Loops
• Real-World Example: Factorial of a Number
Output
Factorial of 5 is 120
Looping
Nested Loops
• Real-World Example: While Loop for Guessing Game
Problem: Create a number guessing game using a while loop.
import random
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Looping
Nested Loops
• Infinite Loops: Infinite Loop: A loop that runs endlessly because the
stopping condition is never met.
Example
while True:
print("This will run forever!")
• Avoid infinite loops: Make sure the loop condition eventually becomes
False.
• Use 'break' and 'continue' carefully: Understand the flow of your program
when using these statements.
• Keep loops readable: Avoid deep nesting by breaking logic into smaller
functions.
Looping
Common Mistakes with Loops
• Off-by-One Errors: Make sure to use correct bounds in loops.
• Forgetting break: Ensure that the break statement is used properly when
exiting early from loops.
Python Functions
Functions in Python
What is a Function?
• A function is a block of code that performs a specific task.
• Modularization
• Improved readability
Functions in Python
Syntax of a Function in Python
Syntax
def function_name(parameters):
"""
Optional docstring that describes the function.
"""
# Code block (Function body)
return value # Optional
Functions in Python
Syntax of a Function in Python
greet()
Output
Hello, World!
Functions in Python
Calling a Function
• A function is executed when it is called by its name followed by
parentheses.
Example
def add_two_numbers():
result = 2 + 3
print(result)
add_two_numbers()
Output
5
Functions in Python
Function with parameters
• Parameters allow you to pass information into the function.
Example
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice")
Output
Hello, Alice!
Functions in Python
Return Statement
• The return statement is used to send a result back from a
function.
Example
def add_numbers(a, b):
return a + b
result = add_numbers(4, 5)
print(result)
Output
9
Functions in Python
Positional vs. Keyword Arguments
• Positional Arguments: Passed based on their position.
• Keyword Arguments: Passed using parameter names.
Example
def describe_pet(animal, name):
print(f"I have a {animal} named {name}.")
Example
def greet(name="Guest"):
print(f"Hello, {name}!")
Example
def sum_numbers(*args):
total = sum(args)
print(f"Sum: {total}")
sum_numbers(1, 2, 3, 4)
Output
Sum: 10
Functions in Python
Arbitrary Keyword Arguments (**kwargs)
• Use **kwargs to pass a variable number of keyword
arguments.
Example
def describe_person(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
def my_function():
x = 5 # Local variable
print(f"Inside function: {x}")
my_function()
print(f"Outside function: {x}")
Output
Inside function: 5
Outside function: 10
Functions in Python
Global Keyword
• Use the global keyword to modify global variables within a
function.
Example
x = 10
def modify_global():
global x
x = 20
modify_global()
print(x)
Output
20
Functions in Python
Anonymous (Lambda) Functions
• Lambda functions are short, inline functions without a name.
Syntax
lambda arguments: expression
Example
add = lambda x, y: x + y
print(add(3, 5))
Output
8
Functions in Python
Higher-Order Functions with Lambda
• You can pass lambda functions as arguments.
Example
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)
Output
[1, 4, 9, 16, 25]
Functions in Python
Recursion
• A function that calls itself is known as recursion.
print(factorial(5))
Output
120
Functions in Python
Pros and Cons of Recursion
Pros:
• Elegant solutions for problems like tree traversals,
factorial, etc.
Cons:
• Can lead to performance issues and stack
overflow if not handled properly.
Functions in Python
What are Custom Functions?
greet_user()
Output
Hello! Welcome to Python functions.
Functions in Python
Custom Function with Parameters
• Parameters allow passing data into the function for more
flexibility.
Example:
def greet_user(name):
print(f"Hello, {name}! Welcome to Python functions.")
greet_user("Alice")
Output
Hello, Alice! Welcome to Python functions.
Functions in Python
Return Values in Custom Functions
• The return statement is used to send a result back from the
function.
result = add_numbers(4, 5)
print(result)
Output
9
Functions in Python
Multiple Return Values
• Functions can return multiple values as a tuple.
Example:
def calculate_area_and_perimeter(length, width):
area = length * width
perimeter = 2 * (length + width)
return area, perimeter
Example:
def greet_user(name="Guest"):
print(f"Hello, {name}! Welcome to Python functions.")
Output
Hello, Guest! Welcome to Python functions.
Hello, Bob! Welcome to Python functions.
Functions in Python
Using *args for Arbitrary Arguments
• Allows passing a variable number of non-keyword arguments.
Example:
def sum_all_numbers(*args):
total = sum(args)
print(f"Sum of all numbers: {total}")
sum_all_numbers(1, 2, 3, 4, 5)
Output
Sum of all numbers: 15
Functions in Python
Using **kwargs for Arbitrary Keyword
Arguments
• Allows passing a variable number of keyword arguments.
Example:
def describe_person(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
Output
name: Alice
age: 30
job: Engineer
Functions in Python
Using **kwargs for Arbitrary Keyword Arguments
Real-World Example: Custom Calculator Function
def calculator(operation, a, b):
if operation == 'add':
return a + b
elif operation == 'subtract':
return a - b
elif operation == 'multiply':
return a * b
elif operation == 'divide':
if b != 0:
return a / b
else:
return "Cannot divide by zero"
else:
return "Invalid operation"
# Usage
result = calculator('add', 10, 5)
print(result)
Output
15
Functions in Python
Advanced: Recursive Custom Functions
Recursion is a function calling itself.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # 5! = 5 * 4 * 3 * 2 * 1 = 120
Output
120
Functions in Python
Best Practices for Functions
• Name Functions Clearly: Use descriptive names to explain
what the function does.
print(safe_divide(10, 0))
Output
Error: Division by zero is not allowed.
Functions in Python
Modular Design with Functions
• A module is a file containing Python definitions and statements, such as
functions, classes, or variables, that can be reused in other Python programs.
• Modules allow you to organize your code into separate files, which makes it
more readable and maintainable.
• In python, a module is simply a .py file.
o Example: a file named math_functions.py is considered a module, and it
might contain various mathematical functions.
• Standard Library Modules: Python comes with a large standard library of
modules like math, os, sys, etc., that can be imported and used in any Python
program.
• Reusability: Modules help in reusing code across different programs. Once you
create a module, you can import and use it in any script, reducing code
duplication.
• Package: A collection of related modules can be organized into a package by
placing them in a directory with a special __init__.py file.
Functions in Python
Modular Design with Functions
• A module is a file containing Python definitions and statements, such as
functions, classes, or variables, that can be reused in other Python programs.
• Modules allow you to organize your code into separate files, which makes it
more readable and maintainable.
• Break your code into smaller functions for a more organized, modular design.
• from Keyword: You can import specific elements from a module using the from keyword: