Home > Enterprise >  How to make sure first number in string isn't a 0?
How to make sure first number in string isn't a 0?

Time:07-04

This is for Harvard Uni's CS50P, the requirements given were that I should implement a function is_valid that checks if the user input fits the requirements for a vanity plate.

My code fulfills all requirements except "The first number used cannot be a ‘0’."

The function is_valid needs an if/else statement that takes the user input (string) (passed to is_valid as "s") and makes sure that the first number in it isn't a 0.

Ideally it would return False if the first number found is a 0 since that would make the plate invalid as a vanity plate.

The Requirements are listed here: https://cs50.harvard.edu/python/2022/psets/2/plates/

My code is the following: (Comments removed since I don't get Github formatting)

def main():
    plate = input("Plate: ")
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")

def is_valid(s):
    if len(s) < 2 or len(s) > 6: 
        return False

    if s[0].isdigit() == True or s[1].isdigit() == True: 
        return False

    for i in range(len(s)): #
        if s[i].isdigit():
            if not s[i:].isdigit():
                return False

    if s.isalnum() == False:
        return False

    else:
        return True
main()

CodePudding user response:

First you have to loop over the string, and if current char is a digit, then if it is 0, return False, otherwise, go to the next step


for i in s:
    if i.isdigit():
        if int(i)==0:
            return False
        else:
            break

  • Related