Skip to content
Snippets Groups Projects
Commit 701b2031 authored by Pat's avatar Pat
Browse files

Added a python syntax guide with comparisons to Java

parent 0c7d0b0f
No related branches found
No related tags found
No related merge requests found
# Python Syntax vs Java
Python and Java are very different when it comes to coding within them. Python is a lot less structured, this file will go over similarities and differences between the two to hopefully help you guys out!
## Hello World
### Python
```python
print("Hello World")
```
### Java
```java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
```
As you can see, Python is a lot simpler as you can just "start" coding without having to do all the surrounding method declarations and things like that.
You *can* have a main method in python, if you'd like, though that tends to be more useful for larger programs that use multiple files. Here's how that's done:
```python
def main():
print("Hello World")
if __name__ == "__main__":
main()
```
## Variable Declarations
Java:
```java
String name = "Alice";
int age = 30;
```
Python:
```python
name = "Alice"
age = 30
```
Note: In Python, variables are not explicitly typed. The interpreter infers the type dynamically.
## Basic Data Types
Strings: 'hello', "world"
Integers: 42, -1
Floats: 3.14, -0.001
Booleans: True, False
## Control Structures
### If-Else
Java:
```java
if (age > 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
```
Python:
```python
if age > 18:
print("Adult")
else:
print("Minor")
```
Note: Python uses indentation instead of curly braces to define blocks.
## Loops
For Loop (Java):
```java
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
```
For Loop (Python):
```python
for i in range(5):
print(i)
```
While Loop (Java):
```java
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
```
While Loop (Python):
```python
i = 0
while i < 5:
print(i)
i += 1
```
5. Functions
Java:
```java
public static int addNumbers(int a, int b) {
return a + b;
}
```
Python:
```python
def add_numbers(a, b):
return a + b
```
Note: Python functions start with the def keyword. No need to specify return types.
## Lists and Dictionaries
List (Similar to Java's ArrayList):
```python
numbers = [1, 2, 3, 4, 5]
```
Dictionary (Similar to Java's HashMap):
```python
person = {"name": "Alice", "age": 30}
```
## Comments
Java:
```java
// This is a single line comment
/* This is a multi-line comment */
```
Python:
```python
# This is a single line comment
```
Note: Python does not have a native syntax for multi-line comments, but you can surround the comment in quoutes as a workaround
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment