Introduction to if Statements

Everything you have seen so far has consisted of sequential execution, in which statements are always performed one after the next, in exactly the order specified. That is where control structures come in. A control structure directs the order of execution of the statements in a program. In the real world, we commonly must evaluate information around us and then choose one course of action or another based on what we observe:

If the weather is nice, then I’ll mow the lawn. (It’s implied that if the weather isn’t nice,
then I won’t mow the lawn.)

In a Python program, the if statement is how you perform this sort of decision-making. It allows for conditional execution of a statement or group of statements based on the value of an expression.

 Syntax: if < expr >:
                < statement >

                

We need to understand about decision-making in the computer language. As we all know, Humans make decisions all the time. For instance, if something is True , then do this.

  • If it is raining, then bring and Umbrella.
  • If the Homework is due tonight, then finish the homework.
  • **** Computers also make decisons,
    If something is True,
    then do this.

  • if password is correct, then allow user to login.
  • if it is 8 am, then start morning alarm.
  • if internet is connected, then save user progress.

So How do computer make decisions?

Computers make decisions the same way they do everything by following algorithms. Suppose we have the following code to visualize. Below we have two algorithms that do almost the exact same thing:

conditions
conditions

So, What if our algorithm could decide whether or not to calculate an overtime wage?

conditions

Below we have more examples to analyze, How conditionals work. Conditions work as we give instructions accordingly.

conditions
conditions

Now that we know how to use if statements.... Let's try something slightly more complex.

conditions

We can look at the slides below, How computer performs exactly following the instructions as given.

1/11
Caption Text
2/11
Caption Text
3/11
Caption Text
4/11
Caption Text
5/11
Caption Text
6/11
Caption Text
7/11
Caption Text
8/11
Caption Text
9/11
Caption Text
10/11
Caption Text
11/11
Caption Text