Skip to content
← Back to Community
How to reduce if's and elif's in python
Profile icon
LChan24

So I've seem lots of optimized code which can lead to slower programs yandre dev, but to optimize code you should use dictionaries x = 42 y = ["list] dictionary = { 1:"string", 2: 14 #interger 3: x 4: y}
This can be used with inputs eg

x = int(input("Enter an interger) y = { 1:"Some" 2:"Body" 3:"once" } print(y[x])
This can also be done with strings eg
y = {
"hello" : "world"
}
print(y["hello"]}

Hope you enjoyed optimizing and reducing cpu usage :)

Voters
Profile icon
LChan24
Comments
hotnewtop
Profile icon
HankFried

Solution2Pass offers you an interactive Splunk Core Certified Power User Exam study material that maintains your interest in studies by offering you and easy and expressive study content. You don’t feel bored when learning the Splunk SPLK-1002 exam questions and answers included in our study guide. To further deepen your learning, Splunk Core Certified Power User exam questions dumps has been explained with the help of examples, simulations and graphs. Only a little effort can benefit you a lot and enable you to pass SPLK-1002 exam in very first exam attempt.

Profile icon
CodeLongAndPros

1: Vars do not use the cpu, they use RAM
2: Python is already called 'slow', so...

Profile icon
Highwayman

Is there really a point to optimizing python code? It seems a bit strange to reduce readability for the sake of speed in a language such as python. Isn’t python all about ease of development and readability and all that? Just seems strange to me I guess...

Profile icon
LChan24

@Highwayman Yeah you've got a point, but with 10+ elifs/if's it does take up more lines than it has to. So using dictionaries reduces file size and processing power

Profile icon
Highwayman

@LChan24 true. Hum. I wish python had macros. It’d be so easy to make a switch statement type macro 😝