Python for C and Java Developers
Python Basics
A New Syntax
Coming from C or Java, the first thing you'll notice in Python is the lack of curly braces and semicolons. Python uses indentation to define blocks of code. What was a matter of style in C/Java is a strict rule here. This makes the code clean and readable by default.
For example, an if statement in Java requires braces to group the code inside it:
// Java example
int score = 85;
if (score > 80) {
System.out.println("Great score!");
System.out.println("Keep it up.");
}
In Python, you use a colon and indentation:
# Python equivalent
score = 85
if score > 80:
print("Great score!")
print("Keep it up.")
The standard is to use four spaces for each level of indentation. Any consistent number of spaces will work, but the official style guide recommends four.
No More Type Declarations
Python is dynamically typed, which means you don't need to declare a variable's type. A variable is just a name that refers to an object, and that object has a type. You can even reassign a variable to an object of a different type.
# In Java, the type is fixed:
# String message = "Hello";
# message = 101; // This would cause a compile error
# In Python, this is perfectly fine:
message = "Hello"
print(message)
message = 101
print(message)
This flexibility can speed up development, as you write less boilerplate code. The trade-off is that type errors, which a C or Java compiler would catch, might only appear at runtime in Python.
Powerful Built-in Collections
Python comes with powerful, easy-to-use data structures built right into the language. You'll find yourself using these constantly instead of implementing your own or importing complex libraries for basic tasks.
list
noun
An ordered, mutable collection of items. Lists can contain items of different types.
Lists are similar to Java's ArrayList or C++'s std::vector. They can grow and shrink dynamically.
# Creating and using a list
scores = [98, 87, 92, 75, 83]
# Access an element by index
print(scores[0]) # Output: 98
# Add a new item to the end
scores.append(95)
print(scores) # Output: [98, 87, 92, 75, 83, 95]
# Lists can mix types
mixed_list = ["Alice", 30, True]
A tuple is like a list, but it's immutable, meaning you can't change it after it's created. You define tuples with parentheses instead of square brackets. They're useful for data that shouldn't be modified, like coordinates.
# A tuple of coordinates
point = (10, 20)
# You can access elements like a list
print(point[0]) # Output: 10
# But you cannot change them
# point[0] = 15 # This would raise a TypeError
Finally, dictionaries are Python's implementation of hash maps or associative arrays. They store key-value pairs and provide fast lookups.
# A dictionary of student grades
student_grades = {"Alice": "A", "Bob": "C", "Charlie": "B+"}
# Access a value by its key
print(student_grades["Alice"]) # Output: A
# Add a new key-value pair
student_grades["David"] = "A-"
# Check if a key exists
if "Bob" in student_grades:
print("Bob's grade is:", student_grades["Bob"])
Control Flow, Python Style
Conditional logic in Python is straightforward. It uses if, elif (short for "else if"), and else.
grade = 85
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("Needs Improvement")
Loops are also a bit different. Python's for loop is more like a "for-each" loop in Java. It iterates directly over the items of a sequence, like a list or a string.
# Iterating over a list
students = ["Alice", "Bob", "Charlie"]
for student in students:
print("Hello,", student)
# To replicate a C-style for loop (e.g., for(i=0; i<5; i++))
# you use the range() function:
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
The while loop works just as you'd expect, executing a block of code as long as a condition is true.
count = 0
while count < 3:
print("Count is", count)
count += 1 # Note: Python does not have ++ or -- operators
That covers the core differences. With your background in C and Java, you can start writing simple Python scripts right away.