DEV Community

still-purrfect
still-purrfect

Posted on

If Statements in Programming: Teaching Your Code to Decide

So far, we’ve learned how to store data, organize it, and even perform operations using operators.
But most real programs don’t just run top to bottom.
They make decisions.
That’s where if statements come in.
An if statement allows your program to run certain code only when a condition is true.
Think of it like a simple decision:
“If this is true, do this. Otherwise, do something else.”

🔹 Basic If Statement

age = 18

if age >= 18:
    print("You are allowed to vote")
Enter fullscreen mode Exit fullscreen mode

In this case, the program checks the condition age >= 18.
If it is true, it runs the message.
If not, it simply does nothing.

🔹 If...Else Statement

Sometimes we want two outcomes.

age = 16

if age >= 18:
    print("You are allowed to vote")
else:
    print("You are not allowed to vote")
Enter fullscreen mode Exit fullscreen mode

Now the program chooses between two paths.
One for true, one for false.

🔹 If...Elif...Else

When there are multiple conditions, we use elif.

marks = 75

if marks >= 80:
    print("Grade A")
elif marks >= 60:
    print("Grade B")
else:
    print("Grade C")
Enter fullscreen mode Exit fullscreen mode

The program checks conditions from top to bottom and stops once one is true.

💡 Why If Statements Matter

If statements are what make programs feel “intelligent.”
Without them, everything would run the same way every time.
With them, your program can:

  • React to input
  • Make decisions
  • Handle different situations This is the beginning of logic in programming.

🌱 Challenge

Write a program that:

  • Takes a number (your choice)
  • Checks if it is:
    • Greater than 0 → print "Positive"
    • Less than 0 → print "Negative"
    • Equal to 0 → print "Zero" Try to think step by step. That’s how programming becomes easier.

Next, we’ll look at loops, where your program stops doing things once and starts repeating actions efficiently.

Top comments (0)