Reputation: 43
In python 3.2, is there a way to stop the rest of a function executing?
Basically, I'm creating a login system as a concept for my coursework, and I've not been able to find the answer to this anywhere.
My code is split into 2 files, a logger, which handles input and output with a logfile, and the main classes, such as the database connection, the login code itself, etc.
Here is the code that handles getting user input, I'm interested in the 3rd and 4th lines, which converts 'quit' to 'QUIT0x0', to minimise the chances of the quit code being called by accident.
def getInput(input_string, type):
result = input(input_string)
if result.lower == 'quit':
result = 'QUIT0x0'
#log the input string and result
if type == 1:
with open(logFile, 'a') as log_file:
log_file.write('[Input] %s \n[Result] %s\n' %(input_string, result))
return result
#no logging
elif type == 2:
return result
#undefined type, returns 'Undefined input type' for substring searches, and makes a log entry
else:
result = '[Undefined input type] %s' %(input_string)
output(result, 4)
return result
This is the code that handles deleting a user record from the user database, I'm interested in how I would make the 4th and 5th line work and stop the rest of the function from executing:
def deleteUser(self):
self.__user = getInput('Enter the username you want to delete records for: ', 1)
if self.__user == 'QUIT0x0':
#Quit code goes here
else:
self.__userList = []
self.__curs.execute('SELECT id FROM users WHERE username="%s"' %(self.__user))
Thanks in advance, Tom
Upvotes: 0
Views: 390
Reputation: 95308
"Quit the function" is called return
:
def deleteUser(self):
self.__user = getInput('Enter the username you want to delete records for: ', 1)
if self.__user == 'QUIT0x0':
return
else:
# ...
But as you already use if/else
, the else
branch shouldn't be executed anyway, so the return is unecessary. You could just as well put a pass
in there:
def deleteUser(self):
self.__user = getInput('Enter the username you want to delete records for: ', 1)
if self.__user == 'QUIT0x0':
pass
else:
# ...
Or even use the following:
def deleteUser(self):
self.__user = getInput('Enter the username you want to delete records for: ', 1)
if self.__user != 'QUIT0x0':
# ...
Or even use an early return:
def deleteUser(self):
self.__user = getInput('Enter the username you want to delete records for: ', 1)
if self.__user == 'QUIT0x0':
return
# ...
Upvotes: 6