Firstly, you are using input
, this is essentially evaluating the user input. So let me show you with an example:
>>> input("?")
?>? 1 + 1
2
Use raw_input
instead. If you are using Python3 however, keep using input
.
Your problem lies in TF
. You are essentially checking whether the empty string is empty or not, so for any kind of input (that is not empty), it will will simply print out the value, because it will the if
statement will evaluate to True
even if the input is something like hello world
. A better approach would be something like this:
if user_input in DB
This will check to see if user_input
is in the keys for your database dictionary.
Thirdly, you are looping through the keys pairs in your dictionary, when you write this for i in DB:
. Why are you doing this in the first place? Simply use the in
keyword to search for keys in a dictionary as described above. So, a functioning program would be something like this:
DB = {'ICMP': 'internet control message protocol', 'RIP': 'RIP Description',
'ipv4': 'Internet protocol v4', 'ipv6': 'IP version 6'}
if __name__ == '__main__':
# Running loop
while True:
# Taking user input
user_input = raw_input("Please enter a protocol, press Q to quit")
# If the input is Q, then we break the loop
if user_input == 'Q':
break
# If the value of user_input is inside DB, then we print it
if user_input in DB:
print DB[user_input]
# Else, we ask the user to add a description, and add it to our dictionary
else:
user_value = raw_input("Please enter a value for your new protocol")
# Adding to dictionary using the update method
DB.update({user_input: user_value})