In previous chapter I explained how you can make choice with help of what-if. Make sure you really understand the concept of a “block” of code. This is important for when you do the next exercise where you write all the parts of if-statements that you can use. “What-If” statement check the query and if it is try it run the bock, otherwise skip it. But what if you want to run some other code instead of skipping. e.g if a > b print yes, otherwise print no. In this case scenario we use inbuilt function of Python If – Else. We will use same script we used in our previous chapter but this time with “if-else”.
people = 20 cats = 30 dogs = 15 if people < cats: print ("Too many cats! The world is doomed!") else: print ("Not many cats! The world is saved!") if people < dogs: print ("The world is drooled on!") else: print ("The world is dry!")
I suggest you to check previous script (of last chapter) where we did it with help of 4 if statements. and we we did it with only 2 Python if-else statements. Remember every else statement required if function.
Run the Script
Now run the script and check the output.
Its same as we get in our previous chapter.
But wait, What if I need more then 2 conditions?
Check remaining half of the script we will convert that script to if-else.
people = 20 cats = 30 dogs = 15 dogs += 5 if people > dogs: print ("People are greater than or equal to dogs.") else: if people < dogs: print ("People are less than or equal to dogs.") else: print ("People are dogs.")
What was that?
This is called nested if-else statement. Its using if-else statement inside a if-else statement.
But using only if statement is easy!!
When you have code of 10-20 lines it is easy, but when you have huge code and you want that code to run really fast you need to avoid unwanted queries. When you use only if statement you ask your program to check every if statement, but with if-else your program only check one condition. Some time our if queries are complex (we will see those later) so we don’t want to execute multiple of those complex queries and make script slow.
Note:- Next 2 chapters are exercise only so I suggest you to check those chapters also. We are using if-else statement in those exercise.
Exercise of the Day:
Make a simple calculator. Which take input from user and print result. e.g
hint: you may need help of chapter 3, to check that click here.