-2

I need to add 2 logic statements in the following code. I need one for if you are under the age of 18 and another one that only lets you enter 2 letters for a state. Both statements need to exit the program and I think that is where I am confused at. I am very new to python, so any help is greatly appreciated. I think I can put if statements but I don't know how to make them exit the program, I only know how to make them print

print('Welcome to the US Voter Registration System')
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: ')

    age = int(input('Please Enter Your Age *** YOU MUST BE 18 OR OLDER ***: '))

    cit = input('Are You A US Citizen? Answer Yes or No: ')

    state = input('Please Enter Your State?' 'Please only 2 letters: ')

    zipc = int(input('Please Enter Your Zip Code? '))

    con = input('You Are Finished Please Type Done: ')

    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 ')
  • You're probably looking for `sys.exit()` (don't forget `import sys` in the top of your program). Although I suggest you read the Python Tutorial https://docs.python.org/3/tutorial/ before delving into any serious code projects. – Hetzroni Jan 11 '21 at 09:00
  • You can use try and except ref: here https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – vijaykumar Jan 11 '21 at 09:02

1 Answers1

1

You can use sys.exit() to exit a program (remember to import sys at the top of your file).

You can check if age is below 18 with if age < 18: ("if age is less than 18"). For length of the state value you can use the len function which gives you the length of the string in characters (technically it gives you the length of a sequence or anything implementing the __len__ method, but that's not important with what you're trying to do).

You can also use break to end the while loop instead of exiting the program.

So to implement those measures:

import sys

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

...

    age = int(input('Please Enter Your Age *** YOU MUST BE 18 OR OLDER ***: '))

    if age < 18:
        print("Must be over 18!")
        sys.exit()  # or break to end the loop

    ..

    state = input('Please Enter Your State?' 'Please only 2 letters: ')
   
    if len(state) != 2:
        print("State must be exactly two letters.")
        sys.exit()  # or break to end the loop

    ..
MatsLindh
  • 49,529
  • 4
  • 53
  • 84