The document discusses conditional statements, control structures, and exception handling in Python. It provides examples of if, if-else, and nested if statements. It also demonstrates while and for loops, including examples of break, continue, and range functions. Finally, it covers try, except, else, and finally blocks for exception handling, and provides examples of catching specific exceptions.
1. 21CSS101J - Programming for Problem
Solving
Conditional Statements
Control Structures
Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Dr. C. SIVASANKAR
Assistant Professor / CSE
3. Conditional Statements
If statement:
Example
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a")
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
4. Conditional Statements
If Else statement:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
5. Conditional Statements
If else:
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
6. Conditional Statements
If Else:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
7. Conditional Statements
If Else:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
8. Conditional Statements
Short Hand If:
If you have only one statement to execute, you can
put it on the same line as the if statement.
Example
One line if statement:
if a > b: print("a is greater than b")
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
9. Conditional Statements
Short Hand If ... Else
If you have only one statement to execute, one for if,
and one for else, you can put it all on the same line:
Example
One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
10. Conditional Statements
You can also have multiple else statements on
the same line:
Example
One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a = = b else print("B")
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
11. Conditional Statements
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
12. Conditional Statements
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
13. Conditional Statements
Nested If
You can have if statements inside if statements, this is
called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
15. while loops
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Example
Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
16. The break Statement
With the break statement we can stop the loop even if the while
condition is true:
Example
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
17. The break Statement
With the break statement we can stop the loop even if the while
condition is true:
Example
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
18. The continue Statement:
With the continue statement we can stop the current iteration, and
continue with the next:
Example
Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
19. The continue Statement:
With the continue statement we can stop the current iteration, and
continue with the next:
Example
Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
20. Python For Loops
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
21. Looping Through a String
Even strings are iterable objects, they contain a sequence of
characters:
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
22. The break Statement
With the break statement we can stop the loop before it has
looped through all the items:
Example
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
23. The range() Function
To loop through a set of code a specified number of times, we
can use the range() function,
The range() function returns a sequence of numbers, starting
from 0 by default, and increments by 1 (by default), and ends
at a specified number.
Example
Using the range() function:
for x in range(6):
print(x)
Note that range(6) is not the values of 0 to 6, but the values
0 to 5.
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
24. The range() function defaults to 0 as a starting value, however
it is possible to specify the starting value by adding a
parameter:
range(2, 6), which means values from 2 to 6
(but not including 6):
Example
Using the start parameter:
for x in range(2, 6):
print(x)
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
25. Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
26. Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration
of the "outer loop":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
27. Nested Loops:
for x in range(2):
for y in range(11):
print(x,"*",y,"=",x*y)
print("--------")
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
28. Python Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Error in Python can be of two types i.e. Syntax errors
and Exceptions.
Errors are the problems in a program due to which
the program will stop the execution.
On the other hand, exceptions are raised when
some internal events occur which changes the
normal flow of the program
29. Python Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Difference between Syntax Error and Exceptions
Syntax Error: As the name suggests this error is caused by the wrong
syntax in the code. It leads to the termination of the program.
# initialize the amount variable
amount = 10000
# check that You are eligible to
# purchase Dsa Self Paced or not
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")
30. Python Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Difference between Syntax Error and Exceptions
Exceptions: Exceptions are raised when the program is syntactically correct, but
the code resulted in an error. This error does not stop the execution of the program,
however, it changes the normal flow of the program
# initialize the amount variable
marks = 10000
# perform division with 0
a = marks / 0
print(a)
31. Python Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Try and Except Statement – Catching Exceptions
Try and except statements are used to catch and handle exceptions
in Python.
Statements that can raise exceptions are kept inside the try clause
and
the statements that handle the exception are written inside except
clause.
32. Python Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Example: Let us try to access the array element whose index is out of
bound and handle the corresponding exception.
# Python program to handle simple runtime error
a = [1, 2, 3]
try:
print ("Second element = " (a[1]))
# Throws error since there are only 3 elements in array
print ("Fourth element = " (a[3]))
except:
print ("An error occurred")
33. Python Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Catching Specific Exception
A try statement can have more than one except clause, to specify handlers for
different exceptions.
Please note that at most one handler will be executed.
For example, we can add IndexError in the above code.
The general syntax for adding specific exceptions are –
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
34. Python Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Catching Specific Exception
A try statement can have more than one except clause, to specify handlers for
different exceptions.
Please note that at most one handler will be executed.
For example, we can add IndexError in the above code.
The general syntax for adding specific exceptions are –
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
36. Python Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Try with else clause :The code enters the else block only if the try clause does not
raise an exception.
37. Python Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Finally Keyword in Python
Python provides a keyword finally, which is always executed after the try and
except blocks.
The final block always executes after normal termination of try block or after try
block terminates due to some exception.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
.
38. Python Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Finally Keyword in Python
Python provides a keyword finally, which is always executed after the try and
except blocks.
The final block always executes after normal termination of try block or after try
block terminates due to some exception.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
.
39. Python Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Finally Keyword in Python
Python provides a keyword finally, which is always executed after the try and
except blocks.
The final block always executes after normal termination of try block or after try
block terminates due to some exception.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
.
40. Python Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Finally Keyword in Python
Python provides a keyword finally, which is always executed after the try and
except blocks.
The final block always executes after normal termination of try block or after try
block terminates due to some exception.
Syntax:
try:
k = 5/0 # raises divide by zero exception.
print(k)
except ZeroDivisionError:
print("Can't divide by zero")
finally:
print('This is always executed')