English version

What is Python?

Python is an object-oriented programming language created by Guido van Rossum in 1989. It is hugely popular and runs on many operating systems, including Windows, Linux, Ubuntu and macOS. Python is an interpreted language, so anyone can open a terminal and type Python commands directly. It is widely used in AI & Machine Learning, live streaming data processing, Big Data, mathematics, physics and many other scientific fields. Python complements Java; it cannot fully replace Java in the global IT market.

Learning Python quickly as a Java developer

Java developers can pick up Python fast by comparing it directly with Java and noting the similarities and differences. A cheat sheet is therefore the most efficient way to learn the basics.

1. Basic Syntax

1.1 End of statements

  • Java: every statement ends with a semicolon ;.
  • Python: no ; needed (a newline ends the statement). You may still use ; to put several statements on one line.

Printing:

// Java
System.out.println("Hello Blogger!");

# Python
print("Hello Blogger!")

1.2 Code blocks and indentation

  • Java: curly braces {} delimit blocks.
  • Python: indentation (4 spaces) defines blocks.
LanguageExample
Java
if (5 == value) {
    System.out.println("Value is five");
} else {
    System.out.println("Value is not five.");
}
Python
if 5 == value:
    print('Value is five')
else:
    print('Value is not five.')

2. Variables & Data Types

Python is dynamically typed: you do not declare a variable's type.

2.1 Declaring and assigning

# Single assignment
number = 27
string = "A short sample string"

# Multiple assignment
a, b = False, True
a = b = c = 7
a, b, c = 3, 4, "mary"

2.2 Numeric types

Python converts between numeric types automatically when needed.

TypeJavaPythonNotes
Integerint a = 27;a = 27Signed integer
Longlong a = 90210L;a = 90210Python 3 handles big integers automatically
Floatfloat a = 7.25f;a = 7.25Floating point
ComplexNot built ina = 2.5JComplex number

3. Data Structures

3.1 String

Strings can use single quotes '...', double quotes "...", or triple quotes """...""" for multi-line text.

OperationJavaPython
Find positionstr.indexOf() / str.charAt()str.find() / str.index()
Lengthstr.length()len(str)
Replacestr.replace()str.replace()
Convert to stringString.valueOf() / toString()str()
Trim whitespacestr.trim()str.strip(), str.lstrip(), str.rstrip()
Comparestr1.equals(str2)str1 == str2

3.2 Boolean & falsy values

Every object in Python has a Boolean value. The following evaluate to False:

  • None (equivalent to null in Java)
  • False
  • The number 0
  • Empty collections: "", (), [], {}
Note: in Java null != false, but in Python None behaves as falsy in a Boolean context.

3.3 List (like Java's ArrayList)

A list is mutable and can hold elements of different types (heterogeneous).

A = []                      # empty list
B = [3, 14, 59, 26]         # list of 4 numbers
C = [8, 6, 'mary']          # mixed types
D = ["Z", B, C]             # list containing other lists

ArrayList (Java) vs List (Python):

OperationJava (ArrayList)Python (List)
CreateList<Object> list = new ArrayList<>();list = []
Addlist.add(obj);list.append(obj)
Accesslist.get(i);list[i]
Lengthlist.size();len(list)
Copylist2 = list.clone();list2 = list[:] or list.copy()

3.4 Tuple (fixed / immutable list)

A tuple looks like a list but is immutable. It is used in place of a static array for better performance.

A = ()                      # empty tuple
B = (2, 71, 82, 8)         # tuple of 4 numbers
C = (9, 5, 'peter')          # heterogeneous tuple
D = ("Z", B, C)             # nested tuple

3.5 Dictionary (like Java's HashMap)

A dictionary stores key: value pairs. Keys are unique and may be of different types.

# Create
hotel_rooms = {'anna': 215, 'bob': 118}

# Add / update
hotel_rooms['anna'] = 507
hotel_rooms['linh'] = 402

# Get all keys
print(hotel_rooms.keys())

# Check whether a key exists
if 'linh' in hotel_rooms:
    print("Exists!")

HashMap (Java) vs Dictionary (Python):

OperationJava (HashMap)Python (Dict)
CreateMap<K, V> map = new HashMap<>();my_dict = {}
Clearmap.clear();my_dict.clear()
Copymap.clone();my_dict.copy()
Check keymap.containsKey(key);key in my_dict
Get valuemap.get(key);my_dict.get(key) or my_dict[key]
Get keysmap.keySet();my_dict.keys()
Add / updatemap.put(key, value);my_dict[key] = value
Removemap.remove(key);my_dict.pop(key)
Sizemap.size();len(my_dict)

4. Operators & Precedence

4.1 Arithmetic

JavaPythonDescription
None**Exponentiation
--Unary negation
**Multiplication
//Division
%%Modulus
+ / -+ / -Addition / subtraction

4.2 Logical & bitwise

JavaPythonDescription
!notLogical NOT
&&Bitwise AND
||Bitwise OR
^^Bitwise XOR
&&andLogical AND
||orLogical OR

4.3 Comparison

JavaPythonDescription
< / >< / >Less than / greater than
<= / >=<= / >=Less or equal / greater or equal
====Value equality (like Java's .equals())
!=!=Not equal
== (reference)isIdentity (same object in memory)

5. Conditionals

5.1 if - elif - else

Python writes else if as elif.

var1 = 20

if var1 <= 10:
    print("Case A: " + str(var1))
elif var1 == 20:
    print("Case B: " + str(var1))
elif var1 >= 30:
    print("Case C: " + str(var1))
else:
    print("Out of range!")

5.2 Combining conditions

skill1 = "spring"
skill2 = "django"

# Both conditions are true
if skill1 == "spring" and skill2 == "django":
    print("Both conditions are met")

# At least one condition is true
if skill1 == "spring" or skill2 == "django":
    print("At least one condition is met")

6. Looping

for loop with range()

In Python, for is usually combined with range(start, stop, step) to iterate over indices.

# 2 to 7 (same as for(int x=2; x<8; x++) in Java)
for x in range(2, 8):
    print("Loop count: " + str(x))

# Custom step: from 20 down to 5, step -5
for x in range(20, 0, -5):
    print(x)

7. Advanced Differences Between Python and Java

  • Multiple inheritance: Python supports it directly for classes; Java does not (it only allows multiple interface implementation).
  • Tuple type: Java has no tuple. In Python, a tuple is like a list/array but immutable: you can create it but not change it afterwards.
  • Attribute initialization: in Python, instance attributes are defined inside __init__() (the equivalent of a Java constructor):
def __init__(self, color, model, year):
    self.color = color
    self.model = model
    self.year = year

self vs this:

  • In Java, an object refers to itself with this:
    public void setColor(String color) {
        this.color = color;
    }
    Note: in Java, this can be omitted implicitly when accessing fields.
  • In Python, self plays the same role, but unlike this in Java it is mandatory when creating or accessing instance attributes.

You can also define attributes in __init__() and use the @property decorator to control access (the equivalent of a Java getter):

class Car:
    def __init__(self, color, model, year):
        self.color = color
        self.model = model
        self.year = year
        self._voltage = 12

    @property
    def voltage(self):
        return self._voltage
  • Naming convention: a leading underscore (_voltage) signals an internal/protected attribute.
  • @property decorator: works like a Java getter, letting you write car.voltage instead of car.getVoltage(), which is cleaner and more "Pythonic".

Học nhanh Python dành cho lập trình viên Java (Tiếng Việt)

Python là gì?

Python là một ngôn ngữ lập trình hướng đối tượng được sáng tạo bởi Guido van Rossum vào năm 1989. Ngôn ngữ này rất phổ biến và có mặt trên nhiều hệ điều hành khác nhau, từ Windows cho đến Linux, Ubuntu hay macOS. Python là ngôn ngữ thông dịch (interpreted language), cho phép bất kỳ ai cũng có thể mở terminal và gõ trực tiếp các lệnh Python. Python được sử dụng rộng rãi trong các lĩnh vực AI & Machine Learning (Trí tuệ nhân tạo & Học máy), xử lý dữ liệu phát trực tiếp (live streaming data), Big Data, Toán học, Vật lý và nhiều ngành khoa học khác. Python đóng vai trò bổ trợ cho Java và không thể thay thế hoàn toàn Java trên thị trường IT toàn cầu.

Học nhanh Python cho lập trình viên Java

Các lập trình viên Java có thể dễ dàng tiếp cận Python bằng cách so sánh trực tiếp với Java, qua đó nắm rõ điểm tương đồng cũng như khác biệt giữa hai ngôn ngữ. Vì vậy, một tài liệu tóm tắt (cheat sheet) là giải pháp tối ưu để học nhanh các kiến thức Python cơ bản.

1. Cú pháp cơ bản (Basic Syntax)

1.1 Kết thúc câu lệnh

  • Java: mọi câu lệnh kết thúc bằng dấu chấm phẩy ;.
  • Python: không cần dấu ; (dùng xuống dòng bằng Enter). Tuy nhiên vẫn có thể dùng ; nếu muốn viết nhiều câu lệnh trên cùng một dòng.

In ra màn hình (print):

// Java
System.out.println("Hello Blogger!");

# Python
print("Hello Blogger!")

1.2 Khối lệnh và thụt lề (Indentation)

  • Java: dùng cặp ngoặc nhọn {} để bao khối lệnh.
  • Python: dùng thụt lề (4 khoảng trắng) để định nghĩa khối lệnh.
Ngôn ngữCú pháp ví dụ
Java
if (5 == value) {
    System.out.println("Value is five");
} else {
    System.out.println("Value is not five.");
}
Python
if 5 == value:
    print('Value is five')
else:
    print('Value is not five.')

2. Biến & Kiểu dữ liệu (Variables & Data Types)

Python là ngôn ngữ kiểu động (dynamically typed): không cần khai báo kiểu dữ liệu trước.

2.1 Khai báo và gán giá trị

# Khai báo đơn
number = 27
string = "A short sample string"

# Khai báo nhiều biến đồng thời
a, b = False, True
a = b = c = 7
a, b, c = 3, 4, "mary"

2.2 Các kiểu số cơ bản (Numbers)

Python tự động chuyển đổi kiểu số khi cần thiết.

Kiểu dữ liệuJavaPythonGhi chú
Integerint a = 27;a = 27Số nguyên có dấu
Longlong a = 90210L;a = 90210Python 3 tự động xử lý số nguyên lớn
Floatfloat a = 7.25f;a = 7.25Số thực
ComplexKhông hỗ trợ sẵna = 2.5JSố phức

3. Cấu trúc dữ liệu (Data Structures)

3.1 Chuỗi (String)

Hỗ trợ nháy đơn '...', nháy kép "..." và nháy ba """...""" (dành cho chuỗi nhiều dòng).

Thao tácJavaPython
Tìm vị trístr.indexOf() / str.charAt()str.find() / str.index()
Độ dàistr.length()len(str)
Thay thếstr.replace()str.replace()
Chuyển kiểu chuỗiString.valueOf() / toString()str()
Xóa khoảng trắngstr.trim()str.strip(), str.lstrip(), str.rstrip()
So sánh chuỗistr1.equals(str2)str1 == str2

3.2 Boolean & giá trị Falsy

Mọi đối tượng trong Python đều có giá trị Boolean. Các giá trị sau được tính là False:

  • None (tương đương null trong Java)
  • False
  • Số 0
  • Tập hợp rỗng: "", (), [], {}
Lưu ý: trong Java null != false, nhưng trong Python None được đánh giá là Falsy trong ngữ cảnh Boolean.

3.3 List (tương đương ArrayList trong Java)

List là danh sách có thể thay đổi (mutable), chứa các phần tử không cùng kiểu (heterogeneous).

A = []                      # List rỗng
B = [3, 14, 59, 26]         # List chứa 4 số
C = [8, 6, 'mary']          # List chứa nhiều kiểu dữ liệu
D = ["Z", B, C]             # List chứa List khác

So sánh ArrayList (Java) vs List (Python):

Thao tácJava (ArrayList)Python (List)
Khởi tạoList<Object> list = new ArrayList<>();list = []
Thêm phần tửlist.add(obj);list.append(obj)
Truy xuấtlist.get(i);list[i]
Độ dàilist.size();len(list)
Sao chép (Clone)list2 = list.clone();list2 = list[:] hoặc list.copy()

3.4 Tuple (mảng cố định / immutable list)

Tuple có cấu trúc giống List nhưng không thể sửa đổi (immutable). Được dùng thay cho mảng tĩnh (static array) để tối ưu hiệu năng.

A = ()                      # Tuple rỗng
B = (2, 71, 82, 8)         # Tuple 4 số
C = (9, 5, 'peter')          # Heterogeneous Tuple
D = ("Z", B, C)             # Tuple lồng nhau

3.5 Dictionary (tương đương HashMap trong Java)

Dictionary lưu trữ dữ liệu dạng cặp Key: Value. Key không trùng lặp và có thể thuộc các kiểu dữ liệu khác nhau.

# Khởi tạo
hotel_rooms = {'anna': 215, 'bob': 118}

# Thêm / Cập nhật
hotel_rooms['anna'] = 507
hotel_rooms['linh'] = 402

# Lấy danh sách keys
print(hotel_rooms.keys())

# Kiểm tra Key tồn tại
if 'linh' in hotel_rooms:
    print("Exists!")

So sánh HashMap (Java) vs Dictionary (Python):

Thao tácJava (HashMap)Python (Dict)
Khởi tạoMap<K, V> map = new HashMap<>();my_dict = {}
Xóa sạchmap.clear();my_dict.clear()
Sao chépmap.clone();my_dict.copy()
Kiểm tra Keymap.containsKey(key);key in my_dict
Lấy giá trịmap.get(key);my_dict.get(key) hoặc my_dict[key]
Lấy tập Keymap.keySet();my_dict.keys()
Thêm/Sửamap.put(key, value);my_dict[key] = value
Xóa phần tửmap.remove(key);my_dict.pop(key)
Kích thướcmap.size();len(my_dict)

4. Toán tử & Thứ tự ưu tiên (Operators)

4.1 Toán tử số học (Arithmetic)

JavaPythonMô tả
Không có**Lũy thừa (Exponentiation)
--Đổi dấu (Unary negation)
**Nhân
//Chia
%%Chia lấy dư (Modulus)
+ / -+ / -Cộng / Trừ

4.2 Toán tử logic & bit (Logical & Bitwise)

JavaPythonMô tả
!notPhủ định (Logical NOT)
&&AND theo bit
||OR theo bit
^^XOR theo bit
&&andĐiều kiện AND
||orĐiều kiện OR

4.3 Toán tử so sánh (Comparison)

JavaPythonMô tả
< / >< / >Nhỏ hơn / Lớn hơn
<= / >=<= / >=Nhỏ hơn hoặc bằng / Lớn hơn hoặc bằng
====So sánh giá trị (tương đương .equals() của Java)
!=!=Khác nhau
== (ref)isSo sánh địa chỉ ô nhớ / identity (cùng một đối tượng)

5. Cấu trúc điều kiện (Conditionals)

5.1 Cú pháp if - elif - else

Trong Python, else if được viết gọn thành elif.

var1 = 20

if var1 <= 10:
    print("Case A: " + str(var1))
elif var1 == 20:
    print("Case B: " + str(var1))
elif var1 >= 30:
    print("Case C: " + str(var1))
else:
    print("Out of range!")

5.2 Kết hợp nhiều điều kiện

skill1 = "spring"
skill2 = "django"

# Cả hai điều kiện đều đúng
if skill1 == "spring" and skill2 == "django":
    print("Both conditions are met")

# Ít nhất một điều kiện đúng
if skill1 == "spring" or skill2 == "django":
    print("At least one condition is met")

6. Vòng lặp (Looping)

Vòng lặp for với range()

Trong Python, vòng lặp for thường kết hợp với hàm range(start, stop, step) để duyệt chỉ số.

# Chạy từ 2 đến 7 (tương đương for(int x=2; x<8; x++) trong Java)
for x in range(2, 8):
    print("Loop count: " + str(x))

# Tùy chỉnh bước nhảy (step)
# Chạy từ 20 về 5 với bước nhảy -5
for x in range(20, 0, -5):
    print(x)

7. Những điểm khác biệt nâng cao giữa Python và Java

  • Đa kế thừa (Multiple inheritance): Python hỗ trợ đa kế thừa trực tiếp trong lớp (class), trong khi Java thì không (Java chỉ cho phép implement nhiều interface).
  • Kiểu dữ liệu Tuple: Java không có Tuple. Trong Python, Tuple tương tự List (hoặc Array) nhưng bất biến (immutable): chỉ có thể khởi tạo chứ không thể thay đổi sau khi tạo.
  • Khởi tạo thuộc tính: trong Python, các thuộc tính của đối tượng được khai báo bên trong phương thức __init__() (tương đương constructor trong Java):
def __init__(self, color, model, year):
    self.color = color
    self.model = model
    self.year = year

Từ khóa self và this:

  • Trong Java, đối tượng tự tham chiếu đến chính nó bằng từ khóa this:
    public void setColor(String color) {
        this.color = color;
    }
    Lưu ý: trong Java, this có thể được ngầm định (bỏ đi) khi truy cập thuộc tính.
  • Trong Python, self đóng vai trò tương tự, nhưng khác với this trong Java, self là bắt buộc khi tạo hoặc truy cập thuộc tính của đối tượng.

Bạn cũng có thể khai báo thuộc tính trong __init__() và dùng decorator @property để quản lý truy cập (tương đương Getter trong Java):

class Car:
    def __init__(self, color, model, year):
        self.color = color
        self.model = model
        self.year = year
        self._voltage = 12

    @property
    def voltage(self):
        return self._voltage
  • Quy ước tên biến: dấu gạch dưới _voltage báo hiệu đây là thuộc tính nội bộ (internal/protected).
  • Decorator @property: đóng vai trò như Getter trong Java, cho phép truy cập thuộc tính như một biến thông thường (car.voltage) thay vì gọi hàm (car.getVoltage()), giúp code gọn gàng và đúng phong cách Python (Pythonic).
Java vs Python

Reference / Tài liệu tham khảo