Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Closing a program
#1
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
Reply
#2
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')
Reply
#3
Have now solved the problem by using
import sys
sys.exit()
Thanks for the reply gontajones
Reply
#4
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.')
Reply
#5
Hey would like to thank both gontajones and snippsat for all their help.
Thanks guys
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Closing a program using a G10 button MBDins 2 1,903 May-23-2021, 05:49 PM
Last Post: MBDins
  Try-except in while loop: error with closing program Lupin_III 7 2,932 Jul-03-2020, 10:57 AM
Last Post: Lupin_III

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020