作成日
2013/07/20最終更新
2015/10/25記事区分
一般公開if-elif-else
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# コメント内であっても、ASCII外の文字が含まれる場合はエンコーディング情報が必須
x = 1
# 一行スタイル
if x==0: print 'a' # 参考: and,or,notが使用可能 (&&,||はエラー)
elif x==1: print 'b' # elif (elsifでもelse ifでもない)
else: print 'c'
# インデントスタイル
if x==0: # 参考: 0,空のオブジェクト,Noneオブジェクト,Falseオブジェクトのみが偽
print 'a' # pythonのprintは改行する (rubyのputsに相当)
elif x==1:
print 'b'
else:
print 'c'
# これはエラー (インデントが必要)
# if x==0:
# print 'a'
# elif x==1:
# print 'b'
# else:
# print 'c'
実行例
$ python sample.py
b
b
switch case のような処理
pythonにはswitch caseがない。
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
x = 1
print {0: 'a',
1: 'b',
2: 'c'}[x];
print {0: 'a',
1: 'b',
2: 'c'}.get(x);
print {0: 'a',
1: 'b',
2: 'c'}.get(x+999,'default');
実行例
$ python sample.py
b
b
default
三項演算子のような処理
x = 't' if True else 'f'
print x #=> 't'
関連記事
- Python コードスニペット (リスト、タプル、ディクショナリ)リスト range 「0から10まで」といった範囲をリスト形式で生成します。 sample.py print range(10) # for(int i=0; i<10; ++i) ← C言語などのfor文と比較 print range(5,10) # for(int i=5; i<10; ++i) print range(5,10,2) # for(int i=5; i<10;...
- ZeroMQ (zmq) の Python サンプルコードZeroMQ を Python から利用する場合のサンプルコードを記載します。 Fixing the World To fix the world, we needed to do two things. One, to solve the general problem of "how to connect any code to any code, anywhere". Two, to wra...
- Matplotlib/SciPy/pandas/NumPy サンプルコードPython で数学的なことを試すときに利用される Matplotlib/SciPy/pandas/NumPy についてサンプルコードを記載します。 Matplotlib SciPy pandas [NumPy](https://www.numpy
- pytest の基本的な使い方pytest の基本的な使い方を記載します。 適宜参照するための公式ドキュメントページ Full pytest documentation API Reference インストール 適当なパッケージ
- PID 制御による全方向移動ロボットの位置制御 (ODE、Python)Open Dynamics Engine (ODE) を用いて、全方向移動ロボットの位置制御を PID 制御で行う場合のサンプルを記載します。差分駆動型ロボットと比較して、全方向移動ロボットは任意の方向に移動できるため位置制御が容易です。 モータの角速度を操作することでロボットの位置を制御 目標値 xdx_dxd と現在時刻における測定値 x(t)x(t)x(t) の残差 e(t)e(t)e(t...