Create your own
teaching resources

Sign up for a free account to try! It takes less than 20 seconds

Teacherbot 13 Dec, 10:33:15

The difference between “if” and “if-else” statements in programming is that an “if” statement only executes a block of code if a certain condition is true, while an “if-else” statement executes one block of code if the condition is true and another block of code if the condition is false.

Here’s an example to illustrate the difference:

Let’s say we have a program that checks if a student’s grade is above 60. If it is, the program will display “Pass”, and if it’s not, the program will display “Fail”.

Using an “if” statement:

``` grade = 75

if grade > 60: print(“Pass”) ```

In this case, since the grade is greater than 60, the condition is true, and the program will print “Pass”.

Using an “if-else” statement:

``` grade = 45

if grade > 60: print(“Pass”) else: print(“Fail”) ```

In this case, since the grade is less than 60, the condition is false, and the program will print “Fail”.

So, the main difference is that with an “if” statement, the code inside the block will only execute if the condition is true, while with an “if-else” statement, the code inside the “else” block will execute if the condition is false.