LoginSignup
1
0

More than 5 years have passed since last update.

Pythonについて vol03.if文

Posted at

今回からロジックに入っていきます。
まずはif文についてです。
 
基本形

if <条件文>:
    <命令文>
elif <条件文>:
    <命令文>
else:
    <命令文>

各々の命令文の行頭にインデントを入れてください。
python界ではインデントはスペース4つが定説です。
(って後輩に借りパクされたオライリーに書いてあった気がする。)

条件文には以下の比較演算子が利用できます。
数字:==, !=, >, >=, <, <=
文字:==, !=
オブジェクト:is, is not

等号、不等号の順番は固定です。(必ず不等号が先)
またオブジェクトのis, is notはNone(Null)の時に使う。くらいに覚えておけばよいです。
 
記述例)

if var is None:
    print('var is None')
elif var is not None:
    print('var is not None')

またif文とin演算子の組み合わせは便利です。
配列や辞書をfor文で繰り返す必要がありません。
 
記述例)

array = ['a', 'b', 'c', 'd']
if 'c' in array:
    print('There is c in array')

dict = {'key1':'value1', 'key2':'value2', 'key3':'value3'}
if 'key3' in dict:
    print('key3 is '+dict['key3'])
else:
    print('There is not key3 in dict')

valueを探す場合

if 'value3' in dict.values():
    print('There is value3 in dict')

※value3の時のkeyを見つけるにはforを使わないとだめかなぁ。

1
0
1

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
0