So I understand the logic but don't know how to get it to do what I want. I feel it's super simple but... I need it to record the last valid answer and store it into I but it returns the second to last value since the while loop doesn't iterate again. Relevant code and pictures are attached. Thank you all for any help.
INVALID_CHARACTERS = r"!#$%&'()* ,-.:;<=>?@[]^_`{|}~\/" '"'
INVALID_NUMBERS = "1234567890"
INVALID_LETTERS = "abcdefghijklmnopqrstuvwxyz"
def letter_validity_check(i, msg):
"""Function checks entered answers against a list of invalid characters and invalid numbers"""
while len(i) == 0 or any(c in INVALID_CHARACTERS for c in i) or any(c in INVALID_NUMBERS for c in i):
i = input("First name can not be blank, contain special characters, or numbers. Try again. \n" msg)
while len(i) != 0 and any(c not in INVALID_CHARACTERS for c in i) and any(c not in INVALID_NUMBERS for c in i) and any(c in INVALID_LETTERS for c in i):
print (i)
return i
while len(FIRST_NAME) == 0:
MESSAGE = "What is your first name?: "
FIRST_NAME = input(MESSAGE)
letter_validity_check(FIRST_NAME, MESSAGE)
print(FIRST_NAME)
exit_checker(FIRST_NAME)
CodePudding user response:
You have a few issues here:
- syntax errors mixing
i
andI
- not saving the corrected name to FIRST_NAME
- unnecessary 2nd while loop in
letter_validity_check
Here's a working solution that corrects these issues:
INVALID_CHARACTERS = r"!#$%&'()* ,-.:;<=>?@[]^_`{|}~\/" '"'
INVALID_NUMBERS = "1234567890"
INVALID_LETTERS = "abcdefghijklmnopqrstuvwxyz"
def letter_validity_check(name, msg):
"""Function checks entered answers against a list of invalid characters and invalid numbers"""
while (
len(name) == 0
or any(c in INVALID_CHARACTERS for c in name)
or any(c in INVALID_NUMBERS for c in name)
):
name = input(
"First name can not be blank, contain special characters, or numbers. Try again. \n"
msg
)
return name
FIRST_NAME = ""
while len(FIRST_NAME) == 0:
MESSAGE = "What is your first name?: "
FIRST_NAME = input(MESSAGE)
FIRST_NAME = letter_validity_check(FIRST_NAME, MESSAGE)
print("Your first name is", FIRST_NAME)
A simpler version might be:
MESSAGE = "What is your first name? "
first_name = input(MESSAGE)
while not first_name.isalpha():
print("First names may only contain alphabetic characters. Please try again.")
first_name = input(MESSAGE)
print("Your first name is", first_name)