Anybody Can AI

Quick Stats

Completed

0

Time Spent

0m

Streak

0

User

User

Python for AI: A Gentle Start

Python Basics/Control Flow and Functions

Control Flow and Functions

Make decisions and reuse logic.

Making decisions

Programs need to choose and repeat. Conditionals choose:

for n in [1, 2, 3]:
    if n % 2 == 0:
        print(n, "is even")
    else:
        print(n, "is odd")

if runs a block when a condition is True; else covers the rest; elif adds more branches. The condition is any expression that evaluates to a bool — score > 90, name == "Ada", is_active.

Repeating with loops

The for loop above walks through each item in a collection — the single most common pattern in data work ("for each row, do something"). When you don't know how many times in advance, while repeats until a condition flips. Indentation isn't decoration in Python — it defines what's inside the loop or `if`. Four spaces, consistently.

Functions: reuse and clarity

A function packages reusable logic behind a name:

def greet(name, excited=False):
    msg = f"Hello, {name}"
    return msg + "!" if excited else msg
  • def names the function; the values in parentheses are its parameters.
  • excited=False is a default — callers can omit it.
  • return hands a value back: greet("Ada", excited=True) gives "Hello, Ada!".

Functions keep code readable, testable, and DRY — don't repeat yourself. The moment you copy-paste a block twice, turn it into a function and fix bugs in one place instead of three.

Conditionals choose, loops repeat, functions reuse. Almost every program — and every AI pipeline — is just these three moves arranged over your data.

Try this: Write a function is_long(text, limit=100) that returns True when a string is longer than limit, then loop over a list of sentences and print only the long ones. You've just combined all three ideas — exactly the shape of real data-filtering code.