Home > database >  Good day everyone, i am a rookie here. However, i need a remedy with regard to this code
Good day everyone, i am a rookie here. However, i need a remedy with regard to this code

Time:11-06

My aim is to exempt numeric and alphanumeric inputs by the user in the first, middle and last name. However, if I try an input such as 'ay123' in any of the names it takes it as an alphabetic character and the code continues operation which is not meant to be. I have tried d.isalpha(), isnumeric(), isalnum() but to no avail

import string

print('Welcome to the result checker, for SENIOR SECONDARY SCHOOLS ONLY \n')

alph= string.ascii_letters
print(nums)

def alpha(aa):
    found= False
    for i in alph:
        if aa.find(i) > -1:
            found= True
    return found
while True:
    a = str(input('Enter student First Name: ')).upper()
    b= str(input('Enter student middle name: ')).upper()     
    c= str(input('Enter student Last name: ')).upper()
    d= a ' ' b ' ' c

    if alpha(d):
        print('Welcome')
        break
    else:
        print('Invalid entry, input alphabetic characters only!')

CodePudding user response:

Your "alpha" function returns True if any letter is found in the answer. It basically says "for every letter in the alphabet, if that letter is found in my string, we have a winner." That's not what you want at all. You want basically the opposite. "For every letter in my string, if it is not found in the alphabet, reject it." You can return as soon as you find an outcast; you don't have to check the rest of the string. Also note that you have to allow blanks, since you specifically add blanks to your name.

alph= string.ascii_letters   ' '

def alpha(aa):
    for i in aa:
        if alph.find(i) < 0:
            return False
    return True

This could also be written:

def alpha(aa):
    return all(alph.find(i) >= 0 for i in aa)

CodePudding user response:

The method isalpha() like you simply put on your question does what you want, but returns False when the string contains a whitespace. You don't need to import any library or create your own function, just use isalpha() function singly on every string. I've also done some minor fixes on your code ( e.g print(nums) )

print('Welcome to the result checker, for SENIOR SECONDARY SCHOOLS ONLY \n')

while True:
    a = input('Enter student First Name: ').upper()
    b = input('Enter student middle name: ').upper()     
    c = input('Enter student Last name: ').upper()
    full_name = [a, b, c]

    # map function apply isalpha() method on every item of the list
    check = list(map(str.isalpha, full_name))

    if False not in check:
        d = ' '.join(full_name)
        print(f'Welcome {d}')
        break
    else:
        print('Invalid entry, input alphabetic characters only!')

This is an elegant and very Pythonic way to do it.

  • Related