Reputation: 23
import sys
lijst_salades = {'Eiersalade' : 5.99,
'Paprikasalade' : 6.05,
'truffelsalade': 3.99
}
input = (sys.stdin.readline())
print(lijst_salades[input])
it gives me an error
Traceback (most recent call last): File "C:/some/random/dir/right/here/progr.py", line 9, in print(lijst_salades[input]) KeyError: 'truffelsalade\n'
Can someone explain what is did wrong?
If I use print(lijst_salades['Eiersalade']
it works fine.
Upvotes: 1
Views: 160
Reputation: 8298
The problem is that you read the \n
char with the input passed, as the error state:
KeyError: 'truffelsalade\n'
You should fix the code to:
import sys
lijst_salades = {'Eiersalade' : 5.99,
'Paprikasalade' : 6.05,
'truffelsalade': 3.99
}
input = (sys.stdin.readline()).rstrip()
print(lijst_salades[input])
Also, it is advised to add a testing to the input, because if the key doesn't exist it will also raise an error of type KeyError
.
Edit
You can read about escape characters int the following links:
https://linuxconfig.org/list-of-python-escape-sequence-characters-with-examples
https://docs.python.org/2.0/ref/strings.html
Upvotes: 2