12

More than 5 years have passed since last update.

# Pythonを書くための最低限の文法メモ

Last updated at Posted at 2016-03-28

## 予約語

http://qiita.com/cm3/items/6a856c44dd92632aa54f

## 定数

• True - 真
• False - 偽
• None - 値がない時に使われる。

## bool演算

bool
``````a and b         # a も b も真であれば真
a or b          # a または b が真であれば真
not a           # a が偽であれば真
``````

## Noneの処理判別

none
``````if hoge is None:
#Noneのときの処理

if hoge is not None:
#Noneじゃないとき
``````

## 配列(list)

array
``````values = [1, 2, 3, 4]
print values[0] #1
print "length=" + str( len(values) ) #length=4

``````
push
``````list = ["A", "B", "C"]

list.append("D")
print list     # ["A", "B", "C", "D"]

``````

## オブジェクト(dict)

dict
``````d = {'Yamada': 30, 'Suzuki': 40, 'Tanaka': 80}
``````
dict
``````for k, v in d.items():
print k, v             # Tanaka 80, Yamada 30, Suzuki 40

for k in d.keys():
print k, d[k]          # Suzuki 40, Yamada 30, Tanaka 80

for v in d.values():
print v                # 80, 30, 40

for k, v in d.iteritems():
print k, v             # Tanaka 80, Yamada 30, Suzuki 40
``````

## for文

for
``````#0〜9までループ
for i in range(0, 10):
print "hoge " + str(i)
``````
for
``````#配列の中身を走査
values = [ "hoge", "fuge", 123 ]
for value in values:
print value
``````

## if文

if
``````if hoge < 1:
print "fuga1"
elif hoge < 2:
print "fuga2"
else:
print "fuga3"
``````

## cast

cast
``````print "hoge" + str( 100 ) #hoge100
print 10+int("5") #15
``````

## 数字を丸める

floor
``````import math
math.floor(x)
math.ceil(x)
``````

## 関数

function
``````def hoge(a,b):
print "hoge";
return "hoge" + a + b

#呼び出し
hoge("AAA","BBB")#hogeAAABBB
``````

## `__name__`

よく見かける特別な変数`__name__`。メインプログラムのときは`__name__=="__main__"`となる。importするとファイル名が入る。それらを区別するために以下のような表記をよくつかうようだ。

`__name__`
``````if __name__ = "__main__":
print "メインプログラムだよ"
#else:
#   print "importされてるよ"
``````

## 参考

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
12