初めてのPython(10章)

2部ではビルドインオブジェクトのことをやり、3部ではステートメントについて

Pythonプログラムの構造

4章でもやってたけど、忘れてるので覚えるためにも。
3部でやるステートメントの並べ方でプログラムのロジックが決まる。

  • プログラムはモジュールから構成される
  • モジュールはステートメントから構成される
  • ステートメントは式から構成される
  • 式により、オブジェクトは生成・処理される

Pythonステートメント

代入、関数呼び出し、繰り返し処理と行った基本的なものから、
関数/クラス定義、コンテキストマネージャや文字列をコードとして実行するexecまで色々

Pythonステートメントの特徴

  • 行の終わりがステートメントの終わりなので、セミコロン(;)は不要
  • 複合ステートメントの見出しの最後には必ずコロン(:)
  • コードブロックはインデント量で管理
    • 括弧({})やキーワード(begin/end, then/fiなど)は不要

その他のお勉強

Cのコードブロック

思いっきり勘違い。
(A)と(B)は同じだと思っていたら、(B)とは別で(C)と同じだった。。。
elseは元も内側のifに対応するってことなのか。
「ブロックはちゃんと括弧で括りなさい」っていうのはこういうことが簡単に起きちゃうからなんだね。

(A)

if(input1 == 0)
  if(input2 == 0)
    fprintf(stderr, "input1 and input2 is zero\n");
else
  fprintf(stderr, "input1 is non-zero\n");

(B)

if(input1 == 0) {
  if(input2 == 0) {
    fprintf(stderr, "input1 and input2 is zero\n");
  }
}
else {
  fprintf(stderr, "input1 is non-zero\n");
}

(C)

if(input1 == 0) {
  if(input2 == 0) {
    fprintf(stderr, "input1 and input2 is zero\n");
  }
  else {
    fprintf(stderr, "input1 is non-zero\n");
  }
}    

(お試し結果)

[kobakoba0723@fedora13-intel64 ~]$ gcc -o test test.c
[kobakoba0723@fedora13-intel64 ~]$ ./test 0 0
input1 and input2 is zero
[kobakoba0723@fedora13-intel64 ~]$ ./test 0 1
input1 is non-zero
[kobakoba0723@fedora13-intel64 ~]$ ./test 1 0
[kobakoba0723@fedora13-intel64 ~]$ ./test 1 1
[kobakoba0723@fedora13-intel64 ~]$ gcc -o test_bracket test_bracket.c 
[kobakoba0723@fedora13-intel64 ~]$ ./test_bracket 0 0
input1 and input2 is zero
[kobakoba0723@fedora13-intel64 ~]$ ./test_bracket 0 1
input1 is non-zero
[kobakoba0723@fedora13-intel64 ~]$ ./test_bracket 1 0
[kobakoba0723@fedora13-intel64 ~]$ ./test_bracket 1 1
[kobakoba0723@fedora13-intel64 ~]$ 

(test.c)

#include <stdio.h>

int main(int argc, char *argv[]) {
  int input1, input2;
  
  input1 = atoi(argv[1]);
  input2 = atoi(argv[2]);
  
  if(input1 == 0) {
    if(input2 == 0) {
      fprintf(stderr, "input1 and input2 is zero\n");
    }
  }
  else {
    fprintf(stderr, "input1 is non-zero\n");
  }

  return 0;
}

(test_bracket.c)

#include <stdio.h>

int main(int argc, char *argv[]) {
  int input1, input2;
  
  input1 = atoi(argv[1]);
  input2 = atoi(argv[2]);
  
  if(input1 == 0) {
    if(input2 == 0) {
      fprintf(stderr, "input1 and input2 is zero\n");
    }
    else {
      fprintf(stderr, "input1 is non-zero\n");
    }
  }    

  return 0;
}
ステートメントと式

ステートメント*1は、

プログラムの一命令のことで、1行から構成されるもの、複数行から構成されるものがある

pythonだと、

  • a = "str"
  • if a == "str": print "matched"

*2は、

定められた優先順位や結びつきの規定に則って評価される値、変数、演算子、関数の組み合わせのこと

pythonだと、

  • [1, 2, 3]
  • 1 + 2
  • a * 2