Python for AI Engineers · Part A · Lesson 2 of 26

Python for Java and JavaScript developers: the differences that matter

The Python you need when you already know Java or JavaScript: indentation instead of braces, dynamic but strong types, None and truthiness, == vs is, big integers and two kinds of division, f-strings, slicing, loops with enumerate and zip, and the one-line tricks Python code is full of.

⏱ 35 min3 exercises that check your codeRuns in your browser

By the end you can

  • Read and write Python blocks: indentation instead of braces, pass for an empty body
  • Predict what Python does with types, None, truthiness and == vs is, where it differs from Java and JS
  • Use / vs //, f-strings and slicing (negative indexes and steps) without surprises
  • Loop the Python way with for, range, enumerate and zip, and use the ternary, multiple assignment and swapping
1 / 7

1Blocks are indentation, and pass is an empty block

Python has no braces and no semicolons. A line that opens a block ends with a colon : (if, elif, else, for, while, def, class, try), and the block is every line below it that is indented further. The block ends when the indentation goes back. Use 4 spaces per level; your editor does this for you.

Conditions need no parentheses, else if is spelled elif, and the logic operators are words: and, or, not instead of &&, ||, !. Comments start with #.

A block cannot be empty. Where Java or JS would write {}, Python writes pass, a statement that does nothing. A function that ends without return returns None (the last line of output below).

Try it: edit and run
def classify(score):
    if score >= 0.8 and score <= 1.0:
        return "relevant"
    elif score >= 0.5:
        return "maybe"
    return "skip"


def not_written_yet():
    pass   # an empty body: Python needs at least one statement here


for s in [0.91, 0.6, 0.2]:
    print(s, classify(s))

print(not_written_yet())
Expected output
0.91 relevant
0.6 maybe
0.2 skip
None
Java
static String classify(double score) {
    if (score >= 0.8 && score <= 1.0) {
        return "relevant";
    } else if (score >= 0.5) {
        return "maybe";
    }
    return "skip";
}

static void notWrittenYet() {}
JavaScript
function classify(score) {
  if (score >= 0.8 && score <= 1.0) {
    return "relevant";
  } else if (score >= 0.5) {
    return "maybe";
  }
  return "skip";
}

function notWrittenYet() {}

Watch out Mixing tabs and spaces, or indenting one line by 3 spaces instead of 4, gives IndentationError or TabError. Let your editor insert 4 spaces and never mix the two in one file.

2Dynamic typing, but strong types

Dynamic means a variable has no declared type: a name just points at a value, and the same name can point at an int now and a str later. type(x) tells you what it holds right now. (Type hints, lesson 6, add types for your editor and checker, but Python does not enforce them when it runs.)

Strong means Python will not quietly convert between types for you. JavaScript turns "3" + 4 into "34" and Java turns "tokens: " + 42 into a string. Python raises TypeError instead, and you convert on purpose with str(), int() or float().

Try it: edit and run
x = 42
print(type(x))
x = "forty-two"          # the same name now holds a str: allowed
print(type(x))

try:
    print("tokens: " + 42)
except TypeError as e:   # try/except is Python's try/catch
    print("TypeError:", e)

print("tokens: " + str(42))
print(int("3") + 4)
print("ab" * 3)          # * on a str repeats it
Expected output
<class 'int'>
<class 'str'>
TypeError: can only concatenate str (not "int") to str
tokens: 42
7
ababab
Java
var x = 42;
// x = "forty-two";        // compile error: x is an int
System.out.println("tokens: " + 42);   // tokens: 42
System.out.println(Integer.parseInt("3") + 4);   // 7
JavaScript
let x = 42;
x = "forty-two";             // allowed, like Python
console.log("tokens: " + 42); // tokens: 42 (silent conversion)
console.log("3" + 4);         // "34"
console.log("3" * 4);         // 12

Tip Model APIs return text. When you parse a number out of a reply, convert it with int() or float() straight away and handle the ValueError they raise for text like "about 3".

3None, and what counts as false

Python has one "no value": None. There is no undefined. A missing variable is a NameError, a missing dict key is a KeyError, a missing attribute is an AttributeError. So the question "is it null or undefined?" never comes up. dict.get(key) is the polite lookup: it returns None when the key is missing.

Any value can be used in an if. These are falsy: None, False, 0, 0.0, "" and every empty container ([], {}, set(), ()). Everything else is truthy. This is the big difference from JavaScript, where [] and {} are truthy. Java has no truthiness at all: an if needs a real boolean.

So if not messages: is the Python way to say "if the list is empty". Test for None with is None, never == None.

Try it: edit and run
users = {1: "Asha"}
print(users.get(1), users.get(2))   # get() returns None for a missing key

for value in [None, 0, 0.0, "", [], {}, set(), "0", [0], " "]:
    print(repr(value), "->", bool(value))

reply = ""
if not reply:
    print("empty reply from the model")

retries = 0
if retries is None:
    print("retries was never set")
else:
    print("retries is", retries)
Expected output
Asha None
None -> False
0 -> False
0.0 -> False
'' -> False
[] -> False
{} -> False
set() -> False
'0' -> True
[0] -> True
' ' -> True
empty reply from the model
retries is 0
Java
List<String> messages = new ArrayList<>();
if (messages.isEmpty()) { /* ... */ }    // an if needs a boolean
String reply = map.get("key");           // null when missing
if (reply == null) { /* ... */ }
JavaScript
const messages = [];
if (!messages.length) { /* ... */ }   // [] itself is truthy!
const reply = obj.key;                // undefined when missing
if (reply == null) { /* null or undefined */ }

Watch out if not value: is also true for 0 and "". If 0 is a valid answer (zero retries, temperature 0.0), write if value is None: so you do not treat it as missing. This exact bug makes code ignore temperature=0.

4== compares values, is compares identity

In Python == asks "are these equal?", like Java's .equals(). Lists, dicts and strings compare by content. is asks "are these the same object?", like Java's == on objects or JavaScript's === on objects.

Assigning a list to a second name does not copy it: both names point to one list, so a change through one is visible through the other.

Try it: edit and run
a = [1, 2, 3]
b = [1, 2, 3]
c = a            # no copy: c and a are the same list

print(a == b)    # same contents?
print(a is b)    # same object?
print(a is c)

c.append(4)
print(a)         # changed through c

name = None
print(name is None)
Expected output
True
False
True
[1, 2, 3, 4]
True
Java
List<Integer> a = List.of(1, 2, 3);
List<Integer> b = List.of(1, 2, 3);
System.out.println(a.equals(b)); // true  (Python: a == b)
System.out.println(a == b);      // false (Python: a is b)
JavaScript
const a = [1, 2, 3];
const b = [1, 2, 3];
a === b;       // false: compares identity
// no built-in deep equality; Python's a == b is true

Tip Use is only for None (and the rare sentinel object). Use == for everything else, strings and numbers included. is on two equal numbers or strings sometimes says True because CPython reuses some small objects, which makes the bug hard to spot.

5Numbers: unbounded ints, / and //

A Python int has no maximum: it grows as big as memory allows, so there is no overflow and no long or BigInt to reach for. float is the same 64-bit double as Java's double and every JavaScript number, with the same rounding (0.1 + 0.2).

/ always returns a float, even for 6 / 3. // is floor division: it rounds down toward minus infinity, not toward zero like Java's integer /. % follows the same rule, so its result has the sign of the right-hand side. ** is power. Underscores in a number literal (1_000_000) are just for reading.

Try it: edit and run
print(2 ** 100)          # never overflows
print(7 / 2)             # / always gives a float
print(6 / 3)
print(7 // 2)            # floor division
print(-7 // 2)           # rounds down: -4, not -3 like Java
print(-7 % 3)            # 2, not -1 like Java
print(0.1 + 0.2)         # a double, same as Java and JS
print(round(0.1 + 0.2, 2))

tokens = 1_234_567
print(tokens // 1000, "thousand tokens")
Expected output
1267650600228229401496703205376
3.5
2.0
3
-4
2
0.30000000000000004
0.3
1234 thousand tokens
Java
System.out.println(Math.pow(2, 100));  // 1.2676506002282294E30 (a double)
System.out.println(Long.MAX_VALUE + 1); // overflows: a negative number
System.out.println(7 / 2);   // 3   (int division)
System.out.println(-7 / 2);  // -3  (toward zero)
System.out.println(-7 % 3);  // -1
JavaScript
2 ** 100;            // 1.2676506002282294e+30 (a float)
2n ** 100n;          // BigInt, a separate type
7 / 2;               // 3.5
Math.floor(-7 / 2);  // -4, like Python's -7 // 2
-7 % 3;              // -1

Watch out Ported Java code like mid = (lo + hi) / 2 now gives a float, and using it as a list index raises TypeError: list indices must be integers or slices, not float. Use // when you want an int.

6Strings: f-strings, and they never change

Single and double quotes mean the same thing. An f-string (an f before the quote) fills in anything inside {}, like a JavaScript template literal. After a colon you can add a format: :, adds thousands separators, :.4f gives 4 decimals, :<8 and :>8 pad to 8 characters. {name = } prints the expression and its value, handy for quick debugging.

Strings are immutable, as in Java and JavaScript: you cannot change one in place. Methods like upper() and replace() return a new string and leave the original alone.

Try it: edit and run
model = "llama3.2:3b"
tokens = 1234567
cost = 0.0004321

print(f"{model} used {tokens:,} tokens, cost {cost:.4f} USD")
print(f"{tokens = }")
print(f"[{'left':<8}|{'right':>8}]")

s = "hello"
try:
    s[0] = "H"
except TypeError as e:
    print("TypeError:", e)

s2 = "H" + s[1:]          # build a new string instead
print(s, s2, s.upper(), s.replace("l", "L"))
Expected output
llama3.2:3b used 1,234,567 tokens, cost 0.0004 USD
tokens = 1234567
[left    |   right]
TypeError: 'str' object does not support item assignment
hello Hello HELLO heLLo
Java
String.format("%s used %,d tokens, cost %.4f USD",
    model, tokens, cost);
"hello".toUpperCase();   // a new String
JavaScript
`${model} used ${tokens.toLocaleString("en-US")} tokens, cost ${cost.toFixed(4)} USD`;
"hello".toUpperCase();   // a new string

Tip f-strings are how you will build prompts: f"Answer using only this context:\n{context}\n\nQuestion: {question}". For long prompts use a triple-quoted f-string (f"""..."""), which can span lines.

7Slicing: negative indexes and steps

Indexes start at 0, and a negative index counts from the end: [-1] is the last item, [-2] the one before. No more s.charAt(s.length() - 1).

A slice [start:stop:step] takes a range: start is included, stop is excluded, any part can be left out. [:3] is the first three, [-3:] the last three, [::2] every second item, [::-1] the whole thing reversed. It works the same on strings, lists and tuples, and always returns a new object.

Slices are forgiving: a stop past the end just stops at the end, with no IndexOutOfBoundsException. A plain index past the end (history[100]) still raises IndexError.

Try it: edit and run
word = "embedding"
print(word[0], word[-1])        # first, last
print(word[0:3])                # index 0, 1, 2 (3 is excluded)
print(word[-3:])                # the last three
print(word[::2])                # every second character
print(word[::-1])               # reversed

history = ["system", "user 1", "bot 1", "user 2", "bot 2", "user 3"]
print(history[-3:])             # keep only the last 3 messages
print(history[1:100])           # a stop past the end is fine
recent = history[:]             # a shallow copy of the whole list
print(recent is history)
Expected output
e g
emb
ing
ebdig
gniddebme
['user 2', 'bot 2', 'user 3']
['user 1', 'bot 1', 'user 2', 'bot 2', 'user 3']
False
Java
word.charAt(word.length() - 1);   // last char
word.substring(0, 3);             // "emb"
history.subList(history.size() - 3, history.size());
new StringBuilder(word).reverse().toString();
JavaScript
word.at(-1);           // last char
word.slice(0, 3);      // "emb"
history.slice(-3);     // last 3
[...word].reverse().join("");

Trimming chat history to the last N messages so it fits the model's context window is a slice you will write in almost every chat app.

8Loops: for, range, enumerate, zip and while

Python's for is always a for-each: for doc in docs: walks any iterable (list, string, dict keys, file lines). There is no C-style for (int i = 0; i < n; i++). When you need numbers, loop over range(stop), range(start, stop) or range(start, stop, step); like slices, stop is excluded.

Need the index too? enumerate(docs) gives (index, item) pairs, and start=1 numbers from 1. Walking two lists side by side? zip(a, b) gives (a_item, b_item) pairs and stops at the shorter list. for i, doc in ... unpacks each pair into two names.

while works as you expect, with break and continue. Python also lets you put an else on a loop: it runs only when the loop finished without break. It is handy for "search, and say so if nothing was found", but many readers do not know it, so use it rarely.

Try it: edit and run
docs = ["intro.md", "setup.md", "faq.md"]
scores = [0.91, 0.42, 0.77]

for doc in docs:
    print(doc)

for i, doc in enumerate(docs, start=1):
    print(i, doc)

for doc, score in zip(docs, scores):
    print(f"{doc}: {score}")

print(list(range(5)), list(range(2, 10, 3)), list(range(3, 0, -1)))

attempt = 0
while attempt < 5:
    attempt += 1                      # Python has no ++
    if attempt == 3:
        print("succeeded on attempt", attempt)
        break
else:
    print("gave up")                  # skipped, because we did break
Expected output
intro.md
setup.md
faq.md
1 intro.md
2 setup.md
3 faq.md
intro.md: 0.91
setup.md: 0.42
faq.md: 0.77
[0, 1, 2, 3, 4] [2, 5, 8] [3, 2, 1]
succeeded on attempt 3
Java
for (String doc : docs) { System.out.println(doc); }
for (int i = 0; i < docs.size(); i++) {
    System.out.println((i + 1) + " " + docs.get(i));
}
// zip: loop over an index and call get(i) on both lists
JavaScript
for (const doc of docs) console.log(doc);
docs.forEach((doc, i) => console.log(i + 1, doc));
docs.forEach((doc, i) => console.log(doc + ": " + scores[i]));
// note: for...in gives indexes (as strings), not items

Tip Write zip(docs, scores, strict=True) when the two lists must be the same length (Python 3.10+). It raises ValueError instead of silently dropping the extra items, which catches a mismatched batch of embeddings early.

9The ternary, multiple assignment and swapping

Python's ternary reads like English: a if condition else b, where Java and JS write condition ? a : b.

You can assign several names in one line: x, y = 1, 2. The right side is a tuple and it is unpacked into the names on the left, so swapping two variables needs no temp: a, b = b, a. A starred name collects the rest into a list. Comparisons can also be chained: 0 <= score <= 1 means 0 <= score and score <= 1.

Try it: edit and run
score = 0.72
label = "relevant" if score >= 0.5 else "skip"
print(label)

prompt_tokens, completion_tokens = 120, 45
print(prompt_tokens + completion_tokens)

a, b = "first", "second"
a, b = b, a                      # swap, no temp variable
print(a, b)

role, *rest = ["system", "be brief", "answer in English"]
print(role, rest)

print(0 <= score <= 1)           # chained comparison
Expected output
relevant
165
second first
system ['be brief', 'answer in English']
True
Java
String label = score >= 0.5 ? "relevant" : "skip";
String tmp = a; a = b; b = tmp;          // swap
boolean ok = 0 <= score && score <= 1;
JavaScript
const label = score >= 0.5 ? "relevant" : "skip";
[a, b] = [b, a];                          // swap
const [role, ...rest] = ["system", "be brief", "answer in English"];

You will see unpacking everywhere in AI code: for doc, score in results: over search hits, answer, usage = call_model(prompt) from a helper that returns two values.

Common mistakes

  • Writing if not value: when 0, 0.0 or "" is a valid value. Use if value is None: to mean "missing".
  • Comparing with is instead of == for strings or numbers. It can pass in a quick test and fail later. is is for None.
  • Porting Java integer math with /: it now returns a float. Use // for whole-number division, and remember it rounds toward minus infinity.
  • Expecting "tokens: " + 42 to work as it does in Java and JS. Python raises TypeError: use an f-string or str().
  • Thinking b = a copies a list. Both names point to one list; copy with a[:] or list(a).
  • Taking the last n items with items[-n:] when n can be 0: -0 is 0, so you get the whole list.

Practice

Write the code, then press Check. Your work is saved in this browser.

1Keep the last n messages

Write last_n(messages, n) that returns a new list with the last n messages, for trimming chat history. If n is 0 it must return an empty list, and if n is larger than the list it returns all of them. Run the starter first: one case is wrong.

Exercise
def last_n(messages, n):
    return messages[-n:]


print(last_n(["a", "b", "c"], 2))
print(last_n(["a", "b", "c"], 0))
Hint

-0 is just 0, and messages[0:] is the whole list. Return an empty list when n is 0 (or less) before you slice.

2Drop missing values, keep zeros

An LLM filled in a form and some fields came back as None or "". Write present(values) that returns a new list without the None and "" items, but keeps 0, 0.0 and False, which are real answers. Keep the original order.

Exercise
def present(values):
    out = []
    for v in values:
        if v:
            out.append(v)
    return out


print(present([3, None, 0, "", "ok", 0.0]))
Hint

if v: is false for 0 too. Test exactly what you mean: v is not None and v != "".

3Number the search results

Write numbered(docs, scores) that returns lines like "1. intro.md (0.91)", numbered from 1, pairing each doc with its score. Show the score with exactly 2 decimals. Use enumerate, zip and an f-string.

Exercise
def numbered(docs, scores):
    lines = []
    for i, (doc, score) in enumerate(zip(docs, scores)):
        lines.append(f"{i}. {doc} ({score})")
    return lines


print(numbered(["intro.md", "faq.md"], [0.912, 0.5]))
Hint

enumerate(..., start=1) numbers from 1, and {score:.2f} formats a number with 2 decimals.

Interview questions

Q1Is Python statically or dynamically typed, and strongly or weakly?

Dynamically typed: names have no declared type and can be rebound to any value; types are checked when the code runs. Strongly typed: it does not convert implicitly between unrelated types, so "a" + 1 raises TypeError instead of producing "a1" as JavaScript does. Type hints are optional and not enforced at run time.

Q2What is the difference between == and is?

== compares values (it calls __eq__, like Java's equals). is checks identity, whether both names refer to the same object, like Java's == on references. Use is for None and == for everything else.

Q3Which values are falsy in Python?

None, False, zero of any numeric type (0, 0.0), and empty sequences and collections: "", [], (), {}, set(), range(0). Objects can define their own truthiness with __bool__ or __len__. Unlike JavaScript, empty lists and dicts are falsy.

Q4What does -7 // 2 return, and why?

-4. // is floor division and rounds toward minus infinity, so that a == (a // b) * b + a % b always holds; that is also why -7 % 3 is 2. Java and C round integer division toward zero and give -3.

Q5Can a Python int overflow?

No. Python ints are arbitrary precision and grow as needed, limited only by memory. Floats are 64-bit IEEE 754 doubles and can overflow to inf or lose precision. Libraries like NumPy use fixed-size ints, which can overflow.

Q6How do you reverse a string or list in Python?

With a slice with step -1: s[::-1], which returns a new object. For a list you can also call items.reverse() to reverse it in place, or reversed(items) to get an iterator.