-2

so I am writing python program for entering name, surname and birth year in the dictionary, but the essence of this is to find errors. For example: if user write letters in the field for entering birth year then the program should warn about this until the user enters the number between 1890 and 2018. I wrote something, but then I got totally stuck.

a = input('Enter name: ')
b = input('Enter surname: ')
c = input('Enter birth year: ')

dict = {}
dict['Name'] = a
dict['Surname'] = b
dict['Birth year'] = c

while 1890 > c < 2018:
    if type(c) == str:
         print('Wrong.')
         c = input('Enter birth year: ')

2 Answers2

0

You're comparing b in the while condition, whereas b is usually a string given your dictionary's key i.e. 'Surname'. Maybe, you want to compare c in the while condition.

Edit : Chapter Input Validation of Automate the Boring Stuff with Python might help with your case.

0

The input() function returns a string. You need to convert the year value to an integer to check if it is a valid year.

For convenience, user input validation can be moved into a separate function.

Code example:


def check_year(year, min_year, max_year):
    """
    Checks if the value entered by the user
    is a valid year in the specified range.
    
    The range includes min_year and max_year.
    """
    # this part is optional, but covers the most common mistakes
    if any([
        len(year) != 4,
        not year.isdigit(),
        year.startswith('0')
        ]):
        print('The year {} is not a valid value. The correct format is four digits (YYYY).'.format(year))
        return False

    # this part converts the string to a number for comparison
    try:
        converted_year = int(year)
    except ValueError:
        print('The year {} is not a valid value. The correct format is four digits (YYYY).'.format(year))
        return False
    
    # to not include min_year and max_year use: min_year < converted_year < max_year
    if min_year <= converted_year <= max_year:
        return True
    else:
        print('The year {} is not in the {} to {} range.'.format(converted_year, min_year, max_year))
        return False

    
user_data = dict()

a = input('Enter name: ')
user_data['Name'] = a
    
b = input('Enter surname: ')
user_data['Surname'] = b

c = input('Enter birth year (from 1890 to 2018): ')
# exit the While loop if the function returns True
# otherwise, the user is asked to enter new data
while not check_year(c, 1890, 2018):
    c = input('Enter birth year: ')

# save year value as a string
user_data['Birth year'] = c

print(user_data)

See also docs:

Comparison operations in Python

int function

SO question:

Asking the user for input until they give a valid response

8349697
  • 415
  • 1
  • 6
  • 11