Python Forum

Full Version: Closing a program
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Have been trying to learn about dictionaries in Python 3 at Understanding Dictionaries in Python 3

# Define original dictionary
usernames = {'Sammy': 'sammy-shark', 'Jamie': 'mantisshrimp54'}

# Set up while loop to iterate
while True:

    # Request user to enter a usernames
    print('Enter a name:')

    # Assign to name variable
    name = input()

    # Check whether name is in the dictionary and print feedback
    if name in usernames:
        print(usernames[name] + ' is the name of ' + name)

    # If the name is not in the dictionary...
    else:

        #provide feedback
        print('I don\'t have ' + name + '\'s username, what is it?')

        # Take in a new username for the associated username
        username = input()

        # Assign username value to name key
        usernames[name] = usernames

        # Print feedback that the data was updated
        print('Data updated.')
But when i try to close the program using Ctrl + C i get the following error:
^CTraceback (most recent call last)
   File "/home/oldDog/usernames.py", line 13, in <module>
     name = input()
KeyboardInterrupt
Could someone help me please
This is the expected (normal) behavior when you send a CTRL+C to the running python script.
If you want to handle this Exception (KeyboardInterrupt) you can do something like this:

try:
    input('Press CTRL+C!')
except KeyboardInterrupt:
    print('\nCTRL+C Received!')
print('Bye')
Have now solved the problem by using
import sys
sys.exit()
Thanks for the reply gontajones
You should have way to break out of the while loop.
This is not nice nice have ' + name + '\'s.
Python has string formatting and the best way is f-string from 3.6 -->.
Here rewritten version,also think of that update is lost every time run code again Wink
usernames = {'Sammy': 'sammy-shark', 'Jamie': 'mantisshrimp54'}
while True:
    name = input('Enter a name,<Q> to quit: ')
    if name.lower() == 'q':
        break
    if name in usernames:
        print(f'{usernames[name]} is the name of {name}')
    else:
        print(f"I don't have {name}'s username, what is it?")
        name = input('Enter new username')
        usernames[name] = name
        print('Data updated.')
Hey would like to thank both gontajones and snippsat for all their help.
Thanks guys