This post is part of a series that will teach you to use Python if you come from Java. I highly recommend you start from here if you don’t know o only has a little bit of Python knowledge. Let’s begin.
This is very interesting topic is the easy way to start with Python if you come from Java is knowing how the Python files are structured.
The structure of files in Java and Python differs significantly because of their distinct programming paradigms, syntax, and organizational conventions. Here’s a breakdown of the differences in terms of file structure between Java and Python:

File Extension
- Java
- In Java the files are saved with the
.javaextension. The file name typically matches the class name defined inside it for example, the fileMyClass.javawill contain a public class called MyClass.
- In Java the files are saved with the
- Python
- In Python the files are saved with the
.pyextension. There’s no strict requirement for the file name to match any class or function inside the file. However, there are some recommendations and best practices to follow. File names should be clear and should indicate their purpose or content. This improves readability, especially when working in larger projects where multiple modules or files are involved. For example, if your file contains utility functions for handling dates, a good name might bedate_utils.pyordate_helpers.py.
- In Python the files are saved with the

File Structure & Class Requirements
- Java:
- Class-centric, Java is an object-oriented language where every piece of code must reside inside a class. Even the entry point of the program (the
mainmethod) must be inside a class. - A Java file typically contains one public class that matches the file name, and it may also include other classes or interfaces that are not public.
- Example:
- Each Java file can only have one public class. The additional classes in the same file must not be marked as
public.
- Class-centric, Java is an object-oriented language where every piece of code must reside inside a class. Even the entry point of the program (the
//MyClass.java
public class MyClass {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
- Python
- Script-oriented, Python is more flexible. You don’t need to organize code inside a class unless you’re following object-oriented principles. A Python file can contain classes, functions, variables, or just plain executable code.
- Python allows for a mix of different constructs, and code can be executed directly without requiring a class or
mainmethod. - You can execute code outside of any class or function, which is often used for scripting or small programs.
Python File Containing Executable Code (Script); the main method in Java. Usually this type of file is used for scripts or run a program.
# my_script.py
def say_hello():
print("Hello, Python!")
if __name__ == "__main__":
say_hello()
Python File Containing Class, In Python is possible to have an structure for classes like Java.
# car.py
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def start_engine(self):
print(f"{self.make} {self.model}'s engine started!")
def stop_engine(self):
print(f"{self.make} {self.model}'s engine stopped!")
class ElectricCar(Car):
def __init__(self, make, model, year, battery_size):
super().__init__(make, model, year)
self.battery_size = battery_size
def charge_battery(self):
print(f"Charging the battery of the {self.make} {self.model}.")
Python File Containing Functions, this file only contains functions that can be reusable on other Python files.
# math_operations.py
def add(a, b):
"""Returns the sum of a and b."""
return a + b
def subtract(a, b):
"""Returns the difference between a and b."""
return a - b
def multiply(a, b):
"""Returns the product of a and b."""
return a * b
def divide(a, b):
"""Returns the division of a by b, handles division by zero."""
if b == 0:
raise ValueError("Cannot divide by zero!")
return a / b
Python File Containing Variables, this is similar to a Java class that defines constants (the static final variables). However, there are some important differences between how Python and Java handle constants.
# config.py
# Configuration settings for the application
DATABASE_URL = "localhost:5432/mydatabase"
API_KEY = "12345abcde"
MAX_CONNECTIONS = 100
TIMEOUT = 30
# These variables can be imported and used in other files.
Python doesn’t have built-in support for true constants like Java’s final. The constants in Python are in all-uppercase to indicate they shouldn’t be changed, but technically, they can still be modified at runtime because Python variables are mutable.
Remember in Java modifying final variable will result in a compile-time error.
Python File Containing a Mix of Classes, Functions, and Variables. Finally we can mix all the different “types of files” to develop a Python’s programs. Just one thing to remind you should structure their code in a modular, reusable, and maintainable way.
# my_program.py
# Configuration variables (often treated like constants)
APP_NAME = "Task Manager"
VERSION = "1.0"
# Function definitions
def greet_user(name):
print(f"Hello, {name}! Welcome to {APP_NAME} v{VERSION}.")
def calculate_sum(a, b):
return a + b
# Class definitions
class Task:
def __init__(self, title, description):
self.title = title
self.description = description
def display(self):
print(f"Task: {self.title}\nDescription: {self.description}")
# Main program logic
if __name__ == "__main__":
greet_user("Alice")
task1 = Task("Buy groceries", "Milk, Bread, Eggs")
task1.display()
result = calculate_sum(5, 10)
print(f"The sum of 5 and 10 is {result}.")

Entry Point
- Java
- The entry point is always the
mainmethod, which must be placed inside a class. - The JVM looks for this method to start the program.
- This method has the signature:
- The entry point is always the
public static void main(String[] args)
- Python
- The entry point is determined by the script’s contents. The special block
if __name__ == "__main__":is commonly used to specify code that should run when the script is executed directly (rather than when it is imported as a module).
- The entry point is determined by the script’s contents. The special block
block if __name__ == "__main__":
There is no need for a main method, though you can define your own function called main() if desired.
# my_script.py
# Function definitions
def greet_user(name):
"""Greet the user by name."""
print(f"Hello, {name}! Welcome to the program.")
def calculate_sum(a, b):
"""Return the sum of two numbers."""
return a + b
def main():
"""Main function that drives the program logic."""
# Gather user input
user_name = input("Enter your name: ")
greet_user(user_name)
# Calculate and display a sum
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = calculate_sum(a, b)
print(f"The sum of {a} and {b} is {result}.")
# Entry point of the script
if __name__ == "__main__":
main() # Call the main function if the script is executed directly

Package Structure & Imports
- Java:
- Java has a strict package system. Files must be organized into directories that represent their packages.
- At the top of the file, the package must be declared, and imports are handled explicitly using the
importkeyword for classes or packages from other files. - Example:
package com.example.myapp;
import java.util.List;
public class MyClass {
// code
}
- Python:
- Python uses a more flexible module system where any
.pyfile can be a module. - Files are organized into directories that can optionally contain an
__init__.pyfile (which makes the directory a package). Imports are managed using theimportkeyword, and modules can be imported based on their file or package names. - Example:
- Python uses a more flexible module system where any
import os
from mymodule import myfunction
def my_function():
pass

Compilation vs Interpretation
- Java:
- Java files need to be compiled into bytecode using the
javaccompiler. The compiled.classfiles can then be run on the Java Virtual Machine (JVM). - The process involves:
- Writing code in a
.javafile. - Compiling it to bytecode with
javac MyClass.java. - Running the bytecode with
java MyClass.
- Writing code in a
- Java files need to be compiled into bytecode using the
- Python:
- Python is an interpreted language. The Python interpreter executes the
.pyfiles directly. - There is no separate compilation step. The
.pyfiles are executed by callingpython my_script.py. - Python does generate
.pycfiles (compiled bytecode) for faster execution when importing modules, but this is handled automatically.
- Python is an interpreted language. The Python interpreter executes the

Main Method & Executable Code Location
- Java:
- All executable code must reside inside methods within a class, typically starting from the
mainmethod.
- All executable code must reside inside methods within a class, typically starting from the
- Python:
- Python can execute code directly within the file without the need for it to be inside a class or function, allowing for more scripting flexibility.
# direct_execution.py
# Importing necessary modules
import datetime
# Print a greeting message
print("Welcome to the Direct Execution Example!")
# Get the current date and time
current_time = datetime.datetime.now()
print(f"Current date and time: {current_time}")
# Perform a simple calculation
a = 10
b = 5
sum_result = a + b
print(f"The sum of {a} and {b} is {sum_result}.")
# Loop through a range of numbers and print them
print("Counting from 1 to 5:")
for i in range(1, 6):
print(i)
# Conditional execution example
user_input = input("Type 'exit' to close the program: ")
if user_input.lower() == 'exit':
print("Exiting the program.")
else:
print("You typed:", user_input)
When you run this script, you will see the following output:
Welcome to the Direct Execution Example!
Current date and time: 2024-09-26 12:34:56.789012
The sum of 10 and 5 is 15.
Counting from 1 to 5:
1
2
3
4
5
Type 'exit' to close the program: hello
You typed: hello

File Organization and naming Conventions
- Java:
- In Java the files are strictly named after the public class they contain. If you have a public class called Cat the file must be
Cat.class. - Naming Convention: In Java the classes typically use PascalCase (e.g.,
MyClass.java).
- In Java the files are strictly named after the public class they contain. If you have a public class called Cat the file must be
- Python:
- In Python the files can be named freely, though it’s a good practice to use descriptive names related to the functionality of the script or module.
- Naming Convention: Python typically uses snake_case for file names (e.g.,
my_script.py).

Summary of Key Differences
The below table shows the key differences between the Python and Java structure files.
| Feature | Java | Python |
|---|---|---|
| File Extension | .java | .py |
| Class Requirement | Every file must contain a class | Classes are optional |
| Entry Point | public static void main(String[] args) | if __name__ == "__main__": block |
| Package/Module Structure | Strict package structure with package keyword | Flexible module/package system |
| Imports | import for specific classes or packages | import for modules or functions |
| Compilation | Must be compiled to bytecode (.class files) | Directly interpreted (.py files) |
| Executable Code Location | Only inside methods (within classes) | Can be outside classes or functions |
| Naming Conventions | PascalCase for class names | snake_case for file names |
In conclusion. Java’s file structure is more rigid, with strict class and method requirements. Whereas Python offers more flexibility, allowing for a mix of scripts, classes, and functions in the same file.
Now, that you know the key differences between the file structures, you have no excuses not to start with Python programming if you come from Java.
Happy Learning!!!


Leave a comment