What is Python?
Python is an object-oriented programming language created by Guido van Rossum in 1989 (first public release in 1991). 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. All examples below use Python 3 (3.10 or newer for match/case).
- 1. Setup & Running Code
- 2. Basic Syntax
- 3. Variables & Data Types
- 4. Strings
- 5. Boolean,
None& Falsy Values - 6. Data Structures (Collections)
- 7. Operators & Precedence
- 8. Conditionals
- 9. Looping
- 10. Functions
- 11. Classes & Object-Oriented Programming
- 12. Exception Handling
- 13. Modules & Packages
- 14. File I/O
- 15. Type Hints (optional)
- 16. Common Pitfalls for Java Developers
- 17. Quick Java → Python Mapping
1. Setup & Running Code
| Topic | Java | Python |
|---|---|---|
| Run code | javac Main.java + java Main | python3 main.py (interpreted, no compile step) |
| Interactive shell | jshell | python3 (REPL) |
| Build / dependency tool | Maven / Gradle | pip + venv |
| Dependency file | pom.xml / build.gradle | requirements.txt / pyproject.toml |
| Package repository | Maven Central | PyPI |
Create an isolated environment per project (similar to a per-project Maven .m2 setup):
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install requests # install a library
pip freeze > requirements.txt # save the dependency list
pip install -r requirements.txt
2. Basic Syntax
2.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:
| Language | Example |
|---|---|
| Java | |
| Python | |
2.2 Program entry point
Python has no required main class. Code runs top to bottom; the __main__ guard makes a file usable both as a script and as an importable module.
| Language | Example |
|---|---|
| Java | |
| Python | |
2.3 Comments
| Language | Example |
|---|---|
| Java | |
| Python | |
2.4 Code blocks and indentation
- Java: curly braces
{}delimit blocks. - Python: indentation (4 spaces) defines blocks. Never mix tabs and spaces.
| Language | Example |
|---|---|
| Java | |
| Python | |
2.5 Reading input
| Language | Example |
|---|---|
| Java | |
| Python | |
3. Variables & Data Types
Python is dynamically typed: you do not declare a variable's type; the type belongs to the value, not the variable.
3.1 Declaring and assigning
| Language | Example |
|---|---|
| Java | |
| Python | |
# Multiple assignment
a, b = False, True
a = b = c = 7
a, b, c = 3, 4, "mary"
a, b = b, a # swap two variables
3.2 Checking and converting types
x = 10
print(type(x)) # <class 'int'>
x = "now a string" # allowed: the same name can hold another type
print(isinstance(x, str)) # True (Java: x instanceof String)
n = int("42") # Integer.parseInt("42")
f = float("3.5") # Double.parseDouble("3.5")
s = str(99) # String.valueOf(99)
3.3 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 (no overflow) |
| Float | double a = 7.25; | a = 7.25 | Floating point (64-bit, like Java double) |
| Complex | Not built in | a = 2.5J | Complex number |
Division is different: in Java, 7 / 2 with two ints is 3. In Python 3, / always returns a float; use // for integer (floor) division.
print(7 / 2) # 3.5
print(7 // 2) # 3
print(-7 // 2) # -4 (rounds down, not toward zero)
print(7 % 2) # 1
print(2 ** 10) # 1024
print(2 ** 100) # 1267650600228229401496703205376
4. Strings
Strings can use single quotes '...', double quotes "...", or triple quotes """...""" for multi-line text. Like in Java, strings are immutable.
| 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 |
| Substring | str.substring(0, 3) | str[0:3] |
| Split / join | str.split(",") / String.join("-", list) | str.split(",") / "-".join(list) |
| Contains | str.contains("py") | "py" in str |
| Upper / lower | toUpperCase() / toLowerCase() | upper() / lower() |
| Format | String.format("%s is %d", n, a) | f"{n} is {a}" (f-string) |
name = "Python"
print(name[0]) # P
print(name[-1]) # n (negative index counts from the end)
print(name[0:3]) # Pyt
print(name[::-1]) # nohtyP (reverse)
age = 30
print(f"Hello {name}, next year you are {age + 1}") # f-string: expressions inside {}
words = "a,b,c".split(",") # ['a', 'b', 'c']
print("-".join(words)) # a-b-c
print("py" in "python") # True
print(name.upper(), name.startswith("Py")) # PYTHON True
text = """Line one
Line two""" # multi-line string (like Java text blocks)
5. Boolean, None & Falsy Values
Every object in Python has a Boolean value. The following evaluate to False:
None(equivalent tonullin Java)False- The number
0(and0.0) - Empty collections:
"",(),[],{},set()
Note: in Javanull != false, but in PythonNonebehaves as falsy in a Boolean context. Booleans are writtenTrue/Falsewith a capital letter.
for v in [None, False, 0, "", [], {}, "0", [0]]:
print(repr(v), bool(v))
# None False / False False / 0 False / '' False / [] False / {} False
# '0' True / [0] True (non-empty = True, even if it contains 0)
items = []
if not items: # idiomatic empty check
print("Empty list")
result = None
if result is None: # use "is" for None (Java: result == null)
print("No result")
name = None
display = name or "Guest" # default value, similar to Optional.orElse
6. Data Structures (Collections)
6.1 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) |
| Insert at index | list.add(i, obj); | list.insert(i, obj) |
| Access | list.get(i); | list[i] |
| Remove | list.remove(obj); / list.remove(i); | list.remove(obj) / list.pop(i) |
| Length | list.size(); | len(list) |
| Contains | list.contains(obj); | obj in list |
| Sort | Collections.sort(list); | list.sort() / sorted(list) |
| Copy | list2 = list.clone(); | list2 = list[:] or list.copy() |
nums = [3, 14, 59, 26]
nums.append(5) # [3, 14, 59, 26, 5]
nums.insert(0, 1) # [1, 3, 14, 59, 26, 5]
nums.remove(59) # [1, 3, 14, 26, 5]
last = nums.pop() # last = 5, nums = [1, 3, 14, 26]
print(nums[1:3]) # [3, 14] (slice: index 1 up to, not including, 3)
nums.sort() # sorts in place
print(sorted(nums, reverse=True)) # [26, 14, 3, 1] (returns a new list)
a, b, *rest = [1, 2, 3, 4] # a=1, b=2, rest=[3, 4] (unpacking)
6.2 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, to return several values, or as a dictionary key.
A = () # empty tuple
B = (2, 71, 82, 8) # tuple of 4 numbers
C = (9, 5, 'peter') # heterogeneous tuple
D = ("Z", B, C) # nested tuple
single = (42,) # one element needs a trailing comma
x, y = (10, 20) # unpacking
# B[0] = 99 # TypeError: 'tuple' object does not support item assignment
6.3 Dictionary (like Java's HashMap)
A dictionary stores key: value pairs. Keys are unique and may be of different types. Since Python 3.7 a dict keeps insertion order (like Java's LinkedHashMap).
# 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!")
print(hotel_rooms.get('zoe', 0)) # 0 (default instead of KeyError)
for name, room in hotel_rooms.items(): # iterate key + value
print(name, room)
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() |
| Get values | map.values(); | my_dict.values() |
| Add / update | map.put(key, value); | my_dict[key] = value |
| Default if absent | map.getOrDefault(key, d); | my_dict.get(key, d) |
| Remove | map.remove(key); | my_dict.pop(key) |
| Size | map.size(); | len(my_dict) |
6.4 Set (like Java's HashSet)
A set holds unique, unordered elements. Note that {} creates an empty dict; use set() for an empty set.
s = {1, 2, 3, 3, 2} # {1, 2, 3} (duplicates removed)
s.add(4) # HashSet.add
s.discard(1) # HashSet.remove (no error if absent)
print(2 in s) # True
a, b = {1, 2, 3}, {3, 4}
print(a | b) # {1, 2, 3, 4} union
print(a & b) # {3} intersection
print(a - b) # {1, 2} difference
unique = list(set([5, 1, 5, 2, 1])) # remove duplicates from a list
6.5 Choosing the right collection
| Need | Java | Python |
|---|---|---|
| Ordered, changeable sequence | ArrayList | list |
| Fixed sequence | array / List.of() | tuple |
| Key → value lookup | HashMap | dict |
| Unique elements | HashSet | set |
| Queue / deque | ArrayDeque | collections.deque |
7. Operators & Precedence
7.1 Arithmetic
| Java | Python | Description |
|---|---|---|
| None | ** | Exponentiation |
- | - | Unary negation |
* | * | Multiplication |
/ | / | Division (Python: always float) |
None (int division by /) | // | Floor (integer) division |
% | % | Modulus |
+ / - | + / - | Addition / subtraction |
i++, i-- | i += 1, i -= 1 | Increment / decrement (++/-- do not exist in Python) |
7.2 Logical & bitwise
| Java | Python | Description |
|---|---|---|
! | not | Logical NOT |
& | & | Bitwise AND |
| | | | Bitwise OR |
^ | ^ | Bitwise XOR |
&& | and | Logical AND |
|| | or | Logical OR |
7.3 Comparison
| Java | Python | Description |
|---|---|---|
< / > | < / > | Less than / greater than |
<= / >= | <= / >= | Less or equal / greater or equal |
== | == | Value equality (like Java's .equals()) |
!= | != | Not equal |
== (ref) | is | Identity (same object in memory) |
x = 5
print(1 < x < 10) # True (chained comparison, not possible in Java)
a = [1, 2]
b = [1, 2]
print(a == b, a is b) # True False (equal values, different objects)
age = 20
status = "adult" if age >= 18 else "minor" # ternary: Java age >= 18 ? "adult" : "minor"
8. Conditionals
8.1 if - elif - else
Python writes else if as elif, and the condition needs no parentheses.
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!")
# Output: Case B: 20
8.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")
if not (skill1 == "java"):
print("Not java")
8.3 switch vs match (Python 3.10+)
| Language | Example |
|---|---|
| Java | |
| Python | |
Python's match has no fall-through, so no break is needed.
9. Looping
9.1 for loop with range()
In Python, for is usually combined with range(start, stop, step) to iterate over indices. stop is exclusive.
# 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) # 20 15 10 5
9.2 For-each over a collection
| Language | Example |
|---|---|
| Java | |
| Python | |
names = ["Anna", "Bob", "Linh"]
for i, name in enumerate(names): # index + value
print(i, name) # 0 Anna / 1 Bob / 2 Linh
ages = [30, 25, 28]
for name, age in zip(names, ages): # iterate two lists together
print(name, age)
9.3 while, break, continue, else
n = 0
while n < 5:
n += 1
if n == 2:
continue # skip this iteration
if n == 4:
break # leave the loop
print(n) # 1 3
for x in range(3):
pass
else:
print("no break happened") # loop-else: runs only if the loop was not broken
while True: # Python has no do-while: emulate it
answer = input("Continue? ")
if answer == "no":
break
9.4 List comprehension vs Streams
A comprehension builds a new collection in one readable line, replacing many stream().filter().map().collect() chains.
| Language | Example |
|---|---|
| Java | |
| Python | |
nums = [1, 2, 3, 4, 5, 6]
print([n * n for n in nums if n % 2 == 0]) # [4, 16, 36]
print({n: n * n for n in nums}) # {1: 1, 2: 4, 3: 9, ...} (dict comprehension)
print({n % 3 for n in nums}) # {0, 1, 2} (set comprehension)
print(sum(nums), max(nums), min(nums)) # 21 6 1
print(sorted(["bb", "a", "ccc"], key=len)) # ['a', 'bb', 'ccc']
10. Functions
Functions are defined with def. They do not need a return type, and they live outside classes. Python has no method overloading; use default and keyword arguments instead.
| Language | Example |
|---|---|
| Java | |
| Python | |
def greet(name, greeting="Hello"): # default argument
return f"{greeting}, {name}!"
print(greet("Anna")) # Hello, Anna!
print(greet("Bob", greeting="Hi")) # Hi, Bob! (keyword argument)
def stats(values):
return min(values), max(values), sum(values) / len(values) # returns a tuple
lo, hi, avg = stats([3, 5, 10]) # lo=3, hi=10, avg=6.0
def total(*args, **kwargs): # varargs (Java: int... args)
print(args) # (1, 2, 3)
print(kwargs) # {'unit': 'kg'}
return sum(args)
total(1, 2, 3, unit="kg")
square = lambda x: x * x # lambda (Java: x -> x * x)
print(list(map(square, [1, 2, 3]))) # [1, 4, 9]
11. Classes & Object-Oriented Programming
11.1 Defining a class and inheritance
class Animal:
species_count = 0 # class attribute (Java: static field)
def __init__(self, name): # constructor
self.name = name # instance attribute
Animal.species_count += 1
def speak(self):
return "..."
def __str__(self): # Java: toString()
return f"Animal({self.name})"
class Dog(Animal): # Java: class Dog extends Animal
def __init__(self, name, breed):
super().__init__(name) # call the parent constructor
self.breed = breed
def speak(self): # override
return "Woof!"
d = Dog("Rex", "Husky") # no "new" keyword
print(d) # Animal(Rex)
print(d.speak()) # Woof!
print(isinstance(d, Animal)) # True
11.2 self vs this
- In Java, an object refers to itself with
this, which can be omitted implicitly when accessing fields. - In Python,
selfplays the same role, but it is mandatory: it must be the first parameter of every instance method and must be used to create or access instance attributes.
| Language | Example |
|---|---|
| Java | |
| Python | |
11.3 Attributes, @property and access control
You can define attributes in __init__() and use the @property decorator to control access (the equivalent of a Java getter/setter):
class Car:
def __init__(self, color, model, year):
self.color = color
self.model = model
self.year = year
self._voltage = 12
@property
def voltage(self): # getter
return self._voltage
@voltage.setter
def voltage(self, value): # setter with validation
if value <= 0:
raise ValueError("voltage must be positive")
self._voltage = value
car = Car("red", "Model S", 2024)
print(car.voltage) # 12 (not car.getVoltage())
car.voltage = 24 # calls the setter
- Naming convention: a leading underscore (
_voltage) signals an internal/protected attribute. Two underscores (__x) trigger name mangling. Python has no realprivate; it relies on convention. @propertydecorator: works like a Java getter, letting you writecar.voltageinstead ofcar.getVoltage(), which is cleaner and more "Pythonic".
11.4 Static methods, class methods, abstract classes
from abc import ABC, abstractmethod
class MathUtil:
@staticmethod
def add(a, b): # Java: public static int add(...)
return a + b
@classmethod
def create(cls): # receives the class itself (cls)
return cls()
print(MathUtil.add(2, 3)) # 5
class Shape(ABC): # Java: abstract class / interface
@abstractmethod
def area(self): ...
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
print(Square(4).area()) # 16
# Shape() # TypeError: cannot instantiate abstract class
11.5 Multiple inheritance
Python supports multiple inheritance directly in classes; Java does not (it only allows implementing multiple interfaces). Python resolves method lookup with the MRO (Method Resolution Order).
class Flyer:
def move(self): return "fly"
class Swimmer:
def move(self): return "swim"
class Duck(Flyer, Swimmer): pass
print(Duck().move()) # fly (Flyer comes first in the MRO)
print([k.__name__ for k in Duck.__mro__]) # ['Duck', 'Flyer', 'Swimmer', 'object']
12. Exception Handling
Python uses try / except / else / finally and raise. There are no checked exceptions: you never have to declare throws.
| Language | Example |
|---|---|
| Java | |
| Python | |
class InsufficientFundsError(Exception): # custom exception
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(f"Need {amount - balance} more")
return balance - amount
try:
withdraw(100, 150)
except (InsufficientFundsError, TypeError) as e: # catch several types
print(e) # Need 50 more
Java try-with-resources corresponds to Python's with statement, which closes the resource automatically (see section 14).
13. Modules & Packages
Every .py file is a module; a folder with __init__.py is a package. Imports are statements you can write anywhere, and they are not tied to folder-matching class names as in Java.
| Language | Example |
|---|---|
| Java | |
| Python | |
import math
from datetime import date
print(math.sqrt(16)) # 4.0
print(date.today().year) # current year
# your own module: utils.py contains def hello(): ...
# from utils import hello
14. File I/O
The with statement guarantees the file is closed, even if an exception occurs.
| Language | Example |
|---|---|
| Java | |
| Python | |
import json
data = {"name": "Anna", "rooms": [215, 118]}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f) # write JSON (like Jackson/Gson)
with open("data.json", encoding="utf-8") as f:
print(json.load(f)["name"]) # Anna
15. Type Hints (optional)
Type hints document intent and help IDEs and tools like mypy, but Python does not enforce them at runtime.
def add(a: int, b: int) -> int:
return a + b
names: list[str] = ["Anna", "Bob"]
ages: dict[str, int] = {"Anna": 30}
maybe: str | None = None # like Optional<String>
print(add("a", "b")) # ab (no error at runtime!)
16. Common Pitfalls for Java Developers
- No
++/--: usei += 1. ==vsis:==compares values (like.equals()),iscompares identity (like Java==).- Integer division:
/returns a float; use//for integers. - Forgetting
selfin method definitions and attribute access. - Indentation errors: mixing tabs and spaces causes
IndentationError. {}is an empty dict, not an empty set.- No block scope: variables created inside
if/forremain visible afterwards. - No overloading: a second
defwith the same name replaces the first.
Mutable default arguments are created once and shared between calls:
def add_item(item, items=[]): # BAD
items.append(item)
return items
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] (surprise!)
def add_item_fixed(item, items=None): # GOOD
if items is None:
items = []
items.append(item)
return items
print(add_item_fixed(1)) # [1]
print(add_item_fixed(2)) # [2]
for i in range(3):
pass
print(i) # 2 (i is still accessible)
17. Quick Java → Python Mapping
| Java | Python |
|---|---|
System.out.println(x) | print(x) |
null | None |
this | self |
x instanceof Foo | isinstance(x, Foo) |
a.equals(b) / a == b (ref) | a == b / a is b |
Integer.parseInt(s) | int(s) |
String.format(...) | f"...{x}..." |
ArrayList / HashMap / HashSet | list / dict / set |
Optional.orElse(d) | x or d / x if x is not None else d |
toString() | __str__() |
equals() / hashCode() | __eq__() / __hash__() |
static | @staticmethod / @classmethod |
interface / abstract class | abc.ABC / typing.Protocol |
try-with-resources | with |
Arrays.sort(a) / Collections.sort(l) | l.sort() / sorted(l) |
StringBuilder | list.append(...) + "".join(list) |
stream().filter().map() | list comprehension |
Math.max(a, b) | max(a, b) |
final | UPPER_CASE convention |
Maven / Gradle | pip + venv |

I'm cheerful I found this blog! Every now and then, understudies need to psychologically the keys of beneficial artistic articles forming. Your information about this great post can turn into a reason for such individuals.
Trả lờiXóaServicenow Training in Hyderabad