- You probably already know uses of conditional statements from your everyday life, but this week we learned what they mean from a programming perspective.
- Conditional statements can be used to tell your code specific things to do. This allows for incredibly creative and complex programs. Instead of just being able to do math or write sentences, you can use conditional statements so that your computer can ‘Think!’. It can make decisions based on certain inputs or outputs, and decide what to do next based on these conditional statements.
- Well, your computer is not really the one thinking, you are!
- If statements are probably the most useful and common of conditional statements. They take in a condition, a boolean, and if that boolean is true and the condition is met, perform a specific function.
Remember that you need to use indents to separate your conditional statement from the rest of your code!
Else If Statements
The Else statement makes it much easier to write code where you have more than one condition. If Statements require a very specific condition to be met, but else statements are run if the If statement is false.
- A while statement is a different kind of conditional statement. Instead of telling your computer if it should run a certain line of code, you are telling your computer how long to run the code.
- This can be incredibly useful in programming because you can automize a lot of repeated tasks. For instance, say you want to add up the numbers 1-100. Instead of manually typing the numbers 1-100 into the computer, you could use a while loop.
When you are writing your code with conditional statements, it is very helpful to plan out the logic of your code. You can represent the different possible routes your code can take by making a flowchart through your if statements to make sure your code will always give the intended output.