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.
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
+ 2
Have you input correctly?
First line int, second line key?
I ran it and got some result...
+ 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.")
+ 1
Is it that simple? I'm now ashamed of myself. Thank you so much. Also, is my code neat enough to understand?
+ 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
+ 1
Thank you very much sir. Now I know deeply how dictionary works.
0
I tried that, sadly it didn't work..
0
I updated the code in the link. It results in KeyError.
I input like this:
1000
e