[Updating] Python Syntax cheat sheet for Java shop

I recently started Python. However, what I want to do comes out when I google, and thanks to the fact that Python 3 is object-oriented, it is good because I can usually grasp the atmosphere, but when I write it, it is grammar that stumbles. Isn't it? (Just me?) When I'm used to Java, I write it in Java, but how do I write it in Python? It will be a kind of idea, so I hope it will be useful for people who are thinking about similar things.

That's why I wrote this in Java, but I'll leave it as this in Python3. It's just the beginning, so it may be a little wrong in the way of thinking, but it's cute. It's rough. I'm the type to remember while writing. I will update it when I feel like it.

environment

Python 3.8 Java 8

Official tutorial

https://docs.python.org/ja/3/tutorial/index.html

Official unit test

https://docs.python.org/ja/3/library/unittest.html

Cheat sheet

comment

Java

//Line-by-line comment
/*
 *Block comment
 */

Python

#comment

Class definition

Java

public class Hoge {

}

Python

class Hoge:  #The colon is important! !!

Constructor definition

Java

public Hoge(){
  //I'm initializing
} 

Python

(Addition) In the case of Python, it seems that it is a method rather than a constructor. It seems better to think of it as a method called from within the constructor.

def __init__(self):
  #I'm initializing

Instance generation

Java

Hoge hoge = new Hoge();

Python

hoge = Hoge()

Processing starting point (so-called main)

Java

public static void main(String[] args) {
    // body of main()
}

Python

if __name__ == "__main__":
  hoge.hoge()

I want to use another module (class)

Java

import jp.co.hoge.Hoge;

Python

There are many ways to write ...! https://nansystem.com/python-module-package-import/

Conditional expression

https://docs.python.org/ja/3/tutorial/controlflow.html

Java

// a = b and b = c
if (a == b && b == c) {
  System.out.println(a)
}

// a = b or b = c
if (a == b || b == c) {
  System.out.println(a)
}
//denial
if (!enable) {
  System.out.println(a)
}

Python

# a = b and b = c
if a = b and b = c:
  print(a)

# a = b or b = c
if a = b or b = c:
  print(a)

#denial
if not enable:
  print(a)

Comparison operator

Comparison operators are the same for both Java and Python

<  <=   >   >=   ==   !=

null and None

Java null has no objects Python None has no value Means each

https://www.quora.com/What-is-the-difference-between-Javas-null-and-Pythons-None

In Java, null is an instance of nothing, it is often referred as "no object" or "unknown" or "unavailable" .

In Python None is an object, denoting lack of value. This object has no methods. It needs to be treated just like any other object with respect to reference counts.

So these two are not much alike, however since Java 8 Optional has come along which is more similar to None. It is a class that encapsulates an optional value. You can view Optional as a single-value container that either contains a value or doesn't (it is empty)

Strictly speaking, null and None have different meanings, so they cannot be used in the same way. None is close to Optional in Java.

While the difference is nuanced, Python's None by being an object itself, helps avoid some types of programming errors such a NullPointerExceptions in Java.

However, since None is an object, it is useful for things like Nullpo processing.

It seems to be a story.

Character string blank / null judgment

Python is None, not null. https://pg-chain.com/python-null

Java

// str != null && str != ""
if (str.isEmpty()) {
  return true;
}

Python

if not str:
  return True
else
  return False

error

https://docs.python.org/ja/3/tutorial/errors.html The default class is Exception class for both Java and Python

java

try {
  //Processing that raises an exception
} catch (Exception e) {
  e.printstacktrace();
  throw new CustomizeException();
} finally {
  //The last thing you want to do
}

Python

try:
  //Processing that raises an exception
except Exception as e:
  print(e)

list

https://docs.python.org/ja/3/tutorial/datastructures.html

Python lists are a nice touch of Java arrays and ArrayList. Writing is similar to a Java array. Python also has an array type, which is almost the same as a Java array. Array type cannot be used by default and needs to be imported.

Java

List<String> list = new ArrayList<>;

//Get the length of the array
list.size();

//Add to list
list.add("lemon");

Python

l = ["John", "Bob", "Carry"]

#Get the number of elements in the list(Use the len function)
len(l)

#Add to list
l.append("Mickey")

Map → dictionary

Map in Java is a Python dictionary (dict). https://docs.python.org/ja/3/tutorial/datastructures.html

Java

Map<String, String> map = new HashMap<>();

Python

#Curly braces{}When creating with
d = {'key1': 'aaa', 'key2': 'bbb'}

#Can also be created with a constructor
d2 = dict()
d3 = dict('k1'='aaa', 'key2'='bbb')
#There are many other ways to write

Other sites that were helpful in various ways

--Naming convention - https://qiita.com/naomi7325/items/4eb1d2a40277361e898b --Pylint gets angry when trying to import another module - https://qiita.com/ysuzuki19/items/55e2907a7c8f06889581 --Read file - https://qiita.com/wiwi7373/items/c4b2b9ef02ae0f970843 --How to use the unittest library - https://kazuhira-r.hatenablog.com/entry/2019/10/20/222620 --Csv import / export - https://note.nkmk.me/python-csv-reader-writer/

reference

https://qiita.com/karadaharu/items/37403e6e82ae4417d1b3 https://www.rose-hulman.edu/class/cs/csse220/200910/Resources/Python_vs_Java.html https://python.keicode.com/lang/oop-basics.php

Acknowledgments

Thank you @shiracamus

Recommended Posts

[Updating] Python Syntax cheat sheet for Java shop
Python cheat sheet (for C ++ experienced)
AtCoder cheat sheet in python (for myself)
Python3 cheat sheet (basic)
PySpark Cheat Sheet [Python]
Python sort cheat sheet
[Python3] Standard input [Cheat sheet]
Data Science Cheat Sheet (Python)
Python Django Tutorial Cheat Sheet
Apache Beam Cheat Sheet [Python]
Python Computation Library Cheat Sheet ~ itertools ~
Differences in syntax between Python and Java
Blender Python Mesh Data Access Cheat Sheet
Mathematical Optimization Modeler (PuLP) Cheat Sheet (Python)
SublimeText2 and SublimeLinter --Syntax check for Python3--
R code compatible sheet for Python users
2016-10-30 else for Python3> for:
python [for myself]
with syntax (Python)
Curry cheat sheet
SQLite3 cheat sheet
pyenv cheat sheet
Python syntax-control syntax
LeetCode Python [updating]
[For data science] Oreore Jupyter cheat sheet [Jupyter Notebook / Lab]
Benchmark for C, Java and Python with prime factorization
A Java programmer studied Python. (for, if, while statement)
[Python of Hikari-] Chapter 05-05 Control syntax (for statement-multiple loops-)