Python Syntax

A detailed, student-friendly Python syntax guide with runnable examples and focused mini challenges. Keep this page open while coding in the sandbox.

This workbook now covers deeper fundamentals: variable types and conversions, multiple loop patterns, conditionals, functions, and core data structures.

Each section also includes a quick syntax-variation reference so students can compare forms like `for item in items` vs `for i in range(...)` at a glance.

FoundationsBeginner

Syntax and Indentation Rules

Open linked lesson

Python uses indentation to define blocks. Missing colons or inconsistent spaces cause immediate errors.

In [1]Code cellpyodide

Mini challenge: Write an if block that prints two indented lines, then one final line outside the block.

FoundationsBeginner

Printing Output

Open linked lesson

print() helps you inspect values and explain what your program is doing.

In [2]Code cellpyodide

Mini challenge: Print your name, grade level, and a sentence using an f-string with two values.

FoundationsBeginner

Comments and Readable Layout

Open linked lesson

Readable code is easier to debug and maintain. Comments explain why code exists, not obvious steps.

In [3]Code cellpyodide

Mini challenge: Write a short 3-5 line program with one helpful comment and clear variable names.

Variables and TypesBeginner

Variable Naming and Reassignment

Open linked lesson

Good names make code self-explanatory. Reassignment lets a value change as your program runs.

Common syntax variations

  • name = 'Ava'
  • score = 72
  • score = score + 1
  • score += 1
In [4]Code cellpyodide

Mini challenge: Create variables for your name and age, print them, then reassign age to age + 1 and print again.

Variables and TypesBeginner

Core Types: int, float, str, bool, None

Open linked lesson

Every value has a type. Understanding types helps prevent bugs and makes conversions predictable.

Common syntax variations

  • age = 12 # int
  • height = 5.1 # float
  • name = 'Mina' # str
  • is_active = True # bool
  • middle_name = None # NoneType
In [5]Code cellpyodide

Mini challenge: Create one variable of each type (int, float, str, bool, None) and print each variable with its type.

Variables and TypesBeginner+

Mutable vs Immutable (Beginner View)

Open linked lesson

Some values can be changed in place (like lists), while others create a new value (like strings).

In [6]Code cellpyodide

Mini challenge: Create a string and a list, modify both, and explain in a comment which one changed in place.

Variables and TypesBeginner+

Type Conversion and Safe Input

Open linked lesson

input() returns text. Converting values correctly is required for math and comparisons.

Common syntax variations

  • raw = input('Enter a number: ')
  • number = int(raw)
  • decimal = float(raw)
  • text = str(number)
In [7]Code cellpyodide

Mini challenge: Read a number with input(), convert it to int, and print that number multiplied by 3.

Variables and TypesBeginner

input() lets your program react to user choices.

In [8]Code cellpyodide

Mini challenge: Ask for a user's name and favorite number, then print number + 10 and number * 2.

Operators and LogicBeginner

Arithmetic Operators

Open linked lesson

Arithmetic operators power totals, counters, and formulas.

In [9]Code cellpyodide

Mini challenge: Choose two numbers and print their sum, product, remainder, and exponent result.

Operators and LogicBeginner

Comparison and Logical Operators

Open linked lesson

Comparisons and logic are the basis of decision-making.

In [10]Code cellpyodide

Mini challenge: Create two boolean conditions and print results using and, or, and not.

Operators and LogicBeginner+

Membership and Identity

Open linked lesson

Use membership to check if a value appears in data and identity to compare object identity.

In [11]Code cellpyodide

Mini challenge: Create two lists with the same values and compare them using == and is. Print both results.

Operators and LogicBeginner

Augmented Assignment

Open linked lesson

Operators like += and -= make update logic cleaner and less error-prone.

In [12]Code cellpyodide

Mini challenge: Start with a variable set to 20, then use +=, *=, and -= once each. Print after every step.

ConditionalsBeginner

Conditionals (if / elif / else)

Open linked lesson

Conditionals let your code make choices.

In [13]Code cellpyodide

Mini challenge: Create a program that prints beginner/intermediate/advanced based on a numeric level.

ConditionalsBeginner+

Nested Conditionals

Open linked lesson

Nested conditionals let you make decisions in stages.

In [14]Code cellpyodide

Mini challenge: Write a nested conditional for a game: check level first, then check if player has a key.

ConditionalsBeginner+

Short Conditional Expression (Ternary)

Open linked lesson

A ternary expression is a compact way to choose one of two values.

In [15]Code cellpyodide

Mini challenge: Use a ternary expression to print pass/fail based on whether score is at least 70.

LoopsBeginner

For Loops with range() Patterns

Open linked lesson

range() gives controlled sequences for counted repetition.

Common syntax variations

  • for i in range(stop):
  • for i in range(start, stop):
  • for i in range(start, stop, step):
  • for i in range(10, 0, -1):
In [16]Code cellpyodide

Mini challenge: Use range() to print even numbers from 2 to 20.

LoopsBeginner+

For Loops over Strings, Lists, and Dicts

Open linked lesson

for loops work with many iterable types, not just range().

Common syntax variations

  • for ch in 'python':
  • for item in ['a', 'b', 'c']:
  • for key in my_dict:
  • for key, value in my_dict.items():
In [17]Code cellpyodide

Mini challenge: Create a dictionary for a book (title, pages, author) and loop through its items.

LoopsBeginner

While Loops and Counters

Open linked lesson

while loops repeat while a condition stays true.

Common syntax variations

  • while condition:
  • while count > 0:
  • while True:
  • if should_stop: break
In [18]Code cellpyodide

Mini challenge: Write a while loop that prints numbers from 1 to 8 and also prints their double.

LoopsBeginner+

break, continue, and pass

Open linked lesson

These control statements let you skip work, stop loops early, or mark unfinished code.

In [19]Code cellpyodide

Mini challenge: Loop from 1 to 12, skip multiples of 3, and stop completely once you reach 10.

LoopsBeginner+

Nested Loops

Open linked lesson

Nested loops handle grid-like and pairwise problems.

In [20]Code cellpyodide

Mini challenge: Use nested loops to print a 5x5 multiplication table (or as much as you can).

LoopsBeginner+

Loop else (Intro)

Open linked lesson

A loop's else runs only when the loop finishes normally (not when break is used).

In [21]Code cellpyodide

Mini challenge: Search for a value in a list using for + else and print either found or not found.

FunctionsBeginner

Functions: Parameters and Return Values

Open linked lesson

Functions make code reusable and easier to test.

In [22]Code cellpyodide

Mini challenge: Write a function `triple(n)` that returns n * 3, then call it with at least two values.

FunctionsBeginner+

Function Scope Basics

Open linked lesson

Variables created inside a function stay local unless explicitly returned.

In [23]Code cellpyodide

Mini challenge: Create a function that uses a local variable and returns it. Print the returned value outside.

Data StructuresBeginner

Lists store ordered, changeable collections of values.

In [24]Code cellpyodide

Mini challenge: Create a list of 5 foods, replace one item, append one item, then loop and print all items.

Data StructuresBeginner

Strings are text values you can slice, format, and inspect.

In [25]Code cellpyodide

Mini challenge: Store a sentence and print: first character, last character, and the sentence in uppercase.

Data StructuresBeginner+

Dictionaries and Tuples

Open linked lesson

Dictionaries map keys to values, and tuples store fixed groups of values.

In [26]Code cellpyodide

Mini challenge: Make a dictionary with name and favorite_color, then add age and print all key/value pairs.

FoundationsBeginner

Imports and Module Usage

Open linked lesson

Imports let you use code from Python and third-party libraries instead of rewriting everything.

Common syntax variations

  • import random
  • import math as m
  • from math import sqrt
  • import pygame, random
In [27]Code cellpyodide

Mini challenge: Import random and print one random number from 1 to 10. Then import sqrt and print sqrt(81).

Operators and LogicBeginner+

Truthiness and Short-Circuit Logic

Open linked lesson

Python treats many values as true/false, and and/or stop early. This affects real program behavior.

Common syntax variations

  • if value:
  • if not value:
  • result = user_name or 'Guest'
  • is_ready = has_account and has_permission
In [28]Code cellpyodide

Mini challenge: Create three variables (one empty, one non-empty, one number) and print their bool() values. Then use or for a fallback label.

LoopsBeginner+

List Comprehensions (Map and Filter)

Open linked lesson

List comprehensions are a compact way to build transformed or filtered lists used often in game code.

Common syntax variations

  • squares = [n * n for n in nums]
  • evens = [n for n in nums if n % 2 == 0]
In [29]Code cellpyodide

Mini challenge: From numbers 1-12, build a list of multiples of 3 and another list with each number doubled.

LoopsBeginner+

any(), all(), and Generator Checks

Open linked lesson

any() and all() are clean ways to answer yes/no questions across a collection.

Common syntax variations

  • any(score >= 90 for score in scores)
  • all(ch.isalpha() for ch in text)
In [30]Code cellpyodide

Mini challenge: Create a list of temperatures and print whether any are below 32 and whether all are below 100.

Operators and LogicBeginner+

min() / max() and Clamping Values

Open linked lesson

Clamping keeps values inside boundaries, which is essential for positions, health bars, and counters.

Common syntax variations

  • smallest = min(values)
  • largest = max(values)
  • x = max(0, min(limit, x))
In [31]Code cellpyodide

Mini challenge: Clamp a score variable so it stays between 0 and 100, then print before and after.

LoopsBeginner+

enumerate() for Indexed Loops

Open linked lesson

enumerate() gives index + value together, which is perfect for menus, grids, and ordered displays.

Common syntax variations

  • for index, item in enumerate(items):
  • for index, item in enumerate(items, start=1):
In [32]Code cellpyodide

Mini challenge: Create a list of 4 tasks and print them as a numbered list starting at 1.

Data StructuresBeginner+

Tuple Unpacking and Multiple Assignment

Open linked lesson

Unpacking makes code cleaner when values naturally travel in pairs or grouped returns.

Common syntax variations

  • x, y = (10, 20)
  • name, score = 'Ava', 95
  • a, b = b, a
In [33]Code cellpyodide

Mini challenge: Store three coordinate pairs in a list and loop with unpacking to print each x and y.

Data StructuresBeginner+

Dictionary .get() and Safe Defaults

Open linked lesson

Using .get() avoids crashes from missing keys and keeps programs resilient to incomplete data.

Common syntax variations

  • value = data.get('key')
  • count = data.get('count', 0)
In [34]Code cellpyodide

Mini challenge: Create a dictionary for a user profile and print a missing field with a default value using .get().

FunctionsBeginner+

Classes and Objects (Beginner Intro)

Open linked lesson

Classes bundle related data and behavior, and help you read APIs like pygame.Rect with confidence.

Common syntax variations

  • class Pet:
  • def __init__(self, name):
  • self.name = name
  • pet = Pet('Luna')
In [35]Code cellpyodide

Mini challenge: Create a class with two attributes and one method, then create one object and call the method.

FoundationsBeginner

Turtle Basics (Drawing with Python)

Open linked lesson

Turtle gives immediate visual feedback and makes loops, angles, and functions feel concrete.

Common syntax variations

  • import turtle
  • pen.forward(80)
  • pen.left(90)
  • pen.penup() / pen.pendown()
  • turtle.done()
In [36]Code cellpyodide

Mini challenge: Use turtle to draw a triangle and a square in different colors. Use at least one loop.

Data StructuresBeginner+

Sets (Unique Values)

Open linked lesson

Sets automatically remove duplicates and support fast membership checks.

In [37]Code cellpyodide

Mini challenge: Create a set from a list with duplicate names and print the cleaned set and its length.

DebuggingBeginner

Debugging Habits and Common Errors

Open linked lesson

Fast debugging comes from reading error messages and checking assumptions one line at a time.

In [38]Code cellpyodide

Mini challenge: Intentionally cause one NameError or TypeError, then fix it and write a one-line note about the fix.

Turtle Basics

Turtle is a great first graphics toolkit for beginners. You write regular Python code, and the turtle draws the result on screen so loops and angles become visual.

1) Draw a line

import turtle

pen = turtle.Turtle()
pen.forward(120)
turtle.done()

2) Draw a square with a loop

import turtle

pen = turtle.Turtle()
for _ in range(4):
    pen.forward(90)
    pen.left(90)
turtle.done()

3) Change color, width, and speed

import turtle

pen = turtle.Turtle()
pen.color("tomato")
pen.width(4)
pen.speed(7)
pen.circle(60)
turtle.done()

4) Lift and move without drawing

import turtle

pen = turtle.Turtle()
pen.forward(80)
pen.penup()
pen.goto(140, 40)
pen.pendown()
pen.circle(30)
turtle.done()

Pygame Starter Guide

Use this section as a practical roadmap for building your first game loop. The patterns below are chosen to match what you can run in the app's game sandbox today (especially in pygbag mode). The syntax page is for reference, while gameplay execution happens in the sandbox.

1) Standard game setup

Every pygame game starts with initialization, a window, a clock, and a running loop.

import pygame

pygame.init()
WIDTH, HEIGHT = 800, 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My First Game")
clock = pygame.time.Clock()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((20, 20, 30))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

2) Draw shapes and text each frame

The screen resets every frame, so redraw everything you want visible on every loop.

font = pygame.font.SysFont(None, 32)
score = 0

# inside the loop, after screen.fill(...)
pygame.draw.rect(screen, (80, 180, 255), (50, 80, 120, 60))
pygame.draw.circle(screen, (255, 180, 80), (260, 110), 30)
label = font.render(f"Score: {score}", True, (240, 240, 240))
screen.blit(label, (20, 20))

3) Handle keyboard input

Use pygame.key.get_pressed() for continuous movement and event checks for one-time actions.

player_x, player_y = 200, 200
speed = 5

# inside the loop
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
    player_x -= speed
if keys[pygame.K_RIGHT]:
    player_x += speed
if keys[pygame.K_UP]:
    player_y -= speed
if keys[pygame.K_DOWN]:
    player_y += speed

4) Keep objects with Rect and detect collisions

pygame.Rect is the most common way to track position, size, and collision in beginner games.

player = pygame.Rect(100, 100, 40, 40)
coin = pygame.Rect(300, 180, 20, 20)

# inside the loop
if keys[pygame.K_a]:
    player.x -= 4
if keys[pygame.K_d]:
    player.x += 4

if player.colliderect(coin):
    score += 1
    coin.x, coin.y = 500, 120  # move coin after collecting

pygame.draw.rect(screen, (120, 220, 120), player)
pygame.draw.rect(screen, (250, 220, 90), coin)

5) Static + moving animation without assets

You can build animation right away using numbers that update each frame. This avoids image loading setup and works well for starter games.

ball_x, ball_y = 120, 140
vx, vy = 4, 3
radius = 16

# inside the loop
ball_x += vx
ball_y += vy

if ball_x - radius <= 0 or ball_x + radius >= WIDTH:
    vx *= -1
if ball_y - radius <= 0 or ball_y + radius >= HEIGHT:
    vy *= -1

pygame.draw.circle(screen, (255, 90, 120), (ball_x, ball_y), radius)

6) Suggested first game plan

  • Build one player square that moves with arrow keys.
  • Add one collectible object and a score counter.
  • Add a win condition (for example, collect 10 items).
  • Add a restart key so you can test quickly.
  • Only after this works, add images, sound, and extra levels.

Common beginner mistakes

  • Forgetting to call pygame.display.flip() every frame.
  • Not limiting FPS with clock.tick(60).
  • Drawing once outside the loop and expecting it to persist.
  • Mixing up event-based input with held-key input.
  • Changing positions without checking screen boundaries.

Not Covered Yet (On Purpose)

We still skip advanced topics for now: inheritance depth, decorators, generators, file I/O project architecture, and comprehensive exception patterns. Mastering this core syntax set first makes advanced Python much easier later.