Learn to Scode

3.Control Flow: Making Decisions

Learn how to make your programs respond to different conditions using if statements and loops.

25 minutes
Beginner
Article Content

Making Decisions with If Statements

Control flow allows your program to make decisions and execute different code based on conditions.

Basic If Statement

An if statement checks if a condition is true and executes code accordingly:

age = 18

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

Comparison Operators

You can compare values using these operators:

  • == Equal to
  • != Not equal to
  • > Greater than
  • < Less than
  • >= Greater than or equal to
  • <= Less than or equal to

Multiple Conditions

You can combine conditions using and and or:

age = 20
has_license = True

if age >= 18 and has_license:
    print("You can drive!")
else:
    print("You cannot drive.")

Loops: Repeating Actions

Loops allow you to repeat code multiple times:

For Loops

Use for loops when you know how many times to repeat:

# Count from 1 to 5
for i in range(1, 6):
    print(i)

# Loop through a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

While Loops

Use while loops when you want to repeat until a condition is met:

count = 0
while count < 5:
    print(count)
    count += 1

🎯 Practice Exercise

Write a program that counts from 1 to 10 and prints "even" for even numbers and "odd" for odd numbers.

Nested Control Flow

You can combine if statements and loops:

for i in range(1, 11):
    if i % 2 == 0:
        print(f"{i} is even")
    else:
        print(f"{i} is odd")