Why does my loop return a string if it is accepted in the "if" but returns a "None" once it passed through the "else"

43 Views Asked by At

Apologies for the vague title. I wasn't sure how to make it specific enough.

I have some code that asks for a word and then turns it into a list of characters. I wanted to pass it through a loop to check in its isalpha().

When I run it. If my word is alpha it works fine. If my word has digits, it will restart the loop as planned and ask again.

However, the word gathered after a digit attempt will return a "None" and throw up an error when it tries to turn it into a list.

def start():
    word = input("Enter word to turn into a list")
    if word.isalpha():
        word = word.lower()
        return word
    else:
        print("Alpha only please")
        start()

user = start()
word_list = list(user)
print (word_list)
1

There are 1 best solutions below

0
Ritvik The God On

This is because an implicit return None is observed in cases where a function does not return a value.

The above code is the same as below:

def start():
    word = input("Enter word to turn into a list")
    if word.isalpha():
        word = word.lower()
        return word
    # all paths above return a value, so technically `else` is redundant here
    # else:
    print("Alpha only please")
    start()
    ## added ##
    return None

However, as mentioned in the comments, what you really want to use here is a while loop:

def start():
    while 1:  # infinite loop, exited with a `return` or `break` statement
        word = input("Enter word to turn into a list: ")

        if word.isalpha():
            # looks good, exit loop and return the value
            return word.lower()

        print("Alpha only please\n")
        # continue to the next `while` loop iteration

user = start()