Skip to content

Python While Finally

  • by

There is no Python While Finally combination in Python. The final block is used in exception handling to ensure that a certain code block is executed regardless of whether an exception is raised. It’s typically used in a tryexcept structure.

However, the finally block doesn’t directly relate to a while loop. A while loop is used for the iterative execution of a block of code as long as a specified condition is true. The finally block, on the other hand, is focused on executing code after a tryexcept block, not after a while loop.

Here’s a basic example of how you might use the finally block with a tryexcept block:

    # Code that might raise an exception
    x = 10 / 0  # This will raise a ZeroDivisionError
except ZeroDivisionError:
    print("Cannot divide by zero")
    print("This will always be executed, regardless of an exception")

Python While Finally example

we’ll simulate a scenario where a user is repeatedly prompted to enter a number until they provide a valid input, and we’ll use a finally block to ensure that some cleanup code is executed regardless of whether an exception occurs.

def get_valid_number():
    while True:
            number = int(input("Please enter a number: "))
        except ValueError:
            print("Invalid input. Please try again.")

    return number

    result = get_valid_number()
    print("You entered:", result)
    print("Cleanup code: This will always be executed.")


Python While Finally

In this example:

  1. We define a function get_valid_number() that uses a while loop to repeatedly prompt the user for a number until a valid input is provided. The loop continues until the user enters a value that can be converted to an integer.
  2. Inside the try block, we call the get_valid_number() function to get a valid number from the user. If the user enters an invalid input (e.g., a non-numeric value), a ValueError exception is caught and an error message is displayed.
  3. Regardless of whether an exception occurs or not, the finally block is executed. In this example, we print a message indicating that the cleanup code is being executed.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading