How to exit a while loop when the input or variable in a user-defined function meets the condition in Python

while loop string python
python while loop user input
python while loop multiple conditions
conditional loop python
while loop in python
python while loop exercises
how to end a while loop in python
while loop practice problems python

I'm trying to use a while loop to iterate through a function in Python which requests a user input, i.e. commitchanges to perform one of two actions, and if the input is not valid after a few attempts to close the program.

If the input is equal to 'y' (Yes) then the program should commit the changes made by the SQL update query, i.e. conn.commit()

If the input is equal to 'n' (No) then the program should not commit the changes and rollback, i.e. conn.rollback()

If the input is anything other than 'y' or 'n' then the program should alert the user that that is not a valid input.

Here's my current function:

def action(inputattempts):
    commitchanges = input()
    if commitchanges.lower() == 'y':
        try:
            conn.commit()
            print ('Table Updated. No. of records updated:', totalupdates)
        except cx_Oracle.DatabaseError as error:
            print(error)
    elif commitchanges.lower() == 'n':
        conn.rollback()
        print ('Rollback - No updates made to table')
    else:
        print ('Not a valid selection - Try again')
        print (inputattempts)

Where the variable totalupdates is a global variable defined later on in the program which counts the number of records affected by the curs.execute SQL query.

I'm then calling the above function in a while loop as follows:

inputattempts = 0
while (inputattempts < 4):
    inputattempts += 1
    action(inputattempts)
print ('FAILED')

Essentially, I'd like the user to have a maximum of 4 attempts at entering a valid input, i.e. 'y' or 'n' before the program aborts if the input is not valid after those attempts. However, if 'y' or 'n' is entered the first time the function is called the program should either commit or rollback and exit the loop.

Currently, I'm having to complete 4 iterations of the while loop regardless of my input. Is there a way I can tweak any of that syntax to exit the loop when the above conditions are met?


As suggested by @rdimaio:

Your action function returns True if the flow was valid; False otherwise (i.e. invalid user input).

def action(inputattempts):
    commitchanges = input()
    if commitchanges.lower() == 'y':
        try:
            conn.commit()
            print ('Table Updated. No. of records updated:', totalupdates)
        except cx_Oracle.DatabaseError as error:
            print(error)

        return True
    elif commitchanges.lower() == 'n':
        conn.rollback()
        print ('Rollback - No updates made to table')

        return True

    print ('Not a valid selection - Try again')
    print (inputattempts)

    return False

Then, you check whether the flow was valid in your while and break when condition is met:

input_attempts = 0

while input_attempts < 4:
    input_attempts += 1

    if action(input_attempts):
        break

if input_attempts == 4:
    print ('FAILED')

3.3. While Statements, How to break out of while loop in Python? Your action function returns True if the flow was valid; False the flow was valid in your while and break when condition is met: Just get the user input outside of actions() and pass it as a parameter: while then change your while loop to break the loop when The while loop can be found in most programming languages. Although its exact function differs from language to language, it is mostly used to perform an action provided certain conditions are met. The while loop is used extensively in Python and alone with for and if-else loops, forms the basis of manipulating data in the …


Just get the user input outside of actions() and pass it as a parameter:

while inputattempts < 4:
    inputattempts += 1
    commit_changes = input()
    action(inputattempts, commit_changes)

Then after the call to action() you can condition on what you need and break out if appropriate.

Calling a method in the while loop condition, A Python while loop behaves quite similarly to common English usage. In English you could mean to stop as soon as the condition you want to test becomes false. For example, in readLines0.py , the user is prompted for the exact number of In this exercise write safe utility function replacements for the input function  The break statement in Python terminates the current loop and resumes execution at the next statement, just like the traditional break found in C. The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.


You can return a value from your function and check over it's returned value to break or not.

def action(inputattempts):
    correct_input = True
    commitchanges = input()
    if commitchanges.lower() == 'y':
        try:
            conn.commit()
            print ('Table Updated. No. of records updated:', totalupdates)
        except cx_Oracle.DatabaseError as error:
            print(error)
    elif commitchanges.lower() == 'n':
        conn.rollback()
        print ('Rollback - No updates made to table')
    else:
        print ('Not a valid selection - Try again')
        print (inputattempts)
        correct_input = False           
    return correct_input

then change your while loop to break the loop when

inputattempts = 0
while (inputattempts < 4):
    inputattempts += 1
    if action(inputattempts):
        break
print ('FAILED')

Using else conditional statement with for loop in python , Are method calls allowed in a condition in a while loop? Initialize a variable used in the test condition: Include a test condition that causes the loop to end when the condition is false: Within the loop body, update the variable used in the test condition: 2. Enter and execute the following code using input values where number. number <10; 10< number < 20; number=20; 20< number < 30; Number > 3


Have your function return a flag telling whether or not the input was accepted:

def action(inputattempts):
    commitchanges = input()
    if commitchanges.lower() == 'y':
        try:
            conn.commit()
            print ('Table Updated. No. of records updated:', totalupdates)
            return True  # <-- New
        except cx_Oracle.DatabaseError as error:
            print(error)
    elif commitchanges.lower() == 'n':
        conn.rollback()
        print ('Rollback - No updates made to table')
        return True  # <-- New
    else:
        print ('Not a valid selection - Try again')
        print (inputattempts)
        return False  # <-- New

Now in your loop, you can do

inputattempts = 0
while (inputattempts < 4):
    inputattempts += 1
    if action(inputattempts):
        break
print ('FAILED')

where the break simply exists the loop. Also, I imagine that the print of 'FAILED' should only occur if the loop is exited after the 4 attempts, not if the break was reached. This can be achieved using else. Finally, your while loop really only counts, and so a for loop is more appropriate. Consider

for inputattempts in range(4):
    if action(inputattempts):
        break
else:
    print ('FAILED')

while loop to repeat when condition is true, . :) It's never a good idea to compare to a boolean result to a boolean literal. Python allows an optional else clause at the end of a while loop. This is a unique feature of Python, not found in most other programming languages. The syntax is shown below: while <expr>: <statement(s)> else: <additional_statement(s)> The <additional_statement (s)> specified in the else clause will be executed when the while loop terminates.


Python For & While Loops: Enumerate, Break, Continue Statement, What are the four elements of while loop in Python? While Loop. In Python, while loops are constructed like so: while [a condition is True]: [do something] The something that is being done will continue to be executed until the condition that is being assessed is no longer true. Let’s create a small program that executes a while loop. In this program, we’ll ask for the user to input a password.


While Loops in Python 3, In this tutorial, we will go over how while loops work and how. jumps back to the start of the while statement until the condition is False. This means that if the user inputs the string password , then the loop will stop and the Then the variable password is set to the user's input with the input() function. Using for loops and while loops in Python allow you to automate and repeat tasks in an efficient manner. But sometimes, an external factor may influence the way your program runs. When this occurs, you may want your program to exit a loop completely, skip part of a loop before continuing, or ignore that external factor.


4. Conditionals and loops, It is standard in Python to use four spaces for indenting. Python has two statements for iteration – the for statement, which we met last A new assignment makes an existing variable refer to a new value (and stop referring to the old value). call last): File "<interactive input>", line 1, in NameError: name 'x' is not defined. While loops, if set to "True" basically means they will continuously cycle through the loop forever, unless you enter a "break" function within the loop's body if a certain condition has been met. (e.g. if what the user has entered something you deem as correct or if a certain variable with a value has reached a certain number)