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?