LoginSignup
1
2

More than 5 years have passed since last update.

Pythonのインデント

Posted at

今まで使ってきた言語にはなかったルールなので、備忘録として。

  • pythonは インデント で文をグループ化しているのが特徴
    • Java等のように {} を使用しない
  • これは、コードの可読性も兼ねてる仕様らしい

サンプル

Python
x = 3
if x == 3:
    print("True!") # ifのブロック
    print("x is 3") # ifのブロック
console
True!
x is 3 

Javaだとこう

Java
int x = 3;
if (x == 3) {
    System.out.println("True!");
    System.out.println("x is 3");
}

インデントを正しく空けないと...

Python
x = 0
if x == 3:
    print("True!") # ifのブロック
print("x is 3") 

結果が偽なのに x is 3 が出力される

console
x is 3 

インデントはいくつ空けるのが適切か?

半角スペース1つだけ空けてもグループ化されるが、
有名なコーディング規約によると
PEP8 によると、 半角スペース4つ が1レベルのインデント として空けるのが良いとのこと

Use 4 spaces per indentation level.

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2