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.
| Language | Example |
| 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.
| Type | Java | Python | Notes |
| Integer | int a = 27; | a = 27 | Signed integer |
| Long | long a = 90210L; | a = 90210 | Python 3 handles big integers automatically |
| Float | float a = 7.25f; | a = 7.25 | Floating point |
| Complex | Not built in | a = 2.5J | Complex number |
3. Data Structures
3.1 String
Strings can use single quotes '...', double quotes "...", or triple quotes """...""" for multi-line text.
| Operation | Java | Python |
| Find position | str.indexOf() / str.charAt() | str.find() / str.index() |
| Length | str.length() | len(str) |
| Replace | str.replace() | str.replace() |
| Convert to string | String.valueOf() / toString() | str() |
| Trim whitespace | str.trim() | str.strip(), str.lstrip(), str.rstrip() |
| Compare | str1.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):
| Operation | Java (ArrayList) | Python (List) |
| Create | List<Object> list = new ArrayList<>(); | list = [] |
| Add | list.add(obj); | list.append(obj) |
| Access | list.get(i); | list[i] |
| Length | list.size(); | len(list) |
| Copy | list2 = 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):
| Operation | Java (HashMap) | Python (Dict) |
| Create | Map<K, V> map = new HashMap<>(); | my_dict = {} |
| Clear | map.clear(); | my_dict.clear() |
| Copy | map.clone(); | my_dict.copy() |
| Check key | map.containsKey(key); | key in my_dict |
| Get value | map.get(key); | my_dict.get(key) or my_dict[key] |
| Get keys | map.keySet(); | my_dict.keys() |
| Add / update | map.put(key, value); | my_dict[key] = value |
| Remove | map.remove(key); | my_dict.pop(key) |
| Size | map.size(); | len(my_dict) |
4. Operators & Precedence
4.1 Arithmetic
| Java | Python | Description |
| None | ** | Exponentiation |
- | - | Unary negation |
* | * | Multiplication |
/ | / | Division |
% | % | Modulus |
+ / - | + / - | Addition / subtraction |
4.2 Logical & bitwise
| Java | Python | Description |
! | not | Logical NOT |
& | & | Bitwise AND |
| | | | Bitwise OR |
^ | ^ | Bitwise XOR |
&& | and | Logical AND |
|| | or | Logical OR |
4.3 Comparison
| Java | Python | Description |
< / > | < / > | Less than / greater than |
<= / >= | <= / >= | Less or equal / greater or equal |
== | == | Value equality (like Java's .equals()) |
!= | != | Not equal |
== (reference) | is | Identity (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:
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ệu | Java | Python | Ghi chú |
| Integer | int a = 27; | a = 27 | Số nguyên có dấu |
| Long | long a = 90210L; | a = 90210 | Python 3 tự động xử lý số nguyên lớn |
| Float | float a = 7.25f; | a = 7.25 | Số thực |
| Complex | Không hỗ trợ sẵn | a = 2.5J | Số 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ác | Java | Python |
| Tìm vị trí | str.indexOf() / str.charAt() | str.find() / str.index() |
| Độ dài | str.length() | len(str) |
| Thay thế | str.replace() | str.replace() |
| Chuyển kiểu chuỗi | String.valueOf() / toString() | str() |
| Xóa khoảng trắng | str.trim() | str.strip(), str.lstrip(), str.rstrip() |
| So sánh chuỗi | str1.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ác | Java (ArrayList) | Python (List) |
| Khởi tạo | List<Object> list = new ArrayList<>(); | list = [] |
| Thêm phần tử | list.add(obj); | list.append(obj) |
| Truy xuất | list.get(i); | list[i] |
| Độ dài | list.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ác | Java (HashMap) | Python (Dict) |
| Khởi tạo | Map<K, V> map = new HashMap<>(); | my_dict = {} |
| Xóa sạch | map.clear(); | my_dict.clear() |
| Sao chép | map.clone(); | my_dict.copy() |
| Kiểm tra Key | map.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 Key | map.keySet(); | my_dict.keys() |
| Thêm/Sửa | map.put(key, value); | my_dict[key] = value |
| Xóa phần tử | map.remove(key); | my_dict.pop(key) |
| Kích thước | map.size(); | len(my_dict) |
4. Toán tử & Thứ tự ưu tiên (Operators)
4.1 Toán tử số học (Arithmetic)
| Java | Python | Mô 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)
| Java | Python | Mô tả |
! | not | Phủ đị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)
| Java | Python | Mô 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) | is | So 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:
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).
Reference / Tài liệu tham khảo