CodingNic

Control Flow and Logic

If Statements

Control Flow and Logic 18 min read

If Statements

If Statements

Sometimes a program should only do something when a condition is true.

For example:

  • If it is raining, take an umbrella.
  • If you are hungry, eat food.
  • If the password is correct, log in.

Python uses if statements to make decisions like this.

What Is an If Statement?

An if statement checks a condition.

If the condition is true, Python runs the code below it.

python
age = 18

if age >= 18:
    print("You are an adult")

Understanding the Example

Let’s break it down:

  • age = 18 stores a value
  • age >= 18 asks: is age greater than or equal to 18?
  • If the answer is True, the message is printed

The Colon :

The colon tells Python that a block of code is starting.

python
if age >= 18:

Always add a colon after the condition.

Indentation

The spaces before the next line are called indentation.

Indented code belongs to the if statement.

python
if age >= 18:
    print("Adult")

Without indentation, Python gives an error.

Another Example

python
score = 90

if score >= 50:
    print("You passed")

If the Condition Is False

If the condition is false, Python skips the indented code.

python
age = 15

if age >= 18:
    print("Adult")

Nothing is printed because the condition is false.

Code Along

python
temperature = 30

if temperature > 25:
    print("It is hot today")

Mini Challenge

Build an age checker.

  • Create a variable called age.

  • If the age is 18 or higher, print:

  • You are old enough to drive

Real World Use Case

Websites use if statements to check passwords, age limits, account status, and many other decisions.

Quiz

  1. What does an if statement do?
  2. What happens if the condition is true?
  3. Why is the colon important?
  4. What is indentation?

Assignment

Create a program that stores a test score. If the score is 50 or more, print "Pass".

Summary

You learned how if statements help Python make decisions, how conditions work, and why colons and indentation are important.