Levi Lee

May 29, 2026

Python 101: The Syntax You Actually Need Before Your First AI Project

Once the environment’s set up, this post covers the core of Python — no padding, just the parts you’ll actually use before building an AI project. Every example can be pasted straight into a .py file and run.

Variables and data types

A variable is a “container for data”. Python doesn’t need type declarations — it figures the type out for you.

name = "Alice"        # str   string
age = 20              # int   integer
gpa = 3.85            # float
is_student = True     # bool

print(name)           # Alice
print(type(age))      # <class 'int'>

# string formatting (f-string)
print(f"{name} is {age} years old")   # Alice is 20 years old

A few key points:

  • Dynamic typing: Python infers the type — no need to write int x = 10 like in Java.
  • = is assignment: it stores the value on the right into the variable name on the left.
  • # is a comment — for humans; Python ignores it.
  • f-strings (f"...{var}...") let you embed variables inside a string. Extremely handy.

Conditionals and loops

# conditionals: if / elif / else
score = 85
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
else:
    print("C")
# output: B

# for loop
for i in range(5):     # 0 to 4
    print(i)           # 0, 1, 2, 3, 4

# iterate over a list
for fruit in ["apple", "banana"]:
    print(fruit)       # apple, banana

# while loop
count = 0
while count < 3:       # keeps going while count < 3
    count += 1         # so it runs three times

Python uses indentation instead of braces, so bad indentation is a syntax error. Use 4 spaces (the VS Code default). Also, range(n) produces 0 to n-1, and range(2, 7) gives 2, 3, 4, 5, 6.

List and Dictionary

These are the two most-used data structures in the AI era: a List holds a bunch of similar things (e.g. a series of chat messages), and a Dict holds named fields (e.g. JSON returned from an API).

# List — ordered, mutable
nums = [10, 20, 30, 40]
print(nums[0])     # 10
print(nums[-1])    # 40 (the last one)
nums.append(50)    # add to the end
nums.pop()         # remove the last one
print(len(nums))   # length
print(nums[1:3])   # slicing → [20, 30]

# Dictionary — key-value pairs
student = {
    "name": "Alice",
    "age": 20,
    "major": "CS",
}
print(student["name"])     # Alice (look up a value by key)
student["gpa"] = 3.85      # add / update
for k, v in student.items():
    print(f"{k}: {v}")

Functions

A function is a “reusable block of code”. Writing functions = less repeated code = easier to debug and maintain.

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))   # Hello, Alice!

# parameters with default values (default exponent is 2)
def power(base, exp=2):
    return base ** exp

print(power(3))      # 9  (3^2)
print(power(3, 3))   # 27 (3^3)

# returning multiple values
def min_max(nums):
    return min(nums), max(nums)

lo, hi = min_max([3, 1, 4, 1, 5])
print(lo, hi)        # 1 5
  • def is the keyword that defines a function.
  • The names in parentheses are parameters — the inputs.
  • return hands the result back to the caller.
  • Call it with function_name(arguments).

Class — just get the gist for now

You don’t need to write these early on, but API responses are often wrapped in a Class, so it helps to recognize one:

class Dog:
    """blueprint for a dog (a class)"""
    def __init__(self, name, breed):   # runs automatically when an object is created
        self.name = name               # attribute
        self.breed = breed

    def bark(self):                    # method (the object's behavior)
        return f"{self.name} says Woof!"

my_dog = Dog("Mochi", "Shiba")         # create an object (instantiate)
print(my_dog.bark())                   # Mochi says Woof!

Core idea: a Class is a blueprint (a template for some kind of thing), and an Object is a concrete instance built from it. __init__ is the constructor, self means “this object itself”, self.xxx is an attribute, and def xxx(self) is a method.

How to read a Python program

When you get a piece of code, don’t read it top to bottom blindly — go in this order:

# 1. imports: the tools being used
import requests
from datetime import datetime

# 2. function definitions
def get_weather(city):
    """get a city's weather"""
    url = f"https://api.weather.com/{city}"
    response = requests.get(url)
    return response.json()

# 3. main entry point
if __name__ == "__main__":
    data = get_weather("Taipei")
    print(f"Temp: {data['temp']}°C")
  1. Look at the imports first — which packages? That hints at what it does.
  2. Read the function definitions — what does each def do? Check names and docstrings.
  3. Find the entry pointif __name__ == "__main__" is where it starts; if there isn’t one, read top to bottom.
  4. Follow the data — where variables come from and where they go.

If you’re short on time, learn these first

  • Variables & types: str / int / float / bool — the basic units of data.
  • if / for / while: the core of program logic.
  • List & Dict: essential for handling JSON from APIs.
  • Functions (def): wrap up repeated logic.
  • uv add: install third-party packages to use tools others have built.
  • Bonus: f-strings & print (debugging’s best friend) and try / except (so one bug doesn’t crash the whole program).

Master these and you can start building AI projects.

Hands-on practice

# Exercise 1: Hello World (save as hello.py, then `python hello.py`)
name = input("What's your name? ")
print(f"Hello, {name}!")
# Exercise 2: FizzBuzz
for i in range(1, 16):
    if i % 15 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

Stretch goal: uv add google-genai to install the SDK, then — in the spirit of “Vibe Coding” — just tell the AI what you want and have it write you a simple Gemini-API chatbot (remember to tell it to protect your API Key).

Resources to go deeper

  • Prof. Lu Hsin-min’s quick tutorials — a concise version from an Information Management professor; grasp the core fast: video 1, video 2.
  • Papaya’s detailed Python series — shallow-to-deep, good for systematic learning.
  • “Learn Python in 4 hours (even my grandma can)” — zero-basis intro, gentle pace: video.
  • Coursera’s programming-for-business course — pick this if you want a certificate too: course.

Not sure which to watch? Start with Prof. Lu’s quick tutorial.

Syntax is just a tool — what matters is doing. Run every example above and you’re ready to start your first AI project.


This series was built with datafox.tw for NTU AI Club.

Writing