0% found this document useful (0 votes)
10 views

4. Control Structures & Functions

The document provides an overview of Python control structures, including conditional statements, loops, and exception handling. It explains the syntax and usage of 'if', 'elif', 'else', 'while', and 'for' loops, as well as how to handle exceptions using try-except blocks. Additionally, it covers built-in exceptions and the importance of exception handling in programming.

Uploaded by

stalinking2006
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

4. Control Structures & Functions

The document provides an overview of Python control structures, including conditional statements, loops, and exception handling. It explains the syntax and usage of 'if', 'elif', 'else', 'while', and 'for' loops, as well as how to handle exceptions using try-except blocks. Additionally, it covers built-in exceptions and the importance of exception handling in programming.

Uploaded by

stalinking2006
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 74

PYTHON CONTROL

STRUCTURES AND
FUNCTIONS

Presented by
Prof.G.V.S,SARMA
Department of Chemical Engineering
Andhra University College of Engineering(A)
CONTENTS
 Control Structures
 Conditional
Statements
 Looping
 Exceptions
 Exception Handling
 Custom Exceptions
 Custom Functions
2
CONTROL STRUCTURES

Control structures are an essential part of programming that


allow you to specify the flow of execution in your code.

In Python, there are several types of control structures


including:
• Conditional Statements (Branching)

• Loops

• Exception handling
3
CONDITIONAL STATEMENTS

 Conditional statements allow you to execute certain code


blocks only if a certain condition is met.

 For example, you might want to check if a number is even or


odd before performing some operation on it.

 In Python, the conditional statements are if, elif, and else.

4
1) if Statement: This is first and simplest form of conditional
statement.

Syntax:

if true_or_not:

do_this_if_true

This conditional statement consists of the following strictly


necessary elements in this and this order only.

5
 The ‘if’ keyword

 One or more white spaces

 An expression whose value will be interpreted solely in


terms of ‘True’ (when its value is non-zero) and ‘False’ (when
its is equal zero)

 A colon (:) followed by a newline

 An indented instruction or set of instructions. All


indentations should be exactly same
6
How the statement work?

• If the true_or_not expression represents the truth (value not


equal to zero) the indented statement(s) will be executed.

• If the true_or_not expression does not represent the truth


(value equal to zero) the indented statements will be omitted
and the next executed instruction will be the one after the
original indentation level.

7
Example:

x=0

y=5

if y< x:

print('yes')

print(‘no’)

Output: no

8
2) if-else Statement:

The part of the code which begins with ‘else’ keyword says
what to do if the condition specified for the ‘if’ is not met
(note the colon after the word)

Syntax:

if true_or_false_condition:

perform_if_condition_true

else:

perform_if_condition_false 9
Example:

x = 120

if x < 50:

print('x is small')

else:

print('x is large ')

Output: x is large

10
3) elif Statement:

elif is a keyword and shorter form of else if

‘elif’ is used to check more than just one condition and to


stop when the first statement which is true is found.

Syntax:

if true_or_false_condition:

perform_if_condition_true

else:

perform_if_condition_false 11
Example:

name = 'Joe'

if name == 'Fred':

print('Hello Fred')

elif name == 'Joe':

print('Hello Joe')

else:

print("I don't know who you are!")

Output : Hello Joe


12
LOOPS

 Iteration means executing the same block of code over and over,
potentially many times. A programming structure that implements
iteration is called a loop.

 In programming, there are two types of iteration, indefinite and


definite:
• With indefinite iteration, the number of times the loop is executed
isn’t specified explicitly in advance. Rather, the designated block is
executed repeatedly as long as some condition is met.
• With definite iteration, the number of times the designated block
will be executed is specified explicitly at the time the loop starts. 13
1. ‘while’ loop (Indefinite iteration):

In general, in Python, a loop can be represented as follows:

while:

instruction

• The syntactic difference between while and if instruction is


only one: you can use the word while instead of the word if.

• The semantic difference is more important: when the condition


is met, if performs its statements only once; while repeats the
execution as long as the condition evaluates to True.

14
Syntax:

while <expression>:

<statement(s)>

• The controlling expression, <expression>, typically involves


one or more variables that are initialized prior to starting the
loop and then modified somewhere in the loop body.

• <statement(s)> represents the block to be repeatedly


executed, often referred to as the body of the loop.

15
• When a while loop is encountered, <expression> is first
evaluated in Boolean context.

• If it is True, the loop body is executed.


Then <expression> is checked again, and if still true, the
body is executed again.

• This continues until <expression> becomes False, at


which point program execution proceeds to the first
statement beyond the loop body.

16
Example: Output:

n=5 4
while n > 0: 3
n=n-1
2
print(n)
1

17
2. ‘for’ loop (Definite iteration):

The ‘for’ loop is designed to count the turns of the loop and
to browse large collections of data item by item.

Syntax:

for <var> in <iterable>:

<statements>

• The ‘for’ keyword opens the for loop. There’s no condition


after it, you don’t have to think about conditions, as they’re
checked internally without any intervention.
18
• <iterable> is a collection of objects—for example, a list or tuple.

• The <statement(s)> in the loop body are denoted by


indentation, as with all Python control structures, and are
executed once for each item in <iterable>.

• The loop variable <var> takes on the value of the next element
in <iterable> each time through the loop.

• The ‘in’ keyword introduces a syntax element describing the


range of possible values being assigned to the control variable.

19
Example:

a = ['foo', 'bar', 'baz']

for i in a:

print(i)

Output:

foo

bar

baz

20
The ‘break’ and ‘continue’ statements:

Break Statement:

• The break statement is used to exit or break out of the current


loop prematurely.

• When Python encounters a break statement inside a loop, it


immediately exits the loop and continues with the next
statement outside of the loop.

• It is often used to terminate a loop if a certain condition is met,


without waiting for the loop to naturally complete.
21
Example 1: Output:

for i in range(10): 0
print(i) 1
if i == 5:
2
break
3

22
Example 2:

i=0 Output:
while i < 10: 0
print(i)
1
if i == 5:
2
break
3
i=i+1
4

5
23
Continue Statement:

• The continue statement is used to skip the rest of the code


inside a loop for the current iteration and continue with the next
iteration of the loop.

• Unlike break, continue doesn't terminate the loop; instead, it


skips the current iteration and moves on to the next one.

• It is often used to bypass certain iterations based on specific


conditions without terminating the loop.

24
Example 1: Output:

for i in range(10): 1
if i % 2 == 0: 3
continue
5
print(i)
7

25
Example 2:

i=0 Output:
while i < 10: 1
i=i+1
3
if i % 2 == 0:
5
continue
7
print(i)
9

26
Using ‘else’ with ‘for’ and ‘while’ loops:

• Loops may have else branch too, like if’s.

• The loop’s else branch is always executed once, regardless


of whether the loop has entered its body or not.

• In Python, both for and while loops can be accompanied by


an else block, which executes when the loop completes its
iterations without encountering a break statement.

• This feature can be handy for scenarios where you want to


execute a block of code only if the loop completes
successfully. 27
Example 1: Output:

i=1 1

while i<5 : 2

print(i) 3

i +=1 4

else: else: 5

print(“else:”, i)

28
Example 2: Output:

for i in range(5): 1

print(i) 2

else: 3

print(“else:”, i) 4

else: 4

29
EXCEPTIONS
 Even if a statement or expression is syntactically correct, there
might arise an error during its execution.

 For example, trying to open a file that does not exist, division by
zero and so on.

 Such types of errors might disrupt the normal execution of the


program and are called Exceptions.

 “An exception is a Python object that represents an error”.

 When an error occurs during the execution of a program, an


exception is said to have been raised.
30
Built-in Exceptions:

• Commonly occurring exceptions are usually defined in the


compiler/interpreter. These are called built-in exceptions.

• Python’s standard library is an extensive collection of built-in


exceptions that deal with commonly occurring errors
(exceptions) by providing standardized solutions for such errors.

• On the occurrence of any built-in exception, the appropriate


exception handler code is executed which displays the reason
along with the raised exception name.

31
Built-in Exception Description

1.SyntaxError It is raised when there is an error in the syntax of the


Python code

2. ValueError It is raised when a built-in method or operation receives


an argument that has the right data type but
mismatched or inappropriate values

3. IOError It is raised when the file specified in a program


statement cannot be opened.

4. KeyboardInterrupt It is raised when the user accidentally hits the Delete or


Esc key while executing a program due to which the
normal flow of the program is interrupted.
32
5. ImportError It is raised when the requested module definition is
not found.

6. EOFError It is raised when the end of file condition is reached


without reading any data by input().

7. ZeroDivisionError It is raised when the denominator in a division


operation is zero.

8. IndexError It is raised when the index or subscript in a sequence


is out of range.

9. NameError It is raised when a local or global variable name is not


defined.

33
10. IndentationError It is raised due to incorrect indentation in the program
code.

11. TypeError It is raised when an operator is supplied with a value of


incorrect data type.

12. OverFlowError It is raised when the result of a calculation exceeds the


maximum limit for numeric data type

34
35
Raising Exceptions:

• Each time an error is detected in a program, the Python


interpreter raises (throws) an exception.

• Exception handlers are designed to execute when a specific


exception is raised.

• Programmers can also forcefully raise exceptions in a program


using the raise and assert statements.

• Once an exception is raised, no further statement in the current


block of code is executed.

36
1. The raise Statement:

• The raise statement can be used to throw an exception.

• The syntax of raise statement is:

raise exception-name[(optional argument)]

The argument is generally a string that is displayed


when the exception is raised.

• The raise statement can be used to raise a built-in


exception or user-defined one.

37
38
2. The assert Statement:

• An assert statement in Python is used to test an expression


in the program code.

• If the result after testing comes false, then the exception is


raised.

• This statement is generally used in the beginning of the


function or after a function call to check for valid input.

• The syntax for assert statement is:

assert Expression[,arguments]
39
• On encountering an assert statement, Python evaluates the
expression given immediately after the assert keyword.

• If this expression is false, an AssertionError exception is raised


which can be handled like any other exception.

40
EXCEPTION HANDLING
 Exception handling is a mechanism to deal with errors or
exceptional situations that may occur during the execution
of a program.

Exception handling is being used not only in Python


programming but in most programming languages like C++,
Java, Ruby, etc.

41
Need for Exception Handling:

• Python categorizes exceptions into distinct types so that specific


exception handlers (code to handle that particular exception) can
be created for each type.

• Exception handlers separate the main logic of the program from


the error detection and correction code.

• The compiler or interpreter keeps track of the exact position


where the error has occurred.

• Exception handling can be done for both user-defined and built-in


exceptions.
42
Process of Exception Handling:

An error encountered in a
method

Create exception object


Throwing
Exception
Exception is raised

Runtime system searches for


exception handler in the
current method
Found Not Found

Found Searches for methods in call stack


Executes the code in reverse sequence (forwarding the
(Catching an exception ) exception)
Not Found

Program terminates

43
Catching Exceptions:

• An exception is said to be caught when a code that is


designed to handle a particular exception is executed.

• Exceptions, if any, are caught in the try block and handled


in the except block.

• While writing or debugging a program, a user might doubt


an exception to occur in a particular part of the code. Such
suspicious lines of codes are put inside a try block.

44
• Every try block is followed by an except block.

• The appropriate code to handle each of the possible


exceptions (in the code inside the try block) is written inside
the except clause.

• You can handle multiple exceptions in a single ‘except’ block


or have multiple ‘except’ blocks.

• While executing the program, if an exception is


encountered, further execution of the code inside the try
block is stopped and the control is transferred to the except
block. 45
The syntax of the try ... except clause is as follows:

1. try:

#code that might raise an exception

# If an exception occurs here, it jumps to the except block

except [exception-name]:

#code to handle the exception

2. try:

# code that might raise an exception

except (ExceptionType1, ExceptionType2) as e:

# code to handle either ExceptionType1 or ExceptionType2


46
Example:

try:

num1 = int(input("Enter a numerator: "))

num2 = int(input("Enter a denominator: "))

result = num1 / num2

print("Result:", result)

except ZeroDivisionError:

print("Error: Cannot divide by zero.")

except ValueError:

print("Error: Please enter valid integers.")


47
• ‘try…except...else’ block:

• We can put an optional else clause along with the


try...except clause.

• An except block will be executed only if some exception is


raised in the try block.

• But if there is no error then none of the except blocks will


be executed.

• In this case, the statements inside the else clause will be


executed.
48
The syntax of the try ... except … else clause is as
follows:

try:

# code that might raise an exception

except ExceptionType:

# code to handle the exception

else:

# code to execute if no exception occurred

49
Example:

try:

num1 = int(input("Enter a number: "))

num2 = int(input("Enter another number: "))

except ValueError:

print("Error: Please enter valid integers.")

else:

result = num1 + num2

print("Sum:", result)

50
‘finally’ block:

• The try statement in Python can also have an optional finally


clause.

• The statements inside the finally block are always executed


regardless of whether an exception has occurred in the try block
or not.

• It is a common practice to use the finally clause while working


with files to ensure that the file object is closed.

• If used, finally should always be placed at the end of the try


clause, after all except blocks and the else block. 51
The syntax of the finally clause is as follows:

try:

# code that might raise an exception

except ExceptionType:

# code to handle the exception

finally:

# code that will always execute, regardless of


exceptions

52
Example:

try:

numerator = 50

denom = int(input("Enter the denominator: "))

quotient = numerator / denom

print("Division performed successfully")

except ZeroDivisionError:

print("Denominator as ZERO is not allowed")

else:

print("The result of division operation is", quotient)

finally:

print("OVER AND OUT")


53
CUSTOM EXCEPTIONS
 Custom exceptions in Python allow you to define your exception
classes, providing a way to create and raise specific types of
errors tailored to your application needs.

 This is particularly useful when you encounter situations in your


code that don’t fit standard built-in exceptions.

Definition:

class FoundException(Exception):

pass
54
Usage of Custom Exception:

try:

for row, record in enumerate(table):

for column, field in enumerate(record):

for index, item in enumerate(field):

if item == target:

raise FoundException()

except FoundException:

print("found at ({0}, {1}, {2})".format(row, column, index))

else:

print("not found")
55
Explanation:
• The FoundException class is defined as a subclass of the built-in
Exception class. It’s a custom exception used for breaking out of
deeply nested loops
• Inside the nested loops, if a condition is met (in this case, if ‘item’
is equal to ‘target’), the ‘FoundException’ is raised, causing the
control flow to jump to the ‘except’ block.
• In the ‘except’ block, the program prints the position where the
item was found.
• If the exception is not raised (i.e. the item is not found), then the
‘else’ block is executed, printing “not found”.
56
Benefits:
• Using a custom exception simplifies the code by reducing
the number of nested ‘if’ statements and ‘break’
statements needed to exit from nested loops.
• It improves nested code readability by clearly indicating the
purpose of the exception and the point where it is raised.
• The use of custom exception encapsulates the error-
handling logic, making the code more modular and easier
to maintain.

57
CUSTOM FUNCTIONS

 Custom functions, also known as user-defined functions, are


blocks of reusable code that perform a specific task.

 They allow you to encapsulate functionality into a named


unit, making your code modular, easier to understand, and
more maintainable.

58
The syntax of the custom function is as follows:

def function_name(parameters):

"""

Docstring: Description of the function

"""

# Function body: code block to perform the task

# Use parameters to perform operations

return result # Optional: return statement

59
From the above syntax

def: Keyword used to define a function.

function_name: Name of the function, following Python's naming


conventions.

parameters: Input values required for the function (optional).

Docstring: Optional documentation string describing the


function's purpose and usage.

return: Keyword used to return a value from the function


(optional).
60
Example:
Name of the
custom function

def greet(name):
parameter

"""
Docstring
Function to greet a person by name

"""

return f"Hello, {name}!“

print(greet("Alice"))
Calling the
function
Output: Hello, Alice! 61
Global Functions:

These functions are defined at the global level and can be


accessed from anywhere in the program.

Example:

def global_function():

print("This is a global function")

global_function() # Call the global function

Output: This is a global function

62
Local Functions:

These functions are defined within another function and are only
accessible within that function’s scope.

Example:

def outer_function():

def local_function():

print("This is a local function")

local_function() # Call local function within outer function

outer_function() # Call outer function

Output: This is a local function 63


Lambda Functions:

Lambda functions, also known as anonymous functions, are


small, inline functions defined using ‘lambda’ keyword.

Example:

add = lambda x, y: x + y

print(add(3, 5))

Output: 8

64
Methods:

Functions defined within the classes are called methods.

Example:

class MyClass:

def method(self):

print("This is a method")

obj = MyClass()

obj.method() # Call the method

Output: This is a method


65
Creating functions with parameters and return values :

Functions in Python can accept parameters and return values.

Parameters are values the are passed into the function, and
return values are the results of executing the function.

Example:

def greet(name):

return "Hello, " + name

message = greet("Alice")

print(message)

Output: Hello, Alice 66


Default parameters values :

Python functions can have default parameter values. These default


values are used when the caller does not provide a corresponding
argument

Example:

def greet(name="World"):

return "Hello, " + name

message = greet() # Using default value

print(message) # Output: Hello, World

message = greet("Alice") # Providing a different value

print(message) # Output: Hello, Alice 67


Naming Conventions and Docstrings for Functions :

Naming Conventions:

In Python, function names should be descriptive, using lowercase


letters and underscores to separate words (snake_case). It’s
important to choose meaningful names that reflect the purpose of the
function.

Docstrings:

Docstrings are multi-line strings used to document the purpose,


usage, and parameters of a function, they are enclosed in triple
quotes (“““ ”””) and appear as the first statement in a function body.
68
Example:

def calculate_area(radius):

"""Calculate the area of a circle.

Args:

radius (float): The radius of the circle.

Returns:

float: The area of the circle.

"""

return 3.14 * radius ** 2

69
Argument and Parameter Unpacking:

Argument Unpacking:

In Python, you can unpack a collection of values into individual


variables using the ‘ * ’ operator in the function definition.

Parameter Unpacking:

Similarly, you can pass multiple arguments to a function by


unpacking a collection using ‘ * ’ operator in the function call.

70
Example:

def add(a, b): def greet(*names):

return a + b for name in names:

print("Hello,", name)

numbers = (2, 3)

result = add(*numbers) greet("Alice", "Bob", "Charlie")

# Argument unpacking # Parameter unpacking

print(result) Output: Hello, Alice

Output: 5 Hello, Bob

Hello, Charlie
71
Accessing Variables in the Global Scope:

Variables defined outside any function or class have global scope. They
can be from anywhere in the program, including the functions.

Example:

x = 10 # Global variable

def my_function():

print("Global variable x is", x)

my_function()

Output: Global variable x is 10

72
Assertions for Specifying PreConditions and PostConditions in Functions:

Assertions are used to check for conditions that should always be true
during the execution of a program. They are typically used to enforce
constraints on inputs or outputs of functions.

Example:

def divide(a, b):

assert b != 0, "Division by zero"

return a / b

result = divide(10, 2) # No assertion error

print(result) # Output: 5.0

result = divide(10, 0) # Assertion error: Division by zero


73
THANK YOU

74

You might also like