Coming From Another Language

Java, C# and C++ to Python

Coming To Python From Java, C# or C++

If you already write code in another language, you are not starting from zero. You are translating.

Almost everything you know carries across. A loop is still a loop. A function is still a function. An exception is still an exception. What changes is the spelling, and about five habits that will trip you in your first week.

This page is the translation table. Keep it open beside your editor for a fortnight and you will not need it again.

The mapping table

What you call itJava / C#Python
Whole numberint x = 5;x = 5
Decimaldouble d = 3.14;d = 3.14
TextString s = "hi";s = "hi"
True / falseboolean b = true;b = True
NothingnullNone
Growable arrayArrayList<String> / List<string>list
Key-value storeHashMap / Dictionarydict
Fixed-size arrayString[]tuple (or list)
No duplicatesHashSetset
Error handlingtry / catch / finallytry / except / finally
Base error typeExceptionException
Methodpublic int add(int a, int b)def add(a, b):
Classclass Agent { }class Agent:
Constructorpublic Agent()def __init__(self):
This objectthisself (written out, always)
Inheritanceclass B extends Aclass B(A):
Static-ish helperstatic methoda plain function in a module
Packagepackage com.acme;a folder with .py files
Importimport java.util.List;from typing import List
Dependency managerMaven / NuGetpip
Dependency filepom.xml / .csprojrequirements.txt
Build output.jar / .dllthere isn't one — you run the source
Entry pointpublic static void mainif __name__ == "__main__":
String formattingString.format(...)f"Hello {name}"
Lengthlist.size() / list.Countlen(list)
PrintSystem.out.println(x)print(x)
Comment// like this# like this
Equality of value.equals()==
Equality of identity==is

Note the last two rows carefully. They are swapped compared to Java. In Python, == compares values, which is what you almost always want. is compares whether two names point to the same object, which you almost never want except against None.

The five things that will actually trip you

1. There are no braces

Java marks a block with { and }. Python marks it with a colon at the end of the line and indentation on the lines that follow.

if severity == "P1":
    page_on_call()
    notify = True
print("done")

The two indented lines belong to the if. The print does not. The indentation is not formatting — it is the syntax, and getting it wrong changes what your program does. This has its own page, because it is the single most common early mistake.

2. You do not declare types

x = 5
x = "now I am text"

Both lines are legal. The variable does not have a type; the value does. This feels dangerous coming from a compiled language, and it genuinely is looser. Python's answer is type hints, which are optional annotations your editor and tooling check for you:

def add(a: int, b: int) -> int:
    return a + b

The hints do not stop the program from running with wrong types. They do let your editor catch the mistake before you run it, and they make agent code far easier to read. There is a page on them later.

3. Negative indexes are a feature, not a crash

students = ["Amit", "Sara", "John", "Anil"]
print(students[0])
print(students[-1])

In Java, arr[-1] throws ArrayIndexOutOfBoundsException. In Python, -1 means the last item, -2 the one before it, and so on. It is genuinely useful and it surprises everybody once.

Indexing still starts at 0, exactly as you are used to. And asking for students[10] when there are four students still fails — that part is the same.

4. There is no new, and no main

agent = Agent("triage")

No new keyword. You call the class as if it were a function.

There is also no mandatory main method. A .py file runs from the top, line by line. If you want code that runs only when the file is executed directly and not when it is imported, you write:

if __name__ == "__main__":
    run()

That line is Python's public static void main. It looks strange and then you stop noticing it.

5. Nothing is really private

Java has private. Python has a convention: a leading underscore means "this is internal, please do not touch it". Nothing enforces it.

class Agent:
    def __init__(self):
        self.name = "triage"
        self._retry_count = 0

_retry_count is still reachable from outside. The community treats the underscore as a closed door rather than a locked one. Coming from an enterprise codebase this feels reckless; in practice it causes far less trouble than you would expect.

Same idea, different spelling

Three things you already do every day, written the Python way.

Looping over a collection

tickets = ["P1", "P3", "P2", "P1"]

for t in tickets:
    if t == "P1":
        print("escalate", t)

There is no for (int i = 0; i < n; i++) here. Python's for is Java's enhanced for-loop, always. If you genuinely need the index, use enumerate:

for i, t in enumerate(tickets):
    print(i, t)

Catching an error

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print("cannot divide by zero:", e)
finally:
    print("always runs")

except instead of catch, and as e instead of (Exception e). Otherwise identical, including finally.

A key-value store

member = {"name": "Priya", "role": "Data Architect", "years": 14}

print(member["role"])
print(member.get("city", "unknown"))
member["city"] = "Pune"

This is your HashMap. member["city"] on a missing key raises KeyError, so .get() with a default is the safe form. You will use dictionaries constantly in agent work — every API response and every tool result arrives as one.

What genuinely has no equivalent

A few Python ideas have no clean Java or C# counterpart. You do not need them on day one, but you will meet them in agent code and wonder what you are looking at.

  • Comprehensions — building a list or dictionary in one expression, covered on its own page
  • Decorators — the @something lines above a function; closest cousin is a Java annotation, except a decorator actually wraps and changes the function
  • Duck typing — code that accepts any object with the right methods, without an interface or a base class anywhere
  • Multiple return valuesreturn a, b is normal, and the caller writes x, y = f()

A word on the mental block

There is a habit in our industry of introducing yourself as a Java person, or a .NET person, as though it were a nationality. It is worth dropping.

These languages are far more similar than they are different. You have already learned the hard parts — how systems fail, how data moves, what good code looks like under pressure. Picking up the spelling of a second language is a fortnight of mild discomfort, not a career change.

Practise this

  • Take a class you have written in Java or C# — a small one, a data holder with two or three methods — and rewrite it in Python without looking anything up. Then look up what you got wrong.
  • Write a loop over a list of dictionaries and print one field from each.
  • Write a try/except that catches a specific error type rather than a bare except.
  • Take one thing from the table above that surprised you and prove it to yourself in code.

Try It Yourself

Copy this into a new Colab notebook and run it. Nothing to install.

example.py
1# The same program you have written a hundred times, in Python.
2# Compare each block to how you would write it in Java or C#.
3
4# --- 1. No types, no semicolons, no braces ---
5name = "Priya"
6years = 14
7active = True
8nothing = None # null
9print(name, years, active, nothing)
10
11# --- 2. == is value equality (Java's .equals) ---
12a = "hello"
13b = "hel" + "lo"
14print("a == b :", a == b) # True - compares VALUE
15print("a is b :", a is b) # identity - do not use this for comparison
16
17# --- 3. Collections ---
18skills = ["Python", "SQL"] # ArrayList / List<string>
19skills.append("Cloud") # .add()
20print(len(skills)) # .size() / .Count
21
22member = {"name": "Priya", "tier": "diamond"} # HashMap / Dictionary
23print(member["tier"])
24print(member.get("city", "unknown")) # no KeyError
25
26# --- 4. Negative indexes are a feature, not a crash ---
27print(skills[0], skills[-1])
28try:
29 print(skills[99])
30except IndexError as e:
31 print("IndexError (same as Java):", e)
32
33# --- 5. Enhanced for is the ONLY for ---
34for skill in skills:
35 print("skill:", skill)
36
37for i, skill in enumerate(skills): # when you need the index
38 print(i, skill)
39
40# --- 6. try / except / finally ---
41try:
42 print(10 / 0)
43except ZeroDivisionError as e: # catch (Exception e)
44 print("caught:", e)
45finally:
46 print("finally still exists")
47
48# --- 7. A class: no `new`, explicit `self`, no `private` ---
49class Agent:
50 def __init__(self, name): # constructor
51 self.name = name
52 self._internal = 0 # "private" by convention only
53
54 def greet(self):
55 return f"I am {self.name}"
56
57agent = Agent("triage") # no `new`
58print(agent.greet())
59print("underscore is not enforced:", agent._internal)
60
61# --- 8. Multiple return values ---
62def bounds():
63 return 0, 100
64
65low, high = bounds()
66print(low, high)
67
68# --- 9. The entry point ---
69if __name__ == "__main__":
70 print("this is public static void main")