0

So I have this code:

def validate_username(username):
    find_username = cursor.execute("SELECT username FROM user WHERE username = ?", (username, ))
    if find_username.fetchone() is not None:
        username_is_valid = False
        invalid_reason = 'Username already exists'
    elif len(username) > 255:
        username_is_valid = False
        invalid_reason = 'Invalid format'
    elif not match(r"[^@]+@[^@]+\.[^@]+", username):
        username_is_valid = False
        invalid_reason = 'Username must be an email address'
    else:
        username_is_valid = True
        invalid_reason = None
    return username_is_valid, invalid_reason

So obviously, it will return one of those:

(False, 'Username already exists')
(False, 'Invalid format')
(False, 'Username must be an email address')
(True, None)

Now what I want to do is to pass those two arguments into variables so that they can be reused, printed, etc. but for some reason I can't really find how to do it online; I'm assuming because I don't word my question properly. Maybe someone here can provide some guidance?

Basically the goal here is to run the function with the username, then if the username is invalid, print why it's invalid and if it's valid, then proceed further.

G. Langlois
  • 75
  • 1
  • 8
  • Python functions can only ever return a single value. `(False, 'Username already exists')` is a single value, it is a `tuple`, and you can work with it like any other `tuple`. – juanpa.arrivillaga Mar 09 '20 at 02:06

2 Answers2

2

Just assign the output to two variables like this:

username_is_valid, invalid_reason = validate_username(username)

Alternatively, if you assign the output to a single variable, you can access its elements using slices:

username_validation = validate_username(username)
username_is_valid = username_validation[0]
invalid_readon = username_validation[1]
Clade
  • 966
  • 1
  • 6
  • 14
2

The term is tuple (x, y)is a tuple and you access these values just like you do with a list, which means (x, y)[0] returns x and (x, y)[1] returns y

Fibi
  • 427
  • 3
  • 9