Luis Alfonso
Luis Alfonso

Reputation: 31

My function drops me in the return a "none" when I thought I placed a string?

I have two files and I want to store in Username.txt, but my function just drops me a "None".

def username_input(user):
    user_len = int(len(user))
    while user_len > 12 or not (user.isalnum()):
        print("Error: the username must be an alphanumeric value \nand have as maximum 12 characters")
        user = input("Type a valid username: ")
        user_len = int(len(user))
        if user_len <= 12 and user.isalnum():
            return user



with open("Username.txt", "a") as usr_txt:
    usr = username_input(user = input("Type a username: "))
    usr_txt.write(usr)

Upvotes: 1

Views: 94

Answers (3)

Farhan
Farhan

Reputation: 439

If I understand correctly, you want to ask the user for a username and then store their input in a file called Username.txt if it matches certain criteria.

The reason your code returns None at the moment is due to the conditions of the while loop not being satisfied. Because there is no default return statement after the while loop, if the while loop's conditions are not met, the function will exit and return None.

I suggest refactoring your code slightly:

def username_input():
    while True:
        user = input("Type a valid username: ")
        if len(user) <= 12 and user.isalnum():
            return user
        else:
            print("Error: the username must be an alphanumeric value \nand have as maximum 12 characters")

with open("Username.txt", "a") as usr_txt:
    usr = username_input()
    usr_txt.write(usr)

As a side note, this programming construct is called "loop-and-a-half". It is Python's equivalent of the "do-while" loop. See here for more information.

Upvotes: 1

dcg
dcg

Reputation: 4219

As @Michael Butscher said, if the username you pass the first time doesn't meet the while condition you're giving None back. To fix that you can remove the inner if check and return the username before leaving your function:

def username_input(user):
    while len(user) > 12 or not (user.isalnum()):
        print("Error: the username must be an alphanumeric value \nand have as maximum 12 characters")
        user = input("Type a valid username: ")
    return user

Upvotes: 1

recnac
recnac

Reputation: 3744

In python, no return or return means return None. If never enter the while user_len > 12 or not (user.isalnum()):, it will reach end and no return here, so it will get None from outside, when you call username_input.

Hope that will help you, and comment if you have further questions. : )

Upvotes: 3

Related Questions