In this Python tutorial, I will explain to you how to apply the try except in while loop Python. This will also explain many ways to handle the exception in the while loop with the continue and break statements.
Like many modern programming languages, Python error handling and control flow mechanisms. One of these mechanisms is the try-except construct which is used to catch and handle exceptions. Combined with a while loop, this construct can be especially useful when dealing with uncertain inputs or unpredictable processes.
The while loop in Python repeatedly executes a code block as long as a condition is True. The syntax is:
while condition:
# Code to be executed while the condition is true
While the try block lets us test a block of Python code for errors and the except block lets us handle those errors in Python. The syntax is:
try:
# Code that might cause an error
except SomeSpecificError:
# What to do in case of that specific error
Flow statements in Python influence the execution of loops (for and while):
- break Statement: The break statement in Python is used to exit the current loop prematurely, stopping all further iterations.
- continue statement: The continue statement in Python is used to skip the rest of the current iteration and jump to the next iteration of the loop.
While try except Python
Using a while loop in conjunction with try-except is a powerful combination, especially when waiting for user input or dealing with unpredictable processes. As the Python try while will hold the block of code that can cause the error and the Python while except will handle the error.
This way, even if an error occurs, the program can continue running and prompt the user for correct input or try the process again.
There can be many different ways to use try-except block within a while loop in Python. Let’s see them with illustrative examples:
Example-1: Simple While loop with the try-except block in Python
For instance, We’ve created a simple program in Python where users input a temperature in Fahrenheit, and the Python program converts it to Celsius. If users input something that’s not a valid number, the Python program should inform them and prompt them for a valid temperature again.
Here, Python while True creates an infinite loop in Python, which will repeatedly prompt the user for input until they provide a valid number (temperature in Fahrenheit). Once they provide valid input and the conversion is successful, we can use the Python break statement to exit the loop.
def fahrenheit_to_celsius(f):
return (f - 32) * 5/9
while True:
temp = input("Enter a temperature in Fahrenheit: ")
try:
fahrenheit_temp = float(temp)
celsius_temp = fahrenheit_to_celsius(fahrenheit_temp)
print(f"{fahrenheit_temp}°F is equal to {celsius_temp:.2f}°C.")
break
except ValueError:
print("That's not a valid temperature. Please enter a number.")
The output is: The user is prompted to give a Python input for temperature in Fahrenheit. The program tries to convert the input into a floating-point number. If this fails (e.g., the user enters “hot” instead of a number), a Python ValueError exception is raised. The try-except block in Python catches the error and asks the user for valid input.
Enter a temperature in Fahrenheit: hot
That's not a valid temperature. Please enter a number.
Enter a temperature in Fahrenheit: 80
80.0°F is equal to 26.67°C.
We have taken two different inputs to see how the Python while try and while except block handle the ValueError.
Example-2: Calculating Sales Tax for Different States with Python while true continue
Imagine we’ve developed point-of-sale software in Python for a retail company that operates in multiple states across the USA. At the end of each transaction, the Python software needs to calculate and display the sales tax based on the state where the purchase is being made.
Since sales tax rates vary from state to state, we need to ask the cashier to enter the state abbreviation for each transaction. If the cashier enters an invalid abbreviation or an amount that’s not a number, the Python software should display an error message and prompt them to enter the information again.
sales_tax_rates = {'CA': 7.25, 'NY': 8.875, 'TX': 6.25}
while True:
state_abbr = input("Please enter the state abbreviation:").upper()
try:
purchase_amount = float(input("Enter the purchase amount ($): "))
if state_abbr not in sales_tax_rates:
raise KeyError
tax = purchase_amount * sales_tax_rates[state_abbr] / 100
print(f"The sales tax for a purchase of ${purchase_amount:} in {state_abbr} is ${tax:}")
break
except KeyError:
print(f"We don't have tax data for {state_abbr}. Please enter a valid state abbreviation.")
continue
The output is:
Please enter the state abbreviation:sa
Enter the purchase amount ($): 1000
We don't have tax data for SA. Please enter a valid state abbreviation.
Please enter the state abbreviation:ca
Enter the purchase amount ($): 1000
The sales tax for a purchase of $1000.0 in CA is $72.5
Here, we have taken two different inputs to see how while try except Python is handling the exception that occurred with the help of while true continue and break statements in Python.
Example-3: Mapping Fruit Names to Their Respective Colors with try except in while loop Python
For instance, We’re designing a simple game for children in Python where they need to match fruits with their respective colors. As an aid, we’re developing a utility that tells the color of a fruit when its name is entered in Python.
fruit_to_color = {'Apple': 'Red', 'Banana': 'Yellow', 'Blueberry': 'Blue', 'Grapes': 'Purple', 'Orange': 'Orange'}
while True:
fruit_name = input("Enter the name of the fruit (or 'exit' to quit): ").title()
if fruit_name == 'Exit':
print('Thank You')
break
try:
color = fruit_to_color[fruit_name]
print(f"The color of {fruit_name} is {color}.")
except KeyError:
print(f"{fruit_name} not found in our database. Please try another fruit.")
continue
The output is: Here, we attempt to retrieve the color of fruit directly from the fruit_to_color Python dictionary. If the fruit doesn’t exist in the dictionary, it will raise a Python KeyError. This exception is caught in the except block in Python, providing feedback to the user and prompting them to try again. The loop continues until a valid fruit is entered or the user decides to exit.
Enter the name of the fruit (or 'exit' to quit): Pine apple
Pine Apple not found in our database. Please try another fruit.
Enter the name of the fruit (or 'exit' to quit): Exit
Thank You
This way we can handle the error with Python try except while loop,
Conclusion
In this Python article, we have seen how to try except in while loop Python can handle errors. Here we have seen how while try except Python holds the block of code that can through the error and how while except Python handles the error.
Combining while loop with try-except constructs in Python can create resilient scripts, especially in situations where user input might be unpredictable. With relevant, localized examples like those above, it’s easier to grasp the practical applications of this powerful combination in Python.
You may also like reading the following articles.
- While loop with multiple conditions in Python
- Extract text from PDF Python
- Python loop through a list
- For loop vs while loop in Python
- Python for loop index
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.