This tutorial is a very basic overview of Python for users that have Java experience.
Welcome to Python! This tutorial is an overview of some basic Python commands for people that have previously coded in Java. It is far from an exhaustive list of differences, but if you are familiar with Java, you should get enough to get up and running.
At a high-level, Python is more of a blend between object-oriented programming and functional programming, while Java is really a pure object-oriented programming language. What does that mean? In Java, all of your code is contained inside a class and executed within methods/functions. Python still has classes and functions, but it can also execute code outside of these structures.
Here is a Java example of “Hello World”. Notice how the one line of code that we want to print needs to be inside a method which is inside a class.
In Python, we can execute that line of code independently. Here is an example with a few basic print statements in Python.
Unlike Java, we don’t need to declare a variable type to use them. We just start using it and Python figures out the type.
Example:
Since Python needs to assume a certain data type, sometimes it assumes incorrectly and we need to cast that variable to a specific type. A good example of this is user input. While user input is much easier in Python, all input is assumed to be a string unless we cast it otherwise.
Let’s take a look at an example:
Like nearly all programming languages, control statements such as loops and conditional statements form a key part of the language. Loops and conditional statements work the same way in Python, but they have a slightly different syntax. Most notably different is that Python uses indentation to denote a coding block versus Java’s use of curly bracket { }
.
Here is an example of Python and Java:
Notice how the if statement is indented. As long as you have the same indentation level, Python will continue to only execute that code as part of the if statement. Once you back out, you are no longer part of the if statement block.
The same is true for loops. Any statement in the loop needs to be indented.
Take a look at the following example to see if/else if statements and loops in action.
Now it is your turn to try. See if you can use the examples above to write a Python program that asks the user for two integers and then prints out if the first number is divisible by the second number. (Hint: The modulus operator in Python works exactly the same as Java.)