Regarding wrong input key in a dictionary | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Regarding wrong input key in a dictionary

https://code.sololearn.com/cU0P3ODD7bne/?ref=app here is my code that lets you input a number and a "key". The thing is, when I am not knowledgeable yet on how to code a scenario wherein a user inputs a wrong "key". I want to it to let a user input a key again or at least state that the key they input is wrong. As a beginner, I am taking points on any advises you guys will give to me. I know my code it a bit mess, you can also point out the things to improve for me to make a cleaner code. Thank you everyone.

10th May 2020, 11:34 AM
Xander Christians
Xander Christians - avatar
8 Answers
+ 3
You can use an if-condition for that. if tax_sales_prov not in keyword: # whatever you want # to do in that case
10th May 2020, 11:41 AM
HonFu
HonFu - avatar
+ 2
Have you input correctly? First line int, second line key? I ran it and got some result...
10th May 2020, 11:54 AM
HonFu
HonFu - avatar
+ 2
That's because you try to access the dict even when the key is wrong. First of all, I'd put the function definition at the top of the code. And then structure your code like this: if tax_sales_prov in keyword: rate=keyword[tax_sales_prov] print(f'\n\nYour net sales is {total(gross_s,rate)} CAD.') else: print("You input a wrong keyword.")
10th May 2020, 12:06 PM
HonFu
HonFu - avatar
+ 1
Is it that simple? I'm now ashamed of myself. Thank you so much. Also, is my code neat enough to understand?
10th May 2020, 11:44 AM
Xander Christians
Xander Christians - avatar
+ 1
Btw, there are ways to cut up long strings in your code. For example instead of... print('Hello World') ... you can write: print( 'Hello ' 'World' ) Like that, you can reduce the length of each line to something you deem reasonable and readable. Works with every set of brackets, so you could also tidy up your dict. Instead of... d = {endlessly going on...} ... you can write: d = { 1: 'one', 2: 'two', 3: 'three' } ... or any other order you like. More details: https://code.sololearn.com/c9a0cG9dpVUr/?ref=app
10th May 2020, 12:13 PM
HonFu
HonFu - avatar
+ 1
Thank you very much sir. Now I know deeply how dictionary works.
10th May 2020, 12:16 PM
Xander Christians
Xander Christians - avatar
0
I tried that, sadly it didn't work..
10th May 2020, 11:50 AM
Xander Christians
Xander Christians - avatar
0
I updated the code in the link. It results in KeyError. I input like this: 1000 e
10th May 2020, 12:01 PM
Xander Christians
Xander Christians - avatar