Home > other >  I need to ask for an input inside of a function, but the input will not work
I need to ask for an input inside of a function, but the input will not work

Time:01-04

I was given a prompt: Define a function: takes no args, prompts the user for an input. If the user inputs a string with any special characters(?,!,$,etc...), return False. Otherwise, return the input word.

My code currently is:

def hasspec():
     key = input('Give a word: ')
     for q in key:
        if q == "abcdefghijklmnopqrstuvwxyz":
            return key
        else:
            return False

I was expecting to be asked for an input, but instead I am returned: <function hasspec>

CodePudding user response:

There are a few issues with your program: first, you should call the function so that the function will come to work for you; secondly the way you check special character is not correct; lastly as earlier comments point out that the q only check one single character.

You could use string lib and puntuation to help you. It includes '!"#$%&'()* ,-./:;<=>?@[\]^_`{|}~'

To correct those issues, this code should achieve your goal:


from string import punctuation

def hasspec():
    word = input('Give a word: ')
     
    if any(c in punctuation for c in word):  # go thru each char and check
        return False
    
    return word                    # it's a good word
            

print(hasspec())                   # try a few words .... now

CodePudding user response:

What you need to do in order to make this work is to call the function. You do this by giving it parentheses and any arguments that it needs. In this case it has none so you should just have empty parentheses ().

So you need to do hasspec() in order for the function to run. I recommend watching sentdex's tutorial about functions.

Also note, if what you are trying to do is check that every character is an alphabetical character, then you should instead loop on the key, which contains your input string. This way you get check every character against the string of alphabetical characters.

def hasspec():
     key = input('Give a word: ')
     for c in key:
        if c in "abcdefghijklmnopqrstuvwxyz":
            return key
        else:
            return False

There is further improvement is using the .isalpha() method on the string, which automatically checks if all the characters in the string is an alphabetical character. You can do this as such:

def hasspec():
     key = input('Give a word: ')
     return key.isalpha()
  • Related