
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to handle a python exception within a loop?
The looping technique in Python transforms complex problems into simple ones. It allows us to change the flow of the program so that instead of writing the same code over and over, we can repeat it a limited number of times until a certain condition is satisfied. For example, if we need to display the first ten natural numbers, we can do it inside a loop that runs up to ten iterations rather than using the print command ten times.
Python offers three ways to loop a block of code in a program: using for loops, while loops and nested loops.
In this article, let us see how we can handle exceptions within these loops.
Handling Exception in While Loops
While loops run statements (code) continuously as long as the provided condition is TRUE. It initially examines the condition before proceeding with the instructions.
Syntax
while condition: statements(code)
There are number of statements that are present inside the while loop. The condition could be anything we want it to be. When the condition fails (becomes false), the loop terminates and the execution proceeds to the next line of code.
Exception handling in while loop is very similar to the usual approach. The code containing the possibility of an exception is enclosed in a try block.
We have statements that are preceded by the keyword "except." It is possible to make "customized" exceptions: The raise statement can be used to force the occurrence of a specific exception.
Example
Assume we wish to request an integer number from the user. It is accomplished by using the input() method. However, the default value of the input obtained from this method is a string; that we must convert to an integer. It is done using typecasting with (int).
Here, we shall raise a ValueError if the input given to the method is not a valid integer. The while loop will keep asking the user to enter a correct value every time a wrong type of input is given. Once the correct value is inputted, the loop is exited. This is demonstrated in the following example −
# The loops keeps executing until the value entered is an integer while True: try: n = int(input("Please Enter an Integer: ")) break except ValueError: print(" The Integer You entered is not valid! Please try again…") print("You successfully entered an Integer!")
Output
As seen in the output below, the while loop keeps executing until the correct value is entered as an input.
Please Enter an Integer: g The Integer You entered is not valid! Please try again… Please Enter an Integer: h The Integer You entered is not valid! Please try again… Please Enter an Integer: 7 You successfully entered an Integer!
Handling Exception in For Loops
In Python, the for loop iterates across a sequence (list, tuple, string) or other iterable objects. The process of iterating across a sequence is known as traversal.
for val in sequence: loop body
On each iteration, val is the variable that takes the value of the item in the sequence.
The loop is repeated until we reach the last item in the sequence. Indentation is used to separate the body of the for loop from the rest of the code.
Let's check whether we can access an array index that is longer than the array's length and handle the subsequent exception.
Example
In the following example, we are looping through a list containing the names of months using for loop. Names of these months are printed if they exist in the list; and once the loop exceeds the length of the given list, except block is executed and output is displayed accordingly.
array = ["Jan", "Feb", "Mar", "Apr"] for i in range(5): try: print("The element from the array present in index", i,"is", array[i]) except: print ("Index out of range")
Output
The output for the program above is produced as follows −
The element from the array present in index 0 is Jan The element from the array present in index 1 is Feb The element from the array present in index 2 is Mar The element from the array present in index 3 is Apr Index out of range
- Related Articles
- How to handle exception inside a Python for loop?
- How to handle an exception in Python?
- How to handle Python exception in Threads?
- How to handle python exception inside if statement?
- How to use the try-finally clause to handle exception in Python?
- How to handle an exception in JSP?
- How to handle the Runtime Exception in Java?
- How to handle errors within WaitGroups in Golang?
- Java Program to Handle Unchecked Exception
- How to handle the exception using UncaughtExceptionHandler in Java?
- How to convert a Python for loop to while loop?
- How to handle Java Array Index Out of Bounds Exception?
- How to handle an exception in JShell in Java 9?
- What is the best way to handle list empty exception in Python?
- How do you handle an exception thrown by an except clause in Python?
