1
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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

i just started learning python. why does it read the \n? and what is it for? thank you for replying.
@Dakkie15 the \n is the newline character, when you press the Enter in the console/cmd/terminal it is added to the string automatically
@Dakkie15 see the link I added to the question about escape characters

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.