Nicholas Agrawal
Nicholas Agrawal

Reputation: 33

How do I find the len() of multiple strings?

I need to find the len() of multiple strings.

current_year = input ("What year is it?")

current_year = int(current_year)

birth_year = input ("What year were you born in?")

birth_year = str(birth_year)

if len(birth_year) != 4:
    print ("Please make your year of birth 4 digits long.")
else:
    birth_year = int(birth_year)
    print("You are " + str(current_year  -  birth_year) + " years old.")

I would like to include the len() of birth_year.

Upvotes: 0

Views: 1726

Answers (2)

krewsayder
krewsayder

Reputation: 446

Here is a way to get what you want that is somewhat more dynamic. With this basic function, if a user inputs an inappropriate string, they will be asked to retry. You could even add a line to check if the year was after the current year.

Note that there is a loop in here with an exit that doesn't have a constraint. If you were going to implement this, I'd add a counter as well which would kill the process to prevent infinite loops.

def get_year(input_string):

    # Set loop control Variable
    err = True

    # while loop control variable = true
    while err == True:

        # get input
        input_year = input(input_string + '  ')

        # Ensure format is correct        
        try:

            # Check length
            if len(input_year) == 4:

                # Check Data type
                input_year = int(input_year)

                # if everything works, exit loop by changing variable
                err = False

        # if there was an error, re-enter the loop
        except:

            pass

    # return integer version of input for math
    return input_year

# set variables = function output
birth_year = get_year('What year were you born? Please use a YYYY format!\n')
current_year = get_year('What is the current year? Please use a YYYY format!\n')

# print output displaying age
print("You are " + str(current_year  -  birth_year) + " years old.")

Upvotes: 1

Barmar
Barmar

Reputation: 780974

Use an elif statement to check the current year input.

current_year = input ("What year is it?")    
birth_year = input ("What year were you born in?")

if len(birth_year) != 4:
    print ("Please make your year of birth 4 digits long.")
elif len(current_year) != 4:
    print ("Please make the current year 4 digits long.")
else:
    birth_year = int(birth_year)
    current_year = int(current_year)
    print("You are " + str(current_year  -  birth_year) + " years old.")

There's no need for birth_year = str(birth_year), since input() always returns a string.

You should probably include try/except code around the calls to int(), so you can print an error if they enter a year that isn't actually a number.

Upvotes: 1

Related Questions