添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

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:
        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):
        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 Python exception in Threads?
  • How to handle python exception inside if statement?
  • How to handle an exception in JSP?
  • How to handle the Runtime Exception in Java?
  • Java Program to Handle Unchecked Exception
  • How to handle errors within WaitGroups in Golang?
  • How to handle the exception using UncaughtExceptionHandler in Java?
  • How to convert a Python for loop to while loop?
  • How to handle an exception in JShell in Java 9?
  • How to handle Java Array Index Out of Bounds Exception?
  • 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?
  • How to handle an exception using lambda expression in Java?\n
  • How to catch a python exception in a list comprehension?
  • Kickstart Your Career

    Get certified by completing the course

    Get Started
  • Business Analytics Certification
  • Java & Spring Boot Advanced Certification
  • Data Science Advanced Certification
  • Cloud Computing And DevOps
  • Advanced Certification In Business Analytics
  • Artificial Intelligence And Machine Learning
  • DevOps Certification
  • Game Development Certification
  • Front-End Developer Certification
  • AWS Certification Training
  • Python Programming Certification
  • COMPILERS & EDITORS
  • Online Java Compiler
  • Online Python Compiler
  • Online Go Compiler
  • Online C Compiler
  • Online C++ Compiler
  • Online C# Compiler
  • Online PHP Compiler
  • Online MATLAB Compiler
  • Online Bash Compiler
  • Online SQL Compiler
  • Online Html Editor
  • Tutorials Point is a leading Ed Tech company striving to provide the best learning material on technical and non-technical subjects.