close
Python Forum
First and Last Name Input Loops
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
First and Last Name Input Loops
#1
Could anyone please help me and explain why my script doesn't work properly? My problem is concentrated on getting the proper user input for the last and first name functions. When the user enters an incorrect input, it will circle back to that particular input function, so that, for example, if they incorrectly enter their birthday, it will only bring up the birthday input again, and it works for the most part, but when a user enters an incorrect value for the first name function, it goes back to the last name function, which it shouldn't. I can't see why it does that. Could anyone please help me and explain why it isn't working as intended? I am at the end of my tether.

from datetime import datetime
ollum = []
def birthday(birthDate):
    try:
        datetime.strptime(birthDate, "%m/%d/%Y")
        return True
    except ValueError:
        return False

def function():
    loop = 'yes'
    while loop == 'yes':
            lName = input("Please enter your last name: ")
            if lName != '':
                fName = input("Please enter your first name: ")
                if fName == '':
                    print("Invalid input!")
                    continue
            else:
                print("Invalid input!")
                continue

            while True:
                birDay = input("Please enter your birthday: ")
                if birthday(birDay):
                    break
                else:
                    print("Invalid input!")
            while True:
                gender = input("Please enter your gender: ")
                if gender.upper() not in ['M', 'F']:
                    print("Invalid input!")
                else:
                    break
            while True:
                contNum = input("Please enter your contact number: ")
                if len(contNum) != 1:
                    print("Invalid input!")
                else:
                    break
                ollum.append([fName, lName, birDay, gender, contNum])
            loop = input('>>> ')
for i in ollum:
    print('First Name:', i[0])
    print('Last Name:', i[1])
    print('Birthday:', i[2])
    print('Gender', i[3])
    print('Contact Number:', i[4])
    print()

if __name__ == '__main__':
    function()
Reply
#2
continue goes to the top of the loop. Why are you using a different pattern to input first and latest name? The pattern you use for all the other info works.
Reply
#3
Try with this function()

def function():
    lName = input("Please enter your last name: ")
    while lName == '':
        lName = input("Invalid input! Please enter your last name: ")
    # got something for last name, now do the same again for first name
    fName = input("Please enter your first name: ")
    while fName == '':
       fName = input("Invalid input! Please enter your first name: ")
    # got the first name, now get dob
    birDay = '1111111111'
    while not birthday(birDay) :
        birDay = input("Please enter your birthday in the format MM/DD/YYYY: ")
    gender = 'X'
    while not gender in ['M', 'F']:
        gender = input("Please enter your gender in the format M or F:  (Since Donald T we do not accept non-binary!)")
    contNum = 'X'
    while not contNum.isdigit():
        contNum = input("Please enter your contact number: ")
    ollum.append([fName, lName, birDay, gender, contNum])
    print('Thank you and goodbye!')
Users don't always enter the right things. Checking user input is important. For that the module re is very useful. If you want to learn Python, it is a very good idea to know at least something about how re works.

I just learnt last week that, in re, \w does not only mean letters, it means digits and underscore too!

Try this link, or this link for info on regular expressions. Or just search: regex for finding (whatever you want to find here)

Here some examples of re at work:

import re

# this will find letters with accents, Chinese names, not sure what other languages
# Chinese names are written together, no spaces 朱晓云  Family name is 朱 plus given names 晓云

e = re.compile(r'(?:(?![0-9_])[\w ])+')
names = [ '123 Belén Dámaso 456', 'Jürgen  Özgür Übermensch 1999', '1999 John Smith',  '朱晓云', 'Chloé Inès', 'Chloë Gérard']
for name in names:
    res = e.search(name)
    if res:
        # .strip() removes leading or trailing whitespace
        print(res.group().strip())

f = re.compile(r'(?:(?![0-9_])[\w])+') # no space after w to just get 1 name
for name in names:
    res = f.search(name)
    if res:        
        print(res.group())

dob = input('Please enter you Date of Birth in this format: mm/dd/yyyy ')
# the user has fat fingers and enters: #$%01/11/2000 abc
# \d means digit so we are looking for 2 digits/2 digits/4 digits
# someone may enter 13 for month, or 32 for day. We can find ways to catch that problem too.
g = re.compile(r'\d{2}/\d{2}/\d{4}')
res = g.search(dob)
res.group() # returns  '01/11/2000' from #$%01/11/2000 abc

sex = re.compile(r'[fmFM]{1}')
mf = input('Please enter m or M or f or F for your gender. (Since Donald T, we don\'t do non-binary!) ')
# user enters M + F
res = sex.search(mf)
res.group() # returns 'M' from M + F

# getting phone numbers is a lot like getting your Date of Birth, just more numbers. Try it!
phone = input('Please enter your phone number in this format: +countrycode diallingcode phonenumber ')
# search for: regex to find phone numbers  on the web             
telnr = re.compile(r' # put your regular expression here #')
So, if your result, res, is empty, you can just stay in a while loop until you have a result and res.group() contains what you want, or something like what you want!

Good luck with your homework!
Reply
#4
Hi,

@Anunderling: general advise: don't write spaghetti code. It's hard to read, hard to maintain and it is harder to loop through certain sections. In the given case, you could write functions for input and functions for validation of the input. Like you e.g. did for validating the birth date Depending on what input you need to validate the re module may be indeed your friend, as explained above.

And to make the code more readable -> follow the PEP8 and use proper, understandable variable names. lName is bad, pythonic is last_name. function is hyper-generic and the name couldn't be more meaningless for a function. The name of a function should describe what it is doing, like e.g. user_data_input or ask_for_user_data.

Regards, noisefloor
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  validating user input and loops Austin11 7 8,474 Nov-03-2017, 12:24 AM
Last Post: Austin11

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020