Skip to content

Week 1 · Python and your developer toolkit

Live session: Python basics

Session outline and demo code for the first live session, from variables to loops.

Live sessionEstimated time: 2 h

Session details

  • When and where: see the calendar invite for the time and video link
  • Bring: a working setup from the setup guide, and your ~/projects/fde-course folder from the terminal lesson's daily task
  • How to follow along: type every demo yourself in a file called basics.py and run it with python3 basics.py. Don't copy and paste.

Agenda

TimeSegmentFormat
0:00Check-in: setup problems and questions from the pre-workWhole group
0:10Demo 1: values, variables and typesLive coding
0:30Demo 2: working with textLive coding
0:45Demo 3: lists and dictionariesLive coding
1:05Break
1:15Demo 4: making decisions with ifLive coding
1:30Demo 5: repeating work with loopsLive coding
1:50Reading errors, and preview of the guided buildInstructor

Demo 1: values, variables and types

A variable is a name that points to a value. You create one with =:

customer = "Noor Foods"
order_total = 12800
discount_rate = 0.1
is_paid = False

Every value has a type, which decides what you can do with it:

TypeExampleUsed for
str (string)"Noor Foods"Text
int (integer)12800Whole numbers
float0.1Numbers with a decimal point
bool (boolean)True, FalseYes/no values

Check a value's type with type(), and do arithmetic with +, -, *, /:

print(type(order_total))      # <class 'int'>

discount = order_total * discount_rate
final_total = order_total - discount
print(final_total)            # 11520.0

Lines starting with # are comments: notes for humans that Python ignores.

Demo 2: working with text

Strings have built-in tools, called methods, that you call with a dot:

raw_email = "  Support@NoorFoods.PK  "
email = raw_email.strip().lower()
print(email)                  # support@noorfoods.pk
print(len(email))             # 20

To put values inside text, use an f-string: put f before the quotes and the values in curly braces:

print(f"{customer} owes Rs {final_total:,.0f}")
# Noor Foods owes Rs 11,520

The :,.0f part formats the number with commas and no decimal places.

Demo 3: lists and dictionaries

A list holds several values in order. Positions start at 0:

order_totals = [4500, 12800, 2300]
print(order_totals[0])        # 4500
order_totals.append(7600)
print(len(order_totals))      # 4
print(sum(order_totals))      # 27200

A dictionary stores values under names, called keys. Think of one row of a spreadsheet:

order = {"id": "A102", "customer": "Noor Foods", "total": 12800, "status": "pending"}
print(order["customer"])      # Noor Foods
order["status"] = "delivered"
print(order)

Real data is often a list of dictionaries: many rows, each with the same keys. You'll use this shape all the time, including when you read data from APIs in week 3.

Demo 4: making decisions with if

total = 12800

if total > 10000:
    print("Large order: check stock before confirming")
elif total > 5000:
    print("Medium order")
else:
    print("Small order")

The indented lines belong to the if above them. Python uses indentation (4 spaces) to group code, so it matters. Comparisons you'll use: == (equal), != (not equal), >, <, >=, <=. Combine conditions with and and or.

Demo 5: repeating work with loops

A for loop runs the same code for each item in a list:

orders = [
    {"id": "A101", "total": 4500, "status": "delivered"},
    {"id": "A102", "total": 12800, "status": "pending"},
    {"id": "A103", "total": 2300, "status": "delivered"},
]

pending_count = 0
for order in orders:
    if order["status"] == "pending":
        pending_count += 1
        print(f"Pending: {order['id']}")

print(f"{pending_count} order(s) pending")

pending_count += 1 is short for pending_count = pending_count + 1. Starting a variable at zero and adding to it inside a loop is called accumulating, and it's one of the most common patterns in programming.

Reading errors

You'll see these four errors constantly this week. Each message tells you the line number and what went wrong:

ErrorUsual cause
SyntaxErrorA typo in the code's structure: a missing quote, bracket or colon
IndentationErrorLines inside an if or for aren't indented consistently
NameErrorYou used a variable before creating it, or misspelled its name
TypeErrorYou mixed types that don't work together, such as "5" + 5

After the session

  • Finish the daily task above.
  • Make sure your ~/projects/fde-course folder is ready for the guided build.
  • Write down any error you couldn't fix, with the exact message, and bring it to the next session.

Finished this lesson?