Character checking function not functioning

Question:

I’m working on learning by making a hangman game and I’m trying to validate user input to require a user enter a five character word, with no spaces, special characters or numbers.

Everything worked until I defined the containsspec() function and tried to implement it.

Here’s the main game file, and then the file it’s calling which contains the functions.

#text-based hangman project

#import defined functions from fun.py
from fun import *

#get player1 input and validate that it's at least five characters long, with no numbers or spaces
print("Please select any word with five characters or more:")

c = 0
while c == 0:
    w = getpass.getpass(prompt = "")
    w = list(w)
    if len(w) < 5 or containsnumber(w) or containsspace(w) or containsspec(w):
        print("Your input is invalid. Please try again.")
    else:
        print("Got it - thank you!")
        c += 1

File that contains the functions:

#contains functions for 1.py

import getpass

def containsnumber(value):
    for character in value:
        if character.isdigit():
            return True
    return False

def containsspace(value):
    for character in value:
        if character == " ":
            return True
    return False

def containsspec(value):
    for character in value:
        if character.isalnum():
            return False
    return True

So if w contains a character that isn’t alphanumeric, it should return True, and the main game should print "Your input is invalid. Please try again. Right?

I’m just super confused about why this isn’t working. I’m learning, so I’m not interested in hearing about how I could change the whole code. I’m really interested in just why containsspec() isn’t working.

Asked By: Jonathan Jackson

||

Answers:

Try this:

def containsspec(value):
    return not all(character.isalnum() for character in value)

I believe your issue is that you are immediately returning false when you detect an alphanumeric character, which isn’t what you want because you need to make sure every letter is alphanumeric.

The code above applies a boolean .isalnum() to each character in value, and if every character is alphanumeric, it will return False (indicating that it does not contain special characters), else it will return True. Notice the not! That is important!

You could also make it say any(not character.isalnum() for character in value) — the two are equivalent.

Answered By: Ryan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.