Let's first learn how it works!
Let's say there are two snacks I want to buy at a store. They both cost $3 but I don't know how much money I have in my pocket yet. I need to check how much money I have before I can decide what to buy. Here is where the logic of an "if statement" comes in:
If I have $6 or more then I can buy both the snacks, if I have more than $3 but less than $6 I can only buy one snack, else if I have less than $3 I can't by any snacks.
Let's take a look at how we can right the above "if statement" in python!
Time to break down the above example!
We start with a variable "Money_in_pocket" and set it equal to 5, this is used to represent how much money we have.
We then write our first "if statement";
- if Money_in_pocket >= 6:
This is the way to write an in statement in python. Start with the key word "if" followed by a "condition" that will be either true or false. The ">=" means greater than or equal to. In English what are statement is saying is "if Money_in_pocket is greater than or equal to 6". Notice that we end it with a ":", it is important to remember that statements like this always have to end with ":" or you will get an error.
Now the line under our first if statement reads;
- print("I can buy both snacks!")
This is what would show if our if statement comes out to be true, but since Money_in_pocket is not greater than or equal to 6 because we set it to 5, we could not buy both snacks.
The next line is also a part of the "if statement" tool:
- elif Money_in_pocket >= 3 and Money_in_pocket < 6:
The key word "elif" is short for else if, simply another if statement. The difference is that elif always comes after an initial if statement.
There is another key word here "and". When we use "and" it means that we have two or more conditions that must be true for the statement below to happen.
Lastly, we have the key word "else", this key word comes after an "if" or "elif" statement. It is meant to catch anything that does not meet the previous statements. It makes it easier for us as programmers because we don't have to write all possibilities and we can focus on the ones that matter.
No comments:
Post a Comment