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.
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?
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
We can also use if statements to test see if inputs or variables are members of lists.
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")
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..
Attribution : Please note these challenges were created by: G. Reid – Buckhaven High School