+6

# How to reduce if and elif?

If my code has lot of if and elif statements comparing lots of integers and strings then printing or performing any task so how can I reduce lots of if and elif? Thanks

4/16/2018 3:30:05 PM

+7

My solution: https://code.sololearn.com/cuirVM9afB6j/?ref=app

+6

If you have a function which should be executed on a number of conditions then you can combine them. Instead of if a = 5: do something elif a = 6: do something elif a = 7: do something else: do other you can write: if a in (5,6,7): do something else: do other or if a in range(5,8): do something else: do other

+6

@ Aditya Rawat You are welcome! :-)

+6

cyk Thanks a lot!

+5

Jan Markus Thanks for the idea!

+5

cyk , Jan Markus I have added new problem I don't want to ask another Question so here is the problem 👇 I wanted to add a 'random' operator to so that it can give one of the answer, Thanks! https://code.sololearn.com/cLYqdqNvQPBA/?ref=app

+5

nice solutions guys!

+4

cyk here is the eg👇 https://code.sololearn.com/cc8wFiBhL3LQ/?ref=app

+4

This is what I came up with. If you do random_num = list then random_num no longer takes random values in the range(0, 3). It is a list now... So just keep it the way it is and for a random_num generated get the corresponding element in the list... I tested it entering hey several times and it kept giving me something random from the list https://code.sololearn.com/cLA2pd6boLpe/?ref=app

+3

Well, maybe we can be able to suggest alternative ways of doing that if you posted part of the code

+3

https://code.sololearn.com/cZe3zWpEzaJ6/?ref=app

+3

Jan Hahahaha... This is hilarious!

+3

You can use the list within the If statement and random.choice to select one item. So the Code becomes shorter and more clear: https://code.sololearn.com/cS1Os6bOzdVA/?ref=app