-3

Python code where user inputs surname, forename that must be certain length and wont accept numeric values. I'm creating code for a website to get a user to input various questions like name, address, phone number etc. my code is working currently for each question, but every question is a while statement and I wanted to define functions for each instead (minimizing the repetition of while statements). Please see below 1. working while statement 2. def code I'm failing at creating, because it doesn't take the length or no numeric values into account. The format of my question below for parts 1. and 2. don't include the start "while" & "def" statement for some reason.

1. first_name = "First Name:\t"

while first_name:

first_name = input("First Name:\t")
if len(first_name) < 15 and first_name.isalpha():
    break
else:
    print("Invalid entry. Please try again")
    continue

second_name = "Second Name:\t"

while second_name:

second_name = input("Second Name:\t")
if len(second_name) < 15 and second_name.isalpha():
    break
else:
    print("Invalid entry. Please try again")
    continue
  1. def name(first):

    while True: if len(first) < 15 and first.isalpha(): break else: print('invalid') continue

    first = input("First Name:\t")

  • 1
    I’m afraid you’ve forgotten to ask the question. – S3DEV Dec 04 '22 at 15:45
  • 1
    Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Pranav Hosangadi Dec 04 '22 at 15:46
  • The reason they don't include the first parts is that Stack Overflow doesn't automatically format code. The formatted part is like so because of the indentation. You need to either indent or enclose it in triple backticks (`). – LercDsgn Dec 04 '22 at 15:53

1 Answers1

0

You can modify the function like this:

def name_check(name):
    while True:
        if len(name) < 15 and name.isalpha():
            break
        else:
            print('invalid')
            name = input("First Name:\t")
            continue
    return name

result = name_check(input("First Name:\t"))
print(result)