I always use if-elif-else conditions everytime I code. Can someone suggest me how can I step out from this and code creatively?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I always use if-elif-else conditions everytime I code. Can someone suggest me how can I step out from this and code creatively??

23rd May 2020, 7:56 AM
ROHIT PRADHAN
ROHIT PRADHAN - avatar
6 Answers
+ 4
ROHIT PRADHAN, from my point of view the challenge you have are not the if conditions, but the way you check the status of the various inputs. if comp_input =="rock" and user_input in("rock","Rock","ROCK") or comp_input =="paper"and user_inputin("paper","Paper","PAPER") or comp_input =="scissor" and user_input in("scissor","Scissor","SCISSOR"):
23rd May 2020, 9:26 AM
Lothar
Lothar - avatar
+ 4
Here is a working concept of how it could be done. Still not complete, but working and flexible at all. https://code.sololearn.com/cGWPhqE1KZNN/?ref=app
23rd May 2020, 1:01 PM
Lothar
Lothar - avatar
+ 2
Why do you think using if-elif-if blocks is uncreative? Can you give an example for a code you would like to improve?
23rd May 2020, 8:17 AM
Lisa
Lisa - avatar
23rd May 2020, 8:23 AM
ROHIT PRADHAN
ROHIT PRADHAN - avatar
0
You can optimize your code by generalization. Instead of explicitly writing down every possible condition, try finding a general rule. Also, learn more on collection types. They might be useful for iteration of different conditions/scenarios with loops, saving you a great deal of code space. But hey, in the end - if your code works, you're already half way through :)
23rd May 2020, 9:23 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
if elif else is pretty good, unless your logic explicitly can be optimized, there is multiple scenarios where you can do so for example: You are testing x where type(x) is str, and you will execute some code depending on the value You can use dict instead, where the key is the expected values of x, and the values are the functions like func = scenarios.get(x) if func is not None: func(a,b,c)
23rd May 2020, 9:35 AM
NourEddine Yassine