owned this note
owned this note
Published
Linked with GitHub
---
tags: resources
---
# Going to Python from Java
## Style/Basic syntax
For a thorough comparison, see the [Java](https://hackmd.io/io7Gock2TZqC6UnBwpjP2w) and [Python](https://hackmd.io/69BJEGF_Qe6bXlL4iVjSRA) style guides.
## Data structures/built-in types
The Python [built-in types documentation](https://docs.python.org/3/library/stdtypes.html#truth-value-testing) describes how to use all of these.
You will also find it helpful to refer to the [built-in functions](https://docs.python.org/3/library/functions.html) documentation.
| Java | Python |
|------| -------|
| `boolean` | `bool`* |
|`int` |`int` |
| `double`/`float` | `float` |
| `String` | `str` |
| array/anything that implements `List` | `list` |
| `HashSet` | `set` |
| `HashMap` | `dict` |
*`bool` values in Python are capitalized (`True` and `False`, **not** `true` and `false`)
## Logical operators
| Java | Python |
|------| -------|
| `&&` | `and` |
|`\|\|` |`or` |
| `!` | `not` |
## Defining classes
Here is an example `Dillo` Java class from lecture:
```java=
public class Dillo extends Animal {
public int length;
public boolean isDead;
public Dillo (int len, boolean isD) {
this.length = len;
this.isDead = isD;
}
@override
public boolean isHealthy() {
return !this.isDead && this.length < 20 && this.length > 5;
}
}
...
// in some other class (like Main):
Dillo d = new Dillo(12, false)
if (d.isHealthy()) {
System.out.println("Happy dillo :)")
}
```
Here is the same code, in Python:
```python=
class Dillo(Animal):
def __init__(self, length: int, is_d: bool):
self.length = length
self.is_dead = is_d
def is_healthy(self) -> bool:
return not self.is_dead and self.length < 20 and self.length > 5
# in some other part of the code:
d = Dillo(12, False)
if d.is_healthy():
print("Happy dillo :)")
```
Both of these will print "Happy dillo :)"
Note that `len` is a keyword in Python, so we use `length` as the parameter instead.
## Exceptions
For the Python Exception documentation, see [here](https://docs.python.org/3/tutorial/errors.html).
In Java, we wrote `throw new RuntimeException("An Error Message")`. In Python, we write `raise ValueError("An Error Message")`. See the documentation for types of exceptions that you can raise.
### `try` blocks
A `try/catch` block in Java looked like:
```=java
try {
// code to try something
} catch CustomException e {
// handle e
}
```
The same code in Python looks like:
```=python
try:
# code to try something
except CustomException as e:
# handle e
```
## Testing
For a thorough overview, see our [Python testing guide](https://hackmd.io/cLCJRBbXTSyOyEoNQq4N-Q)
## Common code comparison
### `for` (with a range)
<table>
<tr><th>Java</th><th>Python</th><th>Output</th></tr>
<tr>
<td>
<pre>
for (int i = 0; i < n; i++) {
System.out.println(i);
}
</pre>
</td>
<td>
<pre>
for i in range(0, n):
print(i)
</pre>
</td>
<td>
(when n is 5)
<pre>
0
1
2
3
4
</pre>
</td>
</tr>
</table>
### `foreach` / iterators
<table>
<tr><th>Java</th><th>Python</th><th>Output</th></tr>
<tr>
<td>
<pre>
for (int itm : lst) {
System.out.println(itm);
}
</pre>
</td>
<td>
<pre>
for itm in lst:
print(itm)
</pre>
</td>
<td>
(when lst is [0, 1, 2, 3, 4])
<pre>
0
1
2
3
4
</pre>
</td>
</tr>
</table>
### `while`
<table>
<tr><th>Java</th><th>Python</th><th>Output</th></tr>
<tr>
<td>
<pre>
int i = 0;
while (i < 5) {
System.out.println(i++);
}
</pre>
</td>
<td>
<pre>
i = 0
while i < 5:
print(i)
i+=1
</pre>
</td>
<td>
<pre>
0
1
2
3
4
</pre>
</td>
</tr>
</table>
### `if` / `switch`
<table>
<tr><th>Java</th><th>Python</th><th>Output</th></tr>
<tr>
<td>
<pre>
if (x == 0) {
System.out.println("first");
} else if (x == 1) {
System.out.println("second");
} else {
System.out.println("third");
}
</pre>
</td>
<td>
<pre>
if x == 0:
print("first")
elif x == 1:
print("second")
else:
print("third")
</pre>
</td>
<td>
(when x is 5)
<pre>
third
</pre>
</td>
</tr>
</table>
Python does not have switch statements. Use an `if-elif-else` block instead.
## Useful Python code features
### `enumerate`
You can use `enumerate` to get both the item in a list and its index:
```python=
for i,x in enumerate(["a", "b", "c", "d"]):
print("list at index " + str(i) + ": " + x)
```
Would output:
```
list at index 0: a
list at index 1: b
list at index 2: c
list at index 3: d
```
### List comprehensions
[List comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) provide a syntactically intuitive way to perform common operations (`map`, `filter`) over lists:
**Map a function over a list**:
```python=
def square(x: int):
return x * x
lst = [-1, 2, 3]
[square(n) for n in lst]
# outputs [1, 4, 9]
# can also simply do:
[n * n for n in lst]
```
**Filter a list**:
```python=
lst = [-1, 2, 3]
[x for x in lst if x > 0]
# outputs [2, 3]
```
**Combine mapping and filtering**:
```python=
lst = [-1, 2, 3]
[x * x for x in lst if x > 0]
# outputs [4, 9]
```
Notice that the filtering is done *before* the mapping.
**Using enumerate and filter/map**:
```python=
lst = [True, True, False, False, True]
[i for i,x in enumerate(lst) if x]
# outputs [0, 1, 4] (indices at which the value in lst is true)
```