Python Primer for Java Developers
I took these notes while ramping up on Python, to be able to contribute to a few Github projects, deploy AWS Lambdas quicker, and use boto3 for quite a few projects. Plus I find it a very light, frictionless, quick and easy scripting language to have in the arsenal. This information can be particularly useful to anyone who is coming from a Java background, and wants to compare and contrast the two languages’ basic constructs and syntax.
Setup
I recommend using Atom, and installing the Script package. Once done, make sure you download and install Python 3.x. For OSX, this will also install pip3, which is the Python Package Manager. I noticed that on Ubuntu Xenial I had to install pip3 via sudo apt install python3-pip.
There is a (closed) issue logged for Atom to work with Python 3 on OSX, but none of it worked for me except using shebang. Just put #!/usr/local/bin/python3 as the first line in the file which you’ll write code in.
To write code, create a new file in Atom, and you’re good to go. On OSX use ⌘+i to execute.
I’d also recommend checking out the Python Domain on HackerRank for hands-on practice.
That said, lets get started.
Comments
Java
// This is a comment
/*
This is a
multi line comment
*/
Python
# This is a comment
Variables
Java
String name = "Name";
int age = 42;
boolean completed = false;
char c = 'A';
float f = 0.0034;
//conversions
Integer.parseInt("1234");
Object.toString();
Long.parseLong("1024");
Boolean.parseBoolean("false");
//casting
(int) n;
(float) f;
(long) l;
(Object) o;
Python
name = "Name"
age = 42
completed = False
c = 'A'
f = 0.0034
# casting
int(value)
str(value)
float(value)
bool(value) # Will only return false for an empty string or an int=0
list_of_ints = [int(i) for i in list_of_strings]
Hello World
Java
//With newline
System.out.println("Hello World!");
//Without newline
System.out.print("Hello World!");
Python
# With newline
print("Hello World");
# Without newline
print("Hello World", end='')
Read Input
Java
Scanner scanner = new Scanner(System.in);
System.out.println("Enter name");
String name = scanner.next();
System.out.println("Enter age");
int age = scanner.nextInt();
System.out.println("Name is " + name + " and age is " + age);
Python
name = input("Enter name\n")
age = int(input("Enter age\n"))
print("Name is ", name ," and age is ", age)
Operators
Java
int i = 5;
int j = 3;
System.out.println("Sum : " + i+j);
System.out.println("Diff : " + (i-j));
System.out.println("Product : " + i*j);
System.out.println("Modulo : " + i%j);
System.out.println("Power : " + Math.pow(i,j));
System.out.println("Floor Division : " + i/j);
System.out.println("Float Division : " + (float)i/j);
Python
i = 5;
j = 3;
print("Sum : ", i+j)
print("Diff : " , i-j)
print("Product : " , i*j)
print("Modulo : " , i%j)
print("Floor Division : " , i//j)
print("Float Division : " , i/j)
If-then-else
We use the if-then-else exercise from Hackerrank as an example.
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5 , print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20 , print Not Weird
Java
if(n%2==1) System.out.println("Weird");
else if(n%2 == 0 && n >=2 && n <= 5)
System.out.println("Not Weird");
else if(n%2 == 0 && n >= 6 && n <= 20)
System.out.println("Weird");
else if(n%2 == 0 && n > 20)
System.out.println("Not Weird");
Python
if n%2 == 1 :
print("Weird")
elif n%2==0 and n >=2 and n <=5 :
print("Not Weird")
elif n%2==0 and n >=6 and n <=20 :
print("Weird")
elif n%2==0 and n > 20 :
print("Not Weird")
Switch
Java
switch(dayOfWeek){
case 0 :
case 6 :
System.out.println("Weekend");
break;
case 5 :
System.out.println("TGIF");
break;
default:
System.out.println("Weekday");
}
Python
Python does not really have a switch/case. if/elif/else are used instead.
if n == 0 or n == 6 :
print("Weekend")
elif n == 5 :
print("TGIF")
else :
print("Weekday")
For Loop
Java
for(int i=0;i<5;i++){
System.out.println(i);
}
for(char c : "Manish".toCharArray()){
System.out.println(c);
}
Python
for n in range(5) :
print(n)
for c in "Manish" :
print(c)
Python also supports Scala style For Comprehensions, which are called Generators. There is a subtle difference though, as you can see below.
def square(n):
for i in range(n):
yield i**2
for i in square(10):
print(i)
While Loop
Java
int n = 0;
while(true){
++n;
System.out.println(n);
if(n==20) {
break;
}
}
System.out.println("Loop Broke with n = " + n);
Python
n = 0
while True :
n = n + 1
print(n)
if n==20 :
break
print("Loop broke with n = ",n)
Exceptions and Errors
Java
try{
doSomething();
}catch(SomeException e){
//do something
}catch(SomeOtherException e){
//do something else
}finally{
//always executes
}
Python
try:
assert(1==2) # This will cause an error
except AssertionError:
print("Caught Assertion Exception")
except : # catch all exceptions
print("Caught unknown exception")
else: # happy path
print("No exceptions raised")
finally: # will execute regardless of exceptions or happy path
print("Done with the assertion")
Functions
Java
public int add (int x, int y){
return x+y;
}
System.out.println(add(1,2));
Python
def add(x, y):
return x+y # If return is skipped, the method returns a None
print(add(1,2))
# Can be called with named arguments
print(add(x=5,y=7)) # Will print 12
# Can take default arguments too
def add(x, y=2):
return x+y
print(add(5)) # Will return 7
Collections - Lists
There are technically no Arrays in Python, just Lists. Also, they may contain many types of elements, but in practice it is just one type. Python Lists are mutable.
Java
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add(3,"D");
Collections.sort(list); //in place sort
list.remove("C"); //remove the first occurrence of "C"
list.remove(2); //remove object at the index 2
Collections.reverse(list); //reverse the list
int n = list.indexOf("A"); //return the index of first occurrence of "A"
List<String> list1 = new ArrayList<>();
list1.add("E");
list1.add("F");
list.addAll(list1); //add list1 elements to list at the end
int size = list.size(); //size of the list
Python
list = [] # create a new list
list.append("A") # add to the end
list.append("B")
list.append("C")
list.insert(3,"D") # insert at an index
sorted_list = sorted(list) # returns a new, sorted list
list.sort() # in place sort
list.remove("C") # remove first occurrence of "C"
popped = list.pop(2) # return and remove the item at index 2
list.reverse() # reverse the list
a = list.index("A") # return index of "A"
list += ["E","F"] # add a list with E and F to the end of this list
size = len(list) # size of the list
Collections - Sets
Java
Set<String> set1 = new HashSet<>();
set1.add("A");
set1.add("B");
set1.add("C");
Set<String> set2 = new HashSet<>();
set2.add("C");
set2.add("D");
set2.add("E");
//intersection
Set<String> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
//union
Set<String> union = new HashSet<>(set1);
union.addAll(set2);
Python
set_of_words1 = set() # create a new set. Note that we do not use {}, as that is for the dict
set_of_words1.add("The") # add values
set_of_words1.add("A")
set_of_words1.add("Boat")
print("Boat" in set_of_words1) # True
set_of_words2 = {"Anchor","A","Coast"} # create another set and populate it
print(set_of_words1.intersection(set_of_words2)) # intersection
print(set_of_words1.union(set_of_words2)) # union
for value in set_of_words2 : # all values
print(value)
Collections - Tuples
There are no Tuples in Java. A tuple is an immutable collection of values.
Python
words = ("Good", "Morning") # or words = "Good", "Morning"
print("Good" in words) # True
print(hash(words)) # This is what makes the tuples so special - they are hashable
a,b = words # or a,b = "Good", "Morning"
print(a) # Good
print(b) # Morning
print(len(words)) # 2
Collections - Maps
Maps are called dicts or Dictionaries in Python.
Java
Map<String,Integer> wordCount = new HashMap<>();
wordCount.put("anchor",2);
wordCount.put("dock",3);
wordCount.put("the",10);
wordCount.put("a",8);
wordCount.put("boat",1);
int the = wordCount.get("the");
Set<String> keys = wordCount.keySet();
Collection<Integer> values = wordCount.values();
boolean exists = wordCount.containsKey("a");
Set<Map.Entry<String,Integer>> entries = wordCount.entrySet();
int foo = wordCount.get("foo"); //throws NullPointerException
Python
wordcount_map = {} # create a new, empty dict
wordcount_map = {"anchor":2, "dock":3} # create a new dict and add key-values
wordcount_map["the"] = 10 # add keys and values
wordcount_map["a"] = 8
wordcount_map["boat"] = 1
print(wordcount_map["the"]) # value of a key
print(wordcount_map.keys()) # List of keys
print(wordcount_map.values()) # List of values
print("a" in wordcount_map) # True
print(wordcount_map.items()) #prints tuples of key-value pairs
print(wordcount_map["foo"]) # throws a KeyError
Classes and Objects
Java
public class MyClass{
List<String> words;
public MyClass(){
words = new ArrayList<>();
words.add("baz");
}
public MyClass(List<String> data){
words = data;
}
public int count(){
return words.size();
}
}
//Usage
MyClass myClass = new MyClass();
System.out.println(myClass.count()); // will print 1
List<String> data = new ArrayList<String>();
data.add("foo");
data.add("bar");
myClass = new MyClass(data);
System.out.println(myClass.count()); // will print 2
Python
For more details like member visibility and multiple inheritance, etc., see here
class MyClass:
words = []
def __init__(self, data=["baz"]): # think of this as a Constructor in Java
self.words = data
def count(self): # think of self as "this" in Java
return len(self.words)
# Usage
clz = MyClass()
print(clz.count()) # will print 1
print(clz.words) # will print ['baz']
clz = MyClass(["foo","bar"])
print(clz.count()) # will print 2
print(clz.words) # will print ['foo','bar']
Reading and Writing Files
Java
Here is an example with Apache Commons FileUtils
File file = FileUtils.getFile("/tmp/foo.txt");
//Read line by line
LineIterator it = FileUtils.lineIterator(file);
while (it.hasNext()) {
System.out.println(it.next());
}
//Read the entire file in memory
String contents = FileUtils.readFileToString(file);
//Write to a file
File file = FileUtils.getFile("/tmp/bar.txt");
FileUtils.write(file,"This is a test", "UTF-8");
Python
# read line by line
f = open("/tmp/foo.txt","r")
for line in f:
print line
f.close()
# read the entire file in memory
f = open("/tmp/foo.txt","r")
contents = f.read()
print(contents)
f.close()
# write to a file
f = open("/tmp/bar.txt","r+") # open for both read and write
f.write("This is a test")
contents = f.read()
print(contents) # will print "This is a test"
Handling HTTP Communication
Java
Here is an example with okhttp
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://lobster1234.github.io")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
//similarly, use response's methods to get other values like status code, etc.
Python
First, install requests using pip3.
pip3 install requests
Then, you’re ready to make HTTP requests
import requests
r = requests.get("https://lobster1234.github.io")
print(r.headers) # headers as a dict
print(r.status_code) # 200
print(r.content) # body
r.close()
Summary
While these notes provide a quick kick-start and a glimpse in Python Programming, I encourage you to visit python.org and check out the documentation. There is a lot more to Python than what is covered here. Please let me know your feedback with a tweet/DM, and thank you for stopping by!