In my previous article I touched on some of the basics of using operators in Python. While learning Python, I find myself comparing it with Java regularly. This has resulted in some confusion when it comes to the use of variables. I’ll show you an example of why that is.

In Python, you can create a variable and make it, let’s say, an integer. You can then call that same variable later in your code and make it a String.

name = "Darryl"
print(name) #it prints Darryl
name = 5
print(name) #it prints 5

This example works perfectly in Python. In Java however, it would result in an error. It’s quite a complicated issue. Let’s get into why that is.

Static Typing and Dynamic Typing

The difference can be found in how both programming languages handle typing (assigning a datatype to a viable). Java is what is called a “statically typed” or “strongly typed” programming language. This means that once a variable has been assigned a datatype, it can’t be changed. The datatypes get checked before run-time, resulting in an error before your code gets executed.

There is no real agreement on what “strongly typed” means. Although the most widely used definition in the professional literature is that in a “strongly typed” language, it is not possible for the programmer to work around the restrictions imposed by the type system. This term is almost always used to describe statically typed languages.

Static Typing and Dynamic Typing

Python is a dynamically typed language, which is the opposite. Python is also interpreted. This means that code is translated (into 1’s and 0’s) during execution. Java on the other hand, is compiled. In Java, code is translated before execution.

Since Python translates code during execution, it’s highly flexible about reassigning variables to different types. Just look at the example above. If you want to see how far you can push this flexibility, take a look at this example.

exampleVariable = 0

if exampleVariable == 0:
    print('Hi')
else:
    print("3" + 5)

Normally, the above example would result in an error upon execution. That’s because Python can’t concatenate a String to an integer. However, since the if-else statement will validate to True on the first condition (if), the second condition (else) is never executed. Thus, it won’t result in an error. This will cause an error in statically typed languages, however.

Wrapping up

This was a short write-up on the interesting, but still confusing, “typing” difference. The most important thing to take away is that Python gives you a bit more flexibility when programming.

Let me know if this was helpful or if you would like to see more of these types or articles in the future. As always, if you have questions or concerns, feel free to comment below. Lastly, make sure to share the article if you liked it!

There are currently no comments.

This site uses Akismet to reduce spam. Learn how your comment data is processed.