Introducing if statements
If Statements
if some_test: # Notice the colon at the some_test
do_something #Notice the 4 spaces before the do_something code
Sometimes in our programs we will want to do a certain thing only if a a certain thing happens. In this case we will usually want to use an if statement.
Testing equivalence
Example 1 – Testing equivalence
Quite often in our programs we will want to test if something equals something else. In order to this in python we use the == (double equals) sign.
Indented vs non-indented code.
The program executes(runs) the if statement, and then if the result of the if statement is true, it executes the indented code (Indented means you put 4 spaces before the code).
Here is another example. Can you see difference between the indented and non-indented code?
Testing greater / less than
Example 2 – Testing greater / less than
Another common use of an if statement is to test is a value is greater or less than an amount. For this, just like in maths, we use the > (greater than) or < (less than signs.
Comparison Operators we can use
Testing membership
Testing Membership
We can also use if statements to test see if inputs or variables are members of lists.
Multiple tests
Multiple Tests
Sometimes we want to do more than one test. We can do this using the OR statement
Try it out
We can also test multiple variables at the same time using either an OR statement or an AND statement.
Multiple tests with multiple variables
username = input("Please enter your username:") password = input("Please enter your password:") if username == "aladin" and password == "abracadabra": print("You can enter the cave of many shiny treasures")
If…Else… Statements
Although if statements are quite useful just on their own, we often want to force the program down two exclusive paths. In other words the program must execute(run) one of the two branches. For the we use a combination of if…else..
Challenge 13 - Advice Please
Challenge 14 - Darts
Challenge 15 - Charity Collection
Challenge 16 - Area of a Rectangle
Challenge 17 - Advice Please(Part 2)
Challenge 18 - Tyre and Brake Wear
Challenge 19 - Solid, Liquid, Gas
Challenge 20 - Charity Collection ( Part 2)
Attribution : Please note these challenges were created by: G. Reid – Buckhaven High School