8 minutes
Learning Python as a Java developer - 2/
This is the second part of the series “Learning Python as a Java developer”. If you are interested in the other ones, check the links below:
Learning resources
Before going into the details of the second part, I want to enumerate some of the resources I used and I am still using to learn/brush up on Python, beside the ones I mentioned in the first part:
- CS50’s Introduction to Programming with Python, 2022 - free/payed
- Practical Python Programming, a course by David Beazley - free. Note: search for content made by David Beazley, he is a great!
- OpenEDG Python courses - free
- Hyperskill Python tracks - payed
- Educative.io Python courses - payed
- The Python Tutorial - free
- Real Python - free/payed
- Learn X in Y minutes - free
- Working on Python projects
There are a lot of other resources out there, each one with its own pros and cons. I suggest you to try some of them and find the one that fits you the best. Google is your friend!
First impressions … cnt’d
In the first part I talked about some of the first impressions I had when I started learning Python. In this part I want to talk about some other ones.
Python is a dynamically typed language, so you don’t have to declare the type of a variable. For example, if you have a variable a
and you assign it to a value, let’s say 1
, you can’t know the type of a
just by looking at the code. You have to run it and see what happens. However, PEP 484 introduced type hints, so you can add type hints to your code and have a better understanding of what is going on. For example, you can do something like this:
a: int = 1
You would need a tool to check the type hints, like mypy. However, you don’t have to use type hints, they are optional.
Python is also an interpreted language, so you don’t have to compile it, as is the case of Java. This is great, because you can run your code as soon as you write it. On the other side, you don’t have a compiler to tell you if you are doing something wrong. You have to run your code and see what happens.
An interpreted language is also slower than a compiled one. However, Python is not that slow, because it is implemented in C, see CPython. If you need to speed up your code, you can use a tool like Cython. To add to the confusion, there is also Jython, an implementation of Python in Java.
Another thing that I found a bit confusing is the fact that you can assign a value to a variable without declaring it. For example, you can do something like this:
a = 1
b = 2
c = a + b
This is perfectly fine, but if you are coming from a language like Java, you are used to declare the variables before using them.
Knowing another programming language can be a double-edged sword. On one side, you can leverage your knowledge to learn the new language faster. On the other side, you can be confused by the differences between the two languages.
Once you get the hang of it, Python is a great language to work with. It is easy to learn, it has a lot of libraries and it is used in a lot of different fields, from web development to data science. It is also a great language to teach programming.
Another thing worth mentioning is that Python is a multi-paradigm language. You can use it in an imperative, functional or object-oriented way. You can also mix the paradigms. Much the same as Java, but with a simpler syntax and less typing.
When writing Java code I usually look at the internal implementation of the classes and methods I am using. This is a great way to learn how things work under the hood. However, in Python this is not always possible, because the implementation is written in C. You can still look at the source code, but it is not as easy as in Java.
Moving past the syntax and the features you would expect to have in any language, there are some things that are specific to Python. For example, Python has list comprehensions, which are a great way to create lists. You can do something like this:
digits = [x for x in range(10)]
This is equivalent to:
digits = []
for x in range(10):
digits.append(x)
Besides being shorter, list comprehensions are also faster than the equivalent for
loop. Besides list comprehensions, there are also dictionary and set comprehensions.
Generators are another great feature of Python. They are a way to create iterators. You can do something like this:
digits_gen_exp = (x for x in range(10))
This is equivalent to:
def digits_gen_fun():
for x in range(10):
yield x
The difference between the two is that the first one is a generator expression, while the second one is a generator function. The generator expression is shorter and faster than the generator function.
Once you got yourself a generator, you can do a lot of things with it. You can iterate over it:
for digit in digits_gen_exp:
print(digit)
for digit in digits_gen_fun():
print(digit)
You can create other data structures from it:
d1 = list(digits_gen_exp)
d2 = set(digits_gen_fun())
d3 = dict(zip(digits_gen_exp, digits_gen_fun()))
More advanced topics include decorators, context managers and metaclasses. The equivalent in Java would be annotations, try-with-resources and reflection.
Additionally, there are some magic methods that you can implement to customize the behavior of your classes. For example, you can implement the __add__
method to customize the behavior of the +
operator. Overloading operators in not something you can do in Java.
When it comes to doing more at once or doing things faster, Python has the event loop and the asyncio module, the multiprocessing module and the threading module. In Java you have the ExecutorService and the CompletableFuture, among other things.
Python also has modules and packages. A module is a file containing Python code. A package is a directory containing Python code. You can import modules and packages in your code. You can also create your own modules and packages. In Java you have packages and JAR files. The term module is used in Java 9 and later and differs from the Python one.
Python has a lot of built-in functions and built-in types. You can find a list of them here and here. You can also create your own functions and types, much the same as in Java where you have methods and classes.
Both languages have a lot of out-of-the-box functionality provided by the language itself and their respective ecosystems bring a lot more to the table. In Python I find it sometimes difficult to decide on which package to use, because there are a lot of them and there is no bulletproof way to choose one. I haven’t had this feeling in Java.
Handling exceptions in Python is similar to handling them in Java. You have the try
and except
keywords. You can also use the finally
keyword to execute some code after the try
block, regardless of whether an exception was thrown or not. The else
clause is also available, to execute some code if no exception was thrown. This last bit is not available in Java. You can also create your own exceptions, much the same as in Java.
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
In Python you raise exceptions with the raise
keyword, while in Java you throw them with the throw
keyword.
Should you be interested into Machine Learning or Data Science, Python is a great language to learn. There are a lot of libraries available, like NumPy, SciPy, Pandas, Matplotlib and TensorFlow. You can also use Jupyter Notebooks to create interactive documents. Java has some libraries for Machine Learning and Data Science, but they are not as popular as the Python ones.
Python is also a great language for web development. You can use Django or Flask to create web applications. You can also use PyQt or PySide to create desktop applications. Java has Spring for web development and JavaFX for desktop applications.
Another fairly new addition to the Python ecosystem is PyScript which allows you to write Python code and compile it to JavaScript. This is similar to GraalVM which allows you to write Java code and compile it to JavaScript.
Python is also a great language for scripting. You can use it to automate tasks on your computer. You can also use it to create command line interfaces for your applications. Java is not that great for scripting, but you can still use it for that.
In future posts I will try to focus on a specific topic and compare how it is done in Java and Python. This can serve as a go-to guide for people working with both languages, including myself.
Happy coding!