SlideShare a Scribd company logo
1 of 40
21CSS101J - Programming for Problem
Solving
Conditional Statements
Control Structures
Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Dr. C. SIVASANKAR
Assistant Professor / CSE
Conditional Statements
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
O/P:
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
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
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
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
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
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
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
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
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
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
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
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
Conditional Statements
Python Loops
Python has two primitive loop commands:
 while loops
 for loops
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
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
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
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
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
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
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
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
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
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
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
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
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
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
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
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")
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)
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.
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")
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)
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)
Python Exception Handling
SRM INSTITUTE OF SCIENCE AND
TECHNOLOGY, RAMAPURAM
Catching Specific Exception:
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.
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)
.
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)
.
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)
.
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')

More Related Content

Similar to PPS-UNIT4.pptx

Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitions
altwirqi
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
yasir_cesc
 

Similar to PPS-UNIT4.pptx (20)

Lecture 9- Control Structures 1
Lecture 9- Control Structures 1Lecture 9- Control Structures 1
Lecture 9- Control Structures 1
 
Sql operators & functions 3
Sql operators & functions 3Sql operators & functions 3
Sql operators & functions 3
 
Loop's definition and practical code in C programming
Loop's definition and  practical code in C programming Loop's definition and  practical code in C programming
Loop's definition and practical code in C programming
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitions
 
11-ScriptsAndConditionals.ppt
11-ScriptsAndConditionals.ppt11-ScriptsAndConditionals.ppt
11-ScriptsAndConditionals.ppt
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
CONTROL FLOW in C.pptx
CONTROL FLOW in C.pptxCONTROL FLOW in C.pptx
CONTROL FLOW in C.pptx
 
Chap04
Chap04Chap04
Chap04
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
c++ Data Types and Selection
c++ Data Types and Selectionc++ Data Types and Selection
c++ Data Types and Selection
 
What is c
What is cWhat is c
What is c
 
Control structures pyhton
Control structures  pyhtonControl structures  pyhton
Control structures pyhton
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
ch2 Python flow control.pdf
ch2 Python flow control.pdfch2 Python flow control.pdf
ch2 Python flow control.pdf
 
175035 cse lab-03
175035 cse lab-03175035 cse lab-03
175035 cse lab-03
 
Decisions in C or If condition
Decisions in C or If conditionDecisions in C or If condition
Decisions in C or If condition
 
Programming C Part 03
Programming C Part 03Programming C Part 03
Programming C Part 03
 
Savitch Ch 03
Savitch Ch 03Savitch Ch 03
Savitch Ch 03
 
Savitch Ch 03
Savitch Ch 03Savitch Ch 03
Savitch Ch 03
 

Recently uploaded

Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
AldoGarca30
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
MayuraD1
 

Recently uploaded (20)

Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech Civil
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 

PPS-UNIT4.pptx

  • 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
  • 2. Conditional Statements If statement: a = 33 b = 200 if b > a: print("b is greater than a") O/P: SRM INSTITUTE OF SCIENCE AND TECHNOLOGY, RAMAPURAM
  • 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
  • 14. Conditional Statements Python Loops Python has two primitive loop commands:  while loops  for loops 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)
  • 35. Python Exception Handling SRM INSTITUTE OF SCIENCE AND TECHNOLOGY, RAMAPURAM Catching Specific Exception:
  • 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')