4. Control Structures & Functions
4. Control Structures & Functions
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
• Loops
• Exception handling
3
CONDITIONAL STATEMENTS
4
1) if Statement: This is first and simplest form of conditional
statement.
Syntax:
if true_or_not:
do_this_if_true
5
The ‘if’ keyword
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:
Output: x is large
10
3) elif Statement:
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')
print('Hello Joe')
else:
Iteration means executing the same block of code over and over,
potentially many times. A programming structure that implements
iteration is called a loop.
while:
instruction
14
Syntax:
while <expression>:
<statement(s)>
15
• When a while loop is encountered, <expression> is first
evaluated in Boolean context.
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:
<statements>
• The loop variable <var> takes on the value of the next element
in <iterable> each time through the loop.
19
Example:
for i in a:
print(i)
Output:
foo
bar
baz
20
The ‘break’ and ‘continue’ statements:
Break Statement:
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:
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:
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.
31
Built-in Exception Description
33
10. IndentationError It is raised due to incorrect indentation in the program
code.
34
35
Raising Exceptions:
36
1. The raise Statement:
37
38
2. The assert Statement:
assert Expression[,arguments]
39
• On encountering an assert statement, Python evaluates the
expression given immediately after the assert keyword.
40
EXCEPTION HANDLING
Exception handling is a mechanism to deal with errors or
exceptional situations that may occur during the execution
of a program.
41
Need for Exception Handling:
An error encountered in a
method
Program terminates
43
Catching Exceptions:
44
• Every try block is followed by an except block.
1. try:
except [exception-name]:
2. try:
try:
print("Result:", result)
except ZeroDivisionError:
except ValueError:
try:
except ExceptionType:
else:
49
Example:
try:
except ValueError:
else:
print("Sum:", result)
50
‘finally’ block:
try:
except ExceptionType:
finally:
52
Example:
try:
numerator = 50
except ZeroDivisionError:
else:
finally:
Definition:
class FoundException(Exception):
pass
54
Usage of Custom Exception:
try:
if item == target:
raise FoundException()
except FoundException:
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
58
The syntax of the custom function is as follows:
def function_name(parameters):
"""
"""
59
From the above syntax
def greet(name):
parameter
"""
Docstring
Function to greet a person by name
"""
print(greet("Alice"))
Calling the
function
Output: Hello, Alice! 61
Global Functions:
Example:
def 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():
Example:
add = lambda x, y: x + y
print(add(3, 5))
Output: 8
64
Methods:
Example:
class MyClass:
def method(self):
print("This is a method")
obj = MyClass()
Parameters are values the are passed into the function, and
return values are the results of executing the function.
Example:
def greet(name):
message = greet("Alice")
print(message)
Example:
def greet(name="World"):
Naming Conventions:
Docstrings:
def calculate_area(radius):
Args:
Returns:
"""
69
Argument and Parameter Unpacking:
Argument Unpacking:
Parameter Unpacking:
70
Example:
print("Hello,", name)
numbers = (2, 3)
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():
my_function()
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:
return a / b
74