Попытка использовать словарь для проверки аббревиатуры из 2 букв состояния

#python

#python

Вопрос:

Я новичок в Python и пытаюсь использовать словарь для проверки 2-буквенной аббревиатуры состояния. Каждый раз, когда я ввожу аббревиатуру состояния, она просто выходит из моей программы, и я теряюсь в том, как заставить это работать. Я не получаю никаких ошибок в программе, из которой она только что вышла, прежде чем мне это понадобится. Я думаю, что использование словаря — лучший способ, но я не уверен, как заставить его работать. Мне нужно, чтобы программа проверила аббревиатуру и убедилась, что она состоит всего из 2 символов.

 import sys

print('--------------------------------------------------')
print('Welcome to the US Voter Registration System')

# processing phase
con = input('Do You Want to Continue: Yes Or No? ')

while con == 'Yes':
name = input('Please Enter Your First Name: ')
name2 = input('Please Enter Your Last Name: ')

#  Used to continue the program
con2 = input('Do You Want to Continue: Yes Or No? ')
if 'yes'.startswith(con2.lower()):
    print('Yes')
else:
    print('Thanks For Your Time!')
    sys.exit()  #  end the loop
#  Used to get the age of the voter
age = int(input('Please Enter Your Age *** YOU MUST BE 18 OR OLDER ***: 
'))
if age < 18:
    print('Must be over 18!')
    sys.exit()  #  end the loop

if age >= 120:
    print('No one is this old! Try again! ')
    sys.exit()  #  end the loop
#  Used to continue the program
con2 = input('Do You Want to Continue: Yes Or No? ')
if 'yes'.startswith(con2.lower()):
    print('Yes')
else:
    print('Thanks For Your Time!')
    sys.exit()  # end the loop
#  Used to find out if the voter is a citizen or not
cit = input('Are You A US Citizen? Answer Yes or No: ')
if cit != 'Yes':
    print('You Must Be A US Citizen!')
    sys.exit()  #  end the loop
#  Used to continue the program
con2 = input('Do You Want to Continue: Yes Or No? ')
if 'yes'.startswith(con2.lower()):
    print('Yes')
else:
    print('Thanks For Your Time!')
    sys.exit()  # end the loop
#  Used to get the state of the voter
state = input('Please Enter Your State? ' 'Please only 2 letters: ')

state2 = {
    'Alabama': 'AL',
    'Alaska': 'AK',
    'American Samoa': 'AS',
    'Arizona': 'AZ',
    'Arkansas': 'AR',
    'California': 'CA',
    'Colorado': 'CO',
    'Connecticut': 'CT',
    'Delaware': 'DE',
    'District of Columbia': 'DC',
    'Florida': 'FL',
    'Georgia': 'GA',
    'Guam': 'GU',
    'Hawaii': 'HI',
    'Idaho': 'ID',
    'Illinois': 'IL',
    'Indiana': 'IN',
    'Iowa': 'IA',
    'Kansas': 'KS',
    'Kentucky': 'KY',
    'Louisiana': 'LA',
    'Maine': 'ME',
    'Maryland': 'MD',
    'Massachusetts': 'MA',
    'Michigan': 'MI',
    'Minnesota': 'MN',
    'Mississippi': 'MS',
    'Missouri': 'MO',
    'Montana': 'MT',
    'Nebraska': 'NE',
    'Nevada': 'NV',
    'New Hampshire': 'NH',
    'New Jersey': 'NJ',
    'New Mexico': 'NM',
    'New York': 'NY',
    'North Carolina': 'NC',
    'North Dakota': 'ND',
    'Northern Mariana Islands': 'MP',
    'Ohio': 'OH',
    'Oklahoma': 'OK',
    'Oregon': 'OR',
    'Pennsylvania': 'PA',
    'Puerto Rico': 'PR',
    'Rhode Island': 'RI',
    'South Carolina': 'SC',
    'South Dakota': 'SD',
    'Tennessee': 'TN',
    'Texas': 'TX',
    'Utah': 'UT',
    'Vermont': 'VT',
    'Virgin Islands': 'VI',
    'Virginia': 'VA',
    'Washington': 'WA',
    'West Virginia': 'WV',
    'Wisconsin': 'WI',
    'Wyoming': 'WY'
}

if state != state2.get:
    print('Please Enter One Of The 50 States!')
    sys.exit()  #  end the loop

#  Used to continue the program
con2 = input('Do You Want to Continue: Yes Or No? ')
if 'yes'.startswith(con2.lower()):
    print('Yes')
else:
    print('Thanks For Your Time!')
    sys.exit()  # end the loop
#  Used to get the voters zip code
zipc = int(input('Please Enter Your Zip Code? '))
if len(zipc) != 5:
    print('You Must Enter A Vaild Zip Code!')
    sys.exit()  #  end the loop

#  Used once you are done entering data
con = input('You Are Finished Please Type Done: ')

#  Output process
print('---------------------------------------------------------')
print('Thank You For Using the US Voter Registration System ')
print('Below Is A Summary Of Your Data: ')
print('NAME: ', name, name2)
print('AGE: ', age)
print('US CITIZEN:', cit)
print('STATE: ', state)
print('ZIP CODE: ', zipc)
print('Thank You For Using the US Voter Registration System ')
print('Please Check Your Mail For More Voting Information ')
print('---------------------------------------------------------------')

# Empty Line
 

Комментарии:

1. Почему вы используете sys.exit() в середине кода? Это то, что завершает вашу программу.

2. вместо sys.exit() использования break для завершения цикла

3. Если вы вводите неправильные данные, я хочу, чтобы программа завершилась.

4. Когда вы используете break оператор, он завершает цикл while, и, таким образом, вы завершаете программу

5. О, хорошо. Я добавлю break. Нужно ли мне все еще выполнять импорт sys

Ответ №1:

Проблема может заключаться в

 if state != state2.get:
 

Приведенный выше код проверяет значение строки на соответствие встроенной функции, поскольку state2.get это встроенная функция. Это всегда оценивается как True, поскольку строка никогда не равна функции и, следовательно, завершает работу программы.

Возможно, вам лучше использовать

 if state in state2.values():
 

state2.values() выдает только значения dictionary

И поскольку вы сказали, что хотите убедиться, что введенное состояние состоит из 2 символов, вы можете использовать len() так, как вы использовали с zipc.

 if len(state)!=2:
 

Более того, кажется, что полная форма состояний нигде не используется, если вы только хотите убедиться, что введенное состояние находится в допустимом списке состояний, тогда вы можете просто создать список, содержащий сокращения всех допустимых состояний, и проверить, есть ли в списке введенные входные данные.

 state2=['AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'GU', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'MP', 'OH', 'OK', 'OR', 'PA', 'PR', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VI', 'VA', 'WA', 'WV', 'WI', 'WY']
if state not in state2:
            sys.exit()
 

Комментарии:

1. Хорошо, это имеет смысл. Я действительно запутался в том, как настроить словарь. Спасибо

Ответ №2:

 import sys

print('--------------------------------------------------')
print('Welcome to the US Voter Registration System')

# processing phase
con = input('Do You Want to Continue: Yes Or No? ')

while con == 'Yes':
name = input('Please Enter Your First Name: ')
name2 = input('Please Enter Your Last Name: ')

#  Used to continue the program
con2 = input('Do You Want to Continue: Yes Or No? ')
if con2.lower()=='yes':
    print('Yes')
else:
    print('Thanks For Your Time!')
    break  #  end the loop
#  Used to get the age of the voter
age = int(input('Please Enter Your Age *** YOU MUST BE 18 OR OLDER ***: 
'))
if age < 18:
    print('Must be over 18!')
    break  #  end the loop

if age >= 120:
    print('No one is this old! Try again! ')
    break  #  end the loop
#  Used to continue the program
con2 = input('Do You Want to Continue: Yes Or No? ')
if con2.lower()=='yes':
    print('Yes')
else:
    print('Thanks For Your Time!')
    break  # end the loop
#  Used to find out if the voter is a citizen or not
cit = input('Are You A US Citizen? Answer Yes or No: ')
if cit.lower() != 'Yes':
    print('You Must Be A US Citizen!')
    break  #  end the loop
#  Used to continue the program
con2 = input('Do You Want to Continue: Yes Or No? ')
if 'yes'.startswith(con2.lower()):
    print('Yes')
else:
    print('Thanks For Your Time!')
    break  # end the loop
#  Used to get the state of the voter
state = input('Please Enter Your State? ' 'Please only 2 letters: ')

state2 = {
    'Alabama': 'AL',
    'Alaska': 'AK',
    'American Samoa': 'AS',
    'Arizona': 'AZ',
    'Arkansas': 'AR',
    'California': 'CA',
    'Colorado': 'CO',
    'Connecticut': 'CT',
    'Delaware': 'DE',
    'District of Columbia': 'DC',
    'Florida': 'FL',
    'Georgia': 'GA',
    'Guam': 'GU',
    'Hawaii': 'HI',
    'Idaho': 'ID',
    'Illinois': 'IL',
    'Indiana': 'IN',
    'Iowa': 'IA',
    'Kansas': 'KS',
    'Kentucky': 'KY',
    'Louisiana': 'LA',
    'Maine': 'ME',
    'Maryland': 'MD',
    'Massachusetts': 'MA',
    'Michigan': 'MI',
    'Minnesota': 'MN',
    'Mississippi': 'MS',
    'Missouri': 'MO',
    'Montana': 'MT',
    'Nebraska': 'NE',
    'Nevada': 'NV',
    'New Hampshire': 'NH',
    'New Jersey': 'NJ',
    'New Mexico': 'NM',
    'New York': 'NY',
    'North Carolina': 'NC',
    'North Dakota': 'ND',
    'Northern Mariana Islands': 'MP',
    'Ohio': 'OH',
    'Oklahoma': 'OK',
    'Oregon': 'OR',
    'Pennsylvania': 'PA',
    'Puerto Rico': 'PR',
    'Rhode Island': 'RI',
    'South Carolina': 'SC',
    'South Dakota': 'SD',
    'Tennessee': 'TN',
    'Texas': 'TX',
    'Utah': 'UT',
    'Vermont': 'VT',
    'Virgin Islands': 'VI',
    'Virginia': 'VA',
    'Washington': 'WA',
    'West Virginia': 'WV',
    'Wisconsin': 'WI',
    'Wyoming': 'WY'
}

if state != state2.get:
    print('Please Enter One Of The 50 States!')
    break  #  end the loop

#  Used to continue the program
con2 = input('Do You Want to Continue: Yes Or No? ')
if 'yes'.startswith(con2.lower()):
    print('Yes')
else:
    print('Thanks For Your Time!')
    break  # end the loop
#  Used to get the voters zip code

zipc = int(input('Please Enter Your Zip Code? '))
    if len(zipc) != 5:
        print('You Must Enter A Vaild Zip Code!')
        break  #  end the loop


#  Used once you are done entering data
con = input('You Are Finished Please Type Done: ')

#  Output process
print('---------------------------------------------------------')
print('Thank You For Using the US Voter Registration System ')
print('Below Is A Summary Of Your Data: ')
print('NAME: ', name, name2)
print('AGE: ', age)
print('US CITIZEN:', cit)
print('STATE: ', state)
print('ZIP CODE: ', zipc)
print('Thank You For Using the US Voter Registration System ')
print('Please Check Your Mail For More Voting Information ')
print('---------------------------------------------------------------')