0% found this document useful (0 votes)
22 views81 pages

05 20241010 ControlStructures OOP

The document provides an overview of Python control structures, functions, and object-oriented programming (OOP). It covers essential concepts such as conditional statements, loops, and the syntax for defining and calling functions. The document also includes practical examples and best practices for using these programming constructs effectively.

Uploaded by

scs623170
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)
22 views81 pages

05 20241010 ControlStructures OOP

The document provides an overview of Python control structures, functions, and object-oriented programming (OOP). It covers essential concepts such as conditional statements, loops, and the syntax for defining and calling functions. The document also includes practical examples and best practices for using these programming constructs effectively.

Uploaded by

scs623170
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
You are on page 1/ 81

Python Control Structures, Functions

and OOP

Prof. Murali Krishna Gurram


Dept. of Geo-Engineering & RDT
Centre for remote Sensing, AUCE
Andhra University, Visakhapatnam – 530 003
Dt. 15/10/2024
Basic Elements of Python

a) Python Control Structures


b) Functions
c) OOP
Python Control Structures
Python Control Structures
Definition:
 Control structures determine the flow of execution of
statements in a program.

 Python control structures are essential for controlling the


flow of a program.
 Conditional statements (if, elif, else) and loops (for, while) are
key concepts.
 Special statements like break, continue, and pass provide
finer control.

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.

 continue: Skips the rest of the code in the loop for


the current iteration.

 pass: Does nothing; acts as a placeholder.


Python Control Structures
Break, Continue, and Pass
• Break

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

if score >= 90:


grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"

print(f"The grade is {grade}")

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

if withdrawal_amount <= balance:


balance -= withdrawal_amount
print(f"Withdrawal successful! New balance: {balance}")
else:
print("Insufficient funds.")

Output
Withdrawal successful!
New balance: 500
Conditional Branching
Conditional Branching - Short-Hand 'if'(Ternary Operator)
Best Practices for Conditional Branching

 Keep conditions simple: Avoid overly complex conditions;


break them into smaller parts if needed.

 Use meaningful variable names: This makes conditions


more readable.

 Avoid deep nesting: Use logical operators (and, or) to


reduce nested conditions.

 Handle all possible cases: Ensure that all potential outcomes


are accounted for, especially when using else.
Conditional Branching
Conditional Branching - Short-Hand 'if'(Ternary Operator)
Common Mistakes in Conditional Branching

 Missing colon (:): Always end the condition with a colon.

 Incorrect indentation: Python relies on indentation to


define code blocks.

 Not considering all conditions: Ensure you handle all


possible cases to avoid bugs.
Looping
What is a Loop?
Definition:
• A loop is a programming construct that repeats a block of
code multiple times based on a condition.

Types of Loops in Python:

• for loop: Iterates over a sequence (e.g., list, string, range).

• while loop: Repeats as long as a condition is True.


Looping
The 'for' Loop
The for Loop

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

Problem: Calculate the sum of numbers from 1 to 10.


total = 0
for i in range(1, 11):
total += i
print("Sum:", total)

Output
Sum: 55
Looping
Nested Loops
• Real-World Example: Factorial of a Number

Problem: Calculate the factorial of a number using a for loop.


num = 5
factorial = 1

for i in range(1, num + 1):


factorial *= i

print(f"Factorial of {num} is {factorial}")

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

secret_number = random.randint(1, 10)


guess = None

while guess != secret_number:


guess = int(input("Guess a number between 1 and 10: "))
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")

print("Congratulations! You guessed it.")


Output (depends on user input):
Guess a number between 1 and 10: 5
Too low!
Guess a number between 1 and 10: 7
Congratulations! You guessed it.
Looping
Nested Loops
• Real-World Example: Multiplication Table
Problem: Display the multiplication table using nested loops.
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end="\t")
print()

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!")

Avoidance: Ensure a condition is present that eventually breaks the loop.


Looping
Best Practices for Using Loops
• Choose the right loop: Use for loops when the number of iterations is
known.
• Use while loops for indefinite iteration.

• 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.

• Infinite Loops: Ensure conditions in while loops are updated.

• 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.

• Functions are a core concept in Python, allowing code to be


modular, reusable, and easier to maintain.

• Mastering function arguments, return values, and scope will


help you write better Python code.

Functions Helps in:


• Code reusability

• 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

Example of a Simple Function


def greet():
print("Hello, World!")

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}.")

describe_pet("dog", "Buddy") # Positional


describe_pet(animal="cat", name="Whiskers") # Keyword
Output
I have a dog named Buddy.
I have a cat named Whiskers.
Functions in Python
Default Arguments
• You can assign default values to function parameters.

Example
def greet(name="Guest"):
print(f"Hello, {name}!")

greet() # Uses default value


greet("Alice") # Overrides default value
Output
Hello, Guest!
Hello, Alice!
Functions in Python
Arbitrary Arguments (*args)
• Use *args to pass a variable number of non-keyword
arguments.

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}")

describe_person(name="Alice", age=25, job="Engineer")


Output
name: Alice
age: 25
job: Engineer
Functions in Python
Variable Scope
• Local Scope: Variables declared inside a function.
• Global Scope: Variables declared outside any function.
Example
x = 10 # Global variable

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.

Example: Factorial Function


def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)

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?

 Definition: Custom functions are user-defined


functions created to solve specific tasks.

 Custom Functions allow code reuse, simplify complex


tasks, and make your code modular.
Functions in Python
Why Use Custom Functions?

 Code organization and modularity.

 Avoid repetition by reusing code.

 Enhance readability and maintenance.

 Break down complex problems into smaller,


manageable tasks.
Functions in Python
Creating a Custom Function
The basic structure:
def function_name(parameters):
"""
Optional docstring to describe what the function does.
"""
# Function body
return value # Optional

Example: Simple Greeting Function


def greet_user():
print("Hello! Welcome to Python 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.

Example: Sum of Two Numbers


def add_numbers(a, b):
return a + b

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

area, perimeter = calculate_area_and_perimeter(5, 3)


print(f"Area: {area}, Perimeter: {perimeter}")
Output
Area: 15, Perimeter: 16
Functions in Python
Default Arguments
• You can assign default values to function parameters, making
the argument optional.

Example:
def greet_user(name="Guest"):
print(f"Hello, {name}! Welcome to Python functions.")

greet_user() # Uses default value


greet_user("Bob") # Overrides default value

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}")

describe_person(name="Alice", age=30, job="Engineer")

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.

• Keep Functions Small: Each function should perform a single


task.

• Document with Docstrings: Always include a docstring


explaining the function’s purpose.

• Avoid Global Variables: Pass values as arguments instead of


relying on global variables.

• Handle Errors: Use error handling mechanisms like try-except


where needed.
Functions in Python
Handling Errors in Functions
Example: Handling Division by Zero

def safe_divide(a, b):


try:
result = a / b
except ZeroDivisionError:
return "Error: Division by zero is not allowed."
return result

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.

Example: E-commerce price calculator


def calculate_total_price(price, quantity):
return price * quantity
def apply_discount(total, discount):
return total - (total * (discount / 100))
total = calculate_total_price(100, 5)
final_price = apply_discount(total, 10)
print(f"Final price after discount: {final_price}")
Output
Final price after discount: 450.0
Functions in Python
Modular Design with Functions
• Importing Modules: To use the functions, classes, or variables from a module
in another file, you use the import statement.
Example:
import math_functions
result = math_functions.add(5, 3) # Assuming 'add' is a function in the module

• from Keyword: You can import specific elements from a module using the from keyword:

from my_module import greet


print(greet("Alice")) # Output: Hello, Alice!
Functions in Python
Custom Functions
• Custom functions allow you to structure your code efficiently.

• Use functions to avoid code repetition and make your


programs more readable.

• Practice creating functions for common tasks and understand


the different ways to pass arguments and return values.
Thank You

You might also like