What if Function – Python

Now is the time to put some programming logics in your python code. What if Function, this is used to do Boolean check What if? But first you need to learn about boolean.

  • and
  • or
  • not
  • != (not equal)
  • == (equal)
  • >= (greater-than-equal)
  • <= (less-than-equal)

If you have any idea about boolean then you will be understand what I mentioned above. If not, then lets understand it by below script.

people = 20
cats = 30
dogs = 15
if people < cats:
print ("Too many cats! The world is doomed!")
if people > cats:
print ("Not many cats! The world is saved!")
if people < dogs:
print ("The world is drooled on!")
if people > dogs:
print ("The world is dry!")
dogs += 5 # this is same as dogs = dogs + 5
if people >= dogs:
print ("People are greater than or equal to dogs.")
if people <= dogs:
print ("People are less than or equal to dogs.")
if people == dogs:
print ("People are same as Dogs")

If is a function which requires some script in its branch, so we need to provide “:” after if statement and 4 space in next line to put code in “if” branch. If you need more then 1 line of code in what if function you can add more line by providing 4 space.

  1. What do you think the if does to the code under it? An if-statement creates what is called a “branch” in the code. It’s kind of like those choose your own adventure books where you are asked to turn to one page if you make one choice, and another if you go a different direction. The if-statement tells your script, “If this boolean expression is True, then run the code under it, otherwise skip it.”
  2. Why does the code under the if need to be indented four spaces? A colon at the end of a line is how you tell Python you are going to create a new “block” of code, and then indenting four spaces tells Python what lines of code are in that block. This is exactly the same thing you did when you made functions.
  3. Make sure you really understand the concept of a “block” of code. Putting 4 space in front of line and making block is called block of code. It is also knows asĀ indented in python.

Run the script

Lets understand output
  • Our first if query result true output. So the script in that “what if function” executed.
  • Our 2nd if query result false so it didn’t executed that function.
Exercise of the day
  • Get some input form users and run “what-if” queries on it.
  • Try to put some code without indented if statement.


comment (1)

Leave me comment