pythonfunctionif-statementsyntaxisalpha

I want to be able to enter a word via an input, return true if the word contains english and false if it doesn't


I have written this code to ask for an input and then check if that word is english. If yes return true, if not return false.

def onlyEnglishLetters(word):
     word = (input("Enter word here: "))
 if word.isalpha():
    return true
return false

output = SyntaxError: 'return' outside function


Solution

  • Here is an example of what you can do:

    def onlyEnglishLetters():
        word = (input("Enter word here: "))
        if word.isalpha():
            return True
        else:
            return False
    

    Your original code creates an error because the second return statement is outside of the function. By putting it in an else statement it becomes a part of the function.

    You don't need to have 'word' as an argument in the function because you set the value with the input statement.

    Also, this will not print the word 'True' or 'False', it only returns that value.

    Edit:

    If you want the code to print True or False then this is what you should do:

    def onlyEnglishLetters():
        word = (input("Enter word here: "))
        if word.isalpha():
            print(True)
        else:
            print(False)
    
    onlyEnglishLetters()