Conditional statements are part of every programming language. With conditional statements, we can have code that sometimes runs and at other times does not run, depending on the conditions of the program at that time.
When we fully execute each statement of a program, moving from the top to the bottom with each line executed in order, we are not asking the program to evaluate specific conditions. By using conditional statements, programs can determine whether certain conditions are being met and then be told what to do next.
Let’s look at some examples where we would use conditional statements:
The if statement will evaluate whether a statement is true or false, and run code only in the case that the statement is true.
grade = 70 if grade >= 65: print("Passing grade")
With this code, we have the variable grade and are giving it the integer value of 70. We are then using the if statement to evaluate whether or not the variable grade is greater than or equal ( >= ) to 65. If it does meet this condition, we are telling the program to print out the string Passing grade.
In this case, the grade of 70 does meet the condition of being greater than or equal to 65, so you will receive the following output once you run the program:
Let’s now change the result of this program by changing the value of the grade variable to 60:
grade = 60 if grade >= 65: print("Passing grade")
When we run this code, we will receive no output because the condition was not met and we did not tell the program to execute another statement.
To give one more example, let us calculate whether a bank account balance is below 0.
balance = -5 if balance < 0: print("Balance is below 0, add funds now or you will be charged a penalty.")
When we run the program, we’ll receive the following output:
Balance is below 0, add funds now or you will be charged a penalty.
In the program we initialised the variable balance with the value of -5, which is less than 0. Since the balance met the condition of the if statement (balance < 0), once we save and run the code, we will receive the string output. Again, if we change the balance to 0 or a positive number, we will receive no output.
Write a program that checks if a person is over 18.
Write a program that asks if their favourite colour matches yours.
Write a program that checks if a persons name is more than 5 characters.
Thanks [name] from [whichclass][location], Mr McG will get your message…"
[message]"…and will get back to you ASAP via [email]. Catch you soon.
Have a great day!!
K McGuinness - 2018
No personal data will be shared with any third party. The only data processed via this website is anonymous browsing data to best manage your user experience.