How to Approach Python From a Java Perspective
Tags: java, python, beginners, learning
Published: 2020-05-29 19:54:29

Right now I’m taking a break from sharing updates on the image-titler script and reflecting on teaching to respond to a request from a former student. [In one of my course evaluations](https://therenegadecoder.com/teach/reflecting-on-my-fifth-semester-of-teaching/), they asked me to write an article on how to approach Python as someone who knows Java. Naturally, I thought that would be a lot of fun, so here it is!

**In short, in order to approach Python from a Java perspective, I recommend learning how the two languages compare (e.g. compiled vs. interpreted, static vs. dynamic typing, etc.). Then, I recommend learning Python’s idioms, using those idioms, and writing about your experience. There’s no better way of learning than to dive in.**

Hopefully, this gives you a good overview of what to expect in this article. Keep reading for more details!

## Understanding My Expertise

Before we get started, I thought it might be helpful to share exactly why I’m qualified to write this article. If that’s not interesting to you, feel free to jump to the next section. Otherwise, here’s my story.

When I first learned to program, I was 18 and a freshman in college. At the time, I was taking an introductory Java course, so naturally Java became my first programming language.

Over the next four years, I picked up a language or two to get through some other courses. For instance, I learned C/C++ while on an internship—which I ended up using for an operating systems course as well as a graphics course. Around the same time, I also picked up C# for game development and MATLAB for simulation and modeling. In addition, I even messed around with more specialized languages like Verilog and the Arduino language (i.e. C-ish).

In all my years of college, I never once touched Python. That wasn’t until I was about a year into my first engineering job. At that point, I had largely stayed in the Java and C/C++ space. Suddenly, I was stuck picking up a brand new language.

Of course, if any of you have worked a full time job, you know how quickly you’re able to pick things up. As a result, I was able to wrap my head around the syntax in just a couple of weeks.

That said, the code I wrote wasn’t great. In general, I spent a lot of time thinking about how to organize the code the way a Java programmer would. For instance, I spent a lot of time trying to convert code into objects when that wasn’t always necessary. Likewise, I felt myself falling into the same sort of iterative looping mechanisms that I might use in Java.

Over time, I began to think of Python as its own language, separate from Java. However, this was a long process, so I figured I’d put together this article of approaches to help you out.

## What Differentiates Python From Java?

Typically, when a student asks me to teach them a little Python, I like to start by looking at what makes the languages different. That way, we get an idea of what we need to learn. As a result, this section will call out some of the main differences between the two languages. Then, we’ll take a look at how they’re similar.

### Compiled vs. Interpretted

Perhaps the biggest difference between Java and Python is the fact that one is compiled (Java) while the other is interpreted (Python). Basically, that means that one language has to be translated as a unit (Java) while the other can be translated on-the-fly (Python).

To illustrate this concept, I like to share a common introductory program, Hello World, in both languages:

```java
public class HelloWorld { 
  public static void main(String[] args) { 
    System.out.println("Hello, World!") 
  }
}
```

```python
print("Hello, World!")
```

Here, we can see that the Java version requires quite a bit of boilerplate. That’s because we’re dealing with a compiled programming language. As a result, there needs to be some structure to indicate where to begin executing the code (i.e. the main method).

On the flip side, Python, the interpreted language, only needs to call the `print()` function directly. After all, this command is assumed to be executed within a sequence of statements on-the-fly. In other words, there’s no need to provide an entry point.

Naturally, this makes Python a nice scripting language. Basically, that means we can write sequences of commands into a file to be executed as needed. For example, here’s a script that prints the current date and time:

```python
import datetime
print(datetime.datetime.now())
```

For this “script” to work in Java, we’d have to compile it first and run the binary. Unfortunately, that means we can’t really make any changes without compiling the program again.

On the other hand, Python is pretty quick to modify. For instance, here’s that same program but with an additional label:

```python
import datetime
print(f"The current date and time is {datetime.datetime.now()}")
```

How cool is that?

### Static vs. Dynamic Typing 

Another fundamental difference between Java and Python is how variables are typed. Specifically, Java is statically typed while Python is dynamically typed. In essence, this means that Java variables are type checked at compile time while Python variables are type checked at runtime.

To understand the difference, let’s once again take a look at some code snippets:

```java
public class FiveFactorial { 
  public static void main(String[] args) { 
    int total = 1; 
    for (int i = 1; i <= 5; i++) { 
      total *= i; 
    } 
    System.out.print(total); 
  }
}
```

```python
total = 1
for i in range(1, 6): 
  total *= i
print(total)
```

Here, the most obvious difference is that the variables in Java have to be explicitly typed. In other words, we have to say we want to store an integer before we can actually do that. On the flip side, Python types (aka [type hints](https://www.python.org/dev/peps/pep-0484/)) are not required, and I don’t believe they were formally included in the language until Python 3.5.

Of course, to avoid confusion, it’s possible to have a statically typed language that doesn’t require explicit typing (see Kotlin). That said, I think the lack of explicit types is the most jarring change of Java developers. Luckily, type hinting is available and encouraged. Here’s the same sample with type hints added:

```python
total: int = 1
i: int
for i in range(1, 6): 
  total *= i
print(total)
```

All this does is help you catch some bugs in editors like PyCharm. Type hints will not stop you from running code.

### Braces vs. Spaces

At this point, you’ve probably noticed, but one of the more jarring differences between Java and Python is how scope is defined. In Java, we define blocks using braces. Meanwhile, in Python, we define blocks using spaces. To me, this is an elegant way of expressing readability in the language syntax because it forces you to maintain consistent spacing.

Of course, there’s no point in chatting without an example. Let’s once again take a look at the factorial example:

```java
public class FiveFactorial { 
  public static void main(String[] args) { 
    int total = 1; 
    for (int i = 1; i <= 5; i++) { 
      total *= i; 
    } 
    System.out.print(total); 
  }
}
```

```python
total = 1
for i in range(1, 6): 
  total *= i
print(total)
```

In the Java example, we can see that there are three levels of nesting based on the three sets of braces. Of course, we also see that by the indentation, but that’s not strictly necessary:

```java
public class FiveFactorial {
public static void main(String[] args) {
int total = 1;
for (int i = 1; i <= 5; i++) { total *= i; }
System.out.print(total);
}
}
```

Here, we’ve decided to compress the loop to a single line. In addition, we’ve eliminated all indentation. Regardless, the compiler will be happy. On the other hand, your fellow developers (or your future self) will not be too happy with you.

Meanwhile, Python doesn’t really allow for this sort of restructuring of code. In fact, we’ll get a syntax error:

```python
total = 1 
for i in range(1, 6): 
total *= i
print(total)
```

If you try to run this, you’ll get the following error:

```python
SyntaxError: expected an indented block
```

Basically, [this means that the interpreter was expecting some sort of nested block](https://therenegadecoder.com/code/syntax-error-expected-an-indented-block/), but it didn’t find it. As a result, the program crashed.

At any rate, certainly there are other ways that Python and Java are different, but these cover the main difference from a beginner’s perspective. In the next section, we’ll take a look at how the languages are the same, so you can maximize the overlap.

## What Makes Java and Python Similar?

As promised, we’ll now take a look at how Java and Python are the same—or at least similar. You’d be surprised by how much overlap there actually is.

### Programming Paradigms

If you have a background in Java, you’ll be glad to know that Python is largely imperative in nature. Essentially, that means that both program languages leverage statements to update the program’s state.

If you’re not familiar with some of the other programming paradigms, this might not be the most useful information. That said, this means that you won’t really have to stretch your idea of what programming means when learning Python. If you’re already comfortable with the idea of expressions and statements, those concepts will continue to be useful in Python.

All that said, Java sort of binds you to the realm of Object-Oriented Programming (OOP). In Python, you’re not as restricted. You’re free to use the language in whatever paradigm you please which includes OOP and even functional programming (FP).

Also, **you can have more than one top-level class per file in Python**. It’s glorious!

### General Syntax

One of the nice things about Python is that it takes the syntax from languages like Java and cleans them up a bit. For example, the `while` loop in Python is much like its counterpart in Java, but it drops the parentheses and braces and picks up a colon:

```java
int i = 0;
while (i < 10) { 
  i++;
}
```

```python
i = 0
while i < 10: 
  i += 1
```

Meanwhile, conditionals follow the same sort of pattern:

```java
int i = 0;
if (i == 1) { 
  System.out.println("This is dead code, buddy!");
}
```

```python
i = 0
if i == 1: 
  print("This is dead code, buddy!")
```

Of course, you’ll have to get used to using `elif` over `else if`, but that shouldn’t take too long!

Likewise, many of the same operators are intact including all of the following:

- Arithmetic Operators: `+`, `-`, `*`, `%`
- Relational Operators: `<`, `<=`, `==`, `>=`, `>`

Of course, Python messes around with division by including both `/` and `//`. In addition, Python ditches the usual boolean operators and replaces them with their English counterparts: `and`, `or`, and `not`.

That said, I think you’ll find that it’s pretty easy to pick up Python given what you already know about the syntax of Java. Of course, the biggest change will be forgetting about braces and semicolons. But, you got this!

### The Standard Library

One of the great things about using Java is its standard library. For instance, if you need a data structure like a list, you’ll find several implemented for you in the standard library. Luckily, Python also has an excellent standard library, and it’s available right at your fingertips.

For example, do you need a queue for something? Here’s a queue code snippet from both standard libraries:

```java
import java.util.LinkedList; 
import java.util.Queue; 

public class QueueExample { 
  public static void main(String[] args) { 
    Queue<Integer> q = new LinkedList<Integer>(); 
    // Do queue things 
  }
}
```

```python
import queue
q = queue.Queue()
# Do queue things
```

Likewise, with the addition of a nice package manager like [pip](https://pypi.org/project/pip/), you’ll even be able to expand the standard library with 3rd party packages developed for just about everything. For instance, I’m using a few packages in [my image-titler script](https://github.com/TheRenegadeCoder/image-titler) including Pillow and Matplotlib.

## Approaching Python From a Java Perspective

Now that we’ve taken a moment to compare the two languages, I figured I could put together a list of tips to help you transition. Feel free to take these tips with a grain of salt; only you will be able decide what’s useful.

### Learn the Idioms

Python is an idiomatic language. Basically, that means there are certain ways of solving certain problems that are standard in the community. Typically, these idioms are outlined in the Python Enhancement Proposals ([PEPs](https://www.python.org/dev/peps/)), but you’ll tend to run into them in the wild first.

One of the common idioms I think of that’s just not possible in Java is the emptiness test for strings:

```java
if (s.length() == 0) { 
  // Do the thing
}
```

```python
if s: 
  # Do the thing
```

As a Java programmer, it might be tempting to check if a string is empty by testing for the length of the string. While that’s certainly possible in Python, [it’s typically more idiomatic to leverage the variable’s type flexibility](https://therenegadecoder.com/code/how-to-check-if-a-list-is-empty-in-python/). See, in Python, variables can evaluate to booleans under certain conditions. For example, an empty string is perceived as `False` while a string of any length is perceived as `True`.

Another common example of a Python idiom is looping. If we wanted to traverse an array, we might be tempted to use a for loop in Java. In Python, however, the traditional for loop doesn’t exist. Instead, Python programmers use what’s often referred to in Java as [the enhanced for loop or the for-each loop](https://therenegadecoder.com/code/how-to-write-a-loop-in-python/):

```java
int[] arr = {1, 2, 3}
for (int i = 0; i < arr.length; i++) { 
  // Do the thing
}
```

```python
arr = [1, 2, 3]
for item in arr: 
  # Do the thing
```

If for some reason you need the indices, you’ll have to use the `enumerate()` function.

Unfortunately, there are quite a few idioms you’ll have to learn in Python. That said, your code won’t be bad if you don’t use idioms; it’ll just be a little slower and less readable.

If you’re interesting in exploring some idioms, I actually write about them all the time. In fact, [I have an entire series dedicated to solving common problems in Python](https://therenegadecoder.com/series/how-to-python/). Almost every article features a clean idiomatic solution.

### Use the Language

One of the less appetizing pieces of advice is **use the language**. After all, you can study all day, but until you actually try to solve your own problems, you’ll never really know the language.

That said, I figured I’d get you started by curating a little list of Python projects you can try:

- [How to Make an Instagram Bot With Python and InstaPy](https://realpython.com/instagram-bot-python-instapy/)
- [How to Make a Twitter Bot in Python With Tweepy](https://realpython.com/twitter-bot-python-tweepy/)
- [Programming Projects for Advanced Beginners #2: Game of Life](https://robertheaton.com/2018/07/20/project-2-game-of-life/)
- [Programming Projects for Advanced Beginners #4: Photomosaics](https://robertheaton.com/2018/11/03/programming-project-4-photomosaics/)
- [Mining Twitter Data with Python (Part 1: Collecting data)](https://marcobonzanini.com/2015/03/02/mining-twitter-data-with-python-part-1/)

Keep in mind that none of these projects are mine, so I didn’t thoroughly vet them or anything. That said, I thought the titles were enticing and perhaps a good place for you to start (although maybe too difficult for a true beginner).

If you don’t like any of these options, you can always come up with your own. After all, you already know Java, so maybe you can rewrite some of your old projects in Python.

### Write About What You’ve Learned

One of the quickest ways to assess your learning is to explain your understanding. If you can articulate exactly why something works, you’ll reinforce the learning process.

To make this less scary, you can try jotting down the learning process in a notebook. Or, if you want to take your learning to the next level, you can write up a quick blog post on a site like [dev.to](https://dev.to/). If done right, you might be able to help out beginners just like yourself.

If you’re worried about rehashing the same old concepts on the internet, don’t be! I don’t think there’s any shame in writing content that already exists on the internet because it serves to reinforce your own learning. Likewise, we could all benefit from another perspective.

## Start Coding!

At this point, there’s not much else for me to say, so let me summarize. First, when learning Python, it’s important to compare and contrast Python with the language you already know, Java. In terms of differences, I identified three:

- **Python is interpreted** while Java is compiled
- **Python is dynamically typed** while Java is statically typed
- **Python uses spaces for code blocks** which Java uses braces

Naturally, there are probably thousands of differences, but these were the big three for me.

On the flip side, there Python is similar to Java in a lot of ways. For the purposes of brevity, I picked three:

- **Both Java and Python share the imperative programming paradigm**
- **Both Java and Python share general syntactic elements like loops and conditionals**
- **Both Java and Python share the idea of a vast standard library**

Once we compared an contrasted the languages, I shared three tips to help you through the transition:

- **Learn the Python idioms**
- **Use Python to build projects**
- **Write about everything you’ve learned**

Hopefully, these 2500+ words give you a decent starting point on your transition. As someone who had to go through a similar transition, I wish you the best of luck and keep grinding!

If you enjoy this kind of content, I’d appreciate it if you showed the site some love by checking out [my list of ways to grow the site](https://therenegadecoder.com/blog/ways-you-can-help-grow-the-renegade-coder/). For instance, that post will point you to my mailing list as well as my YouTube channel and Patreon. Every little bit helps!

While you’re here, here’s a list of related posts:

- [How to Complete a Programming Project from Scratch](https://therenegadecoder.com/code/how-to-complete-a-programming-project-from-scratch/)
- [Yet Another Way to Learn Recursion](https://therenegadecoder.com/code/yet-another-way-to-learn-recursion/)

Thanks again for hanging out! I appreciate it.