Python Forum
Need help with isdigit() and isalpha() function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help with isdigit() and isalpha() function
#1
I need to write a program that has these conditions:
- Length must be exactly 9
- The first letter must be S, T, F or G
- Must consist of 7 digits
- Reference letter must be A to Z or a to z

Expected Output:

Output:
Enter String: S1234567A Valid String Enter String: X123456789B Error, Length must be exactly 9 Enter String: S12345XXB Error, Must consist of 7 digits
The requirement is to make use of isdigit() and isalpha() function but I read up on various resources online it seems it's most commonly used to return either True/False for the value.

My Code:

def main():
    enterstr = input("Enter String: ")
    firstletter = ["S", "T", "F", "G"]
    refletter = ['A', 'B', 'C', 'D']
    if enterstr.isdigit() < 7:
        print("Error, Must consist of 7 digits")
    elif enterstr.isalpha() [0] != firstletter:
        print("Error, The first letter must be S, T, F or G")
    elif enterstr.isalpha() [-1] != refletter:
        print("Error, Reference letter must be A to Z or a to z")
    elif enterstr.count < 9:
        print("Error, Length must be exactly 9")
    else:
        print("Valid String")
main()
I keep getting the output "Error, Must consist of 7 digits" no matter how many characters the String is. Need your advise, thanks.
Reply
#2
Isdigit and isalpha return true or false
len() returns the length of the object
Recommended Tutorials:
Reply
#3
You are trying to do too many things at once. Although you will get the skills to combine some of these processes, I strongly suggest you tackle the requirements one at a time, like this...
def main():
    enterstr = input("Enter String: ")
    valid_string = True
    """ First test - is the length exactly 9 """
    if len(enterstr) != 9 :
    """ Print the error message and change the flag"""
    """ Will leave the first letter check to you
        Next must contain 7 digits """
    digit_count = 0
    for index in range(0,8):
        if enterstr[index].isdigit():
            digit_count += 1
    """Now check to see if the digit count passes, print error if not, adjust the flag.
        """You can write the rest from here """
        
main()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problems with isdigit function Omegax77 2 3,001 Jun-30-2018, 06:48 PM
Last Post: woooee

Forum Jump:

User Panel Messages

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