Lesson 1

First Decision with If and Else Statements

Navigating Your First Decision with If and Else Statements

Welcome! In this lesson, we're diving into one of the most fundamental concepts in programming: making decisions using if and else statements in PHP. Think of conditionals as your program's way of making choices based on given criteria — much like how you decide whether to bring an umbrella based on the weather forecast.

What You'll Learn

In this lesson, you'll learn how to use if and else statements to control the flow of your PHP programs. Specifically, you'll:

  • Understand how to write basic if statements to execute code only when certain conditions are met.
  • Learn to use else statements to handle the cases when those conditions are not met.
  • See how to use comparison operators to set these conditions effectively.

Here's a quick preview of the kind of code you'll be able to write by the end of this lesson:

php
1<?php 2$fuelLevel = 75; // percentage 3 4// Check if fuel level is greater than 50 5if ($fuelLevel > 50) { 6 echo "Fuel level is sufficient for launch.\n"; 7} else { 8 echo "Fuel level is too low for launch.\n"; 9} 10?>
Basic Comparison Operators

To make effective decisions with if and else statements, you'll need to understand comparison operators. These operators help you compare values and make decisions based on those comparisons. Here are four key comparison operators you'll use frequently:

  • > (Greater than): Checks if the value on the left is greater than the value on the right.
  • < (Less than): Checks if the value on the left is less than the value on the right.
  • >= (Greater than or equal to): Checks if the value on the left is greater than or equal to the value on the right.
  • <= (Less than or equal to): Checks if the value on the left is less than or equal to the value on the right.

Understanding these operators is crucial for setting the conditions that drive your program's decision-making processes.

Why It Matters

Conditionals are essential for making your programs dynamic and responsive. Without them, you could only write static, linear code that can't adapt to different situations. By mastering if and else statements, you set the stage for more complex decision-making in your programs. These are powerful tools that will allow you to build more interactive and intelligent applications, whether you're checking user input, managing game logic, or controlling any other flow of your program.

Excited to get started? Let's dive into the practice section and start experimenting with these powerful tools!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.