Reputation: 3
I'm a beginner with Python. Currently I'm making a car reading tool just to build some programming skill. All works well.
When I get a fault code from a control module from a car, I get a P-code. Like:
P2348 and P21E2 (random P codes)
I can retrieve these P codes, but I want to add a little more info to them. P codes can be linked to a fault description:
P2348 - Misfire detected (random)
I want my program to give the extended information, and not just the P code. There are thousands of P codes and I have them all with discription. But a thousand If statements would be bad coding. I could look the P code up in a textfile and get the complete string from it, but that's not really an option (unless it's possible in the code itself or compiled with the executable).
What would be a neat way to do this? I have encountered this problem before when I took programming lessons. I used IF statements then (about 20) and I hated it.
Upvotes: 0
Views: 157
Reputation: 222862
Use a dictionary:
code_descr = {
'P2348': 'Misfire detected',
'P8866': 'Engine is on fire',
'P7777': 'Tires missing',
}
then you can lookup a key in the dict, no if
needed:
print('{} - {}'.format(code, code_descr[code]))
You can write code to read a database in some format (csv, json, etc) and generate the dict, so you have the descriptions external to the program
Upvotes: 2