+ 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??
6 odpowiedzi
+ 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"):
+ 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
+ 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?
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 :)
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)