2.2. Pythonインタプリタ¶
2.2.1. 算術計算¶
[1]:
1 + 2 # 加算
[1]:
3
[2]:
1 - 2 # 減算
[2]:
-1
[3]:
4 * 5 # 乗算
[3]:
20
[4]:
7 / 5 # 除算
[4]:
1.4
[5]:
3 ** 2 # 累乗 (3の2乗)
[5]:
9
2.2.2. 変数¶
[9]:
x = 10 # 初期化
print(x) # x を出力する
10
[10]:
x = 100 # 代入
print(x)
100
[11]:
y = 3.14
x * y
[11]:
314.0
[12]:
type(x * y)
[12]:
float
2.2.3. リスト¶
[13]:
a = [1, 2, 3, 4, 5] # リストの作成
print(a) # リストの中身を出力する
[1, 2, 3, 4, 5]
[14]:
len(a) # リストの長さを取得
[14]:
5
[15]:
a[0]
[15]:
1
[16]:
a[4]
[16]:
5
[17]:
a[5]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-17-4a84d856522b> in <module>
----> 1 a[5]
IndexError: list index out of range
[18]:
a[4] = 99
print(a)
[1, 2, 3, 4, 99]
[19]:
a[0:2] # インデックスの0番目から2番目まで
[19]:
[1, 2]
[20]:
a[1:] # インデックスの1番目から最後まで
[20]:
[2, 3, 4, 99]
[21]:
a[:3] # 最初からインデックスの3番目まで
[21]:
[1, 2, 3]
[22]:
a[:-1] # 最初から最後の要素の1つ前まで
[22]:
[1, 2, 3, 4]
[23]:
a[:-2] # 最初から最後の要素の2つ前まで
[23]:
[1, 2, 3]
2.2.4. ディクショナリ¶
[24]:
me = {'height': 180} # ディクショナリを作成
me['height'] # 要素にアクセス
[24]:
180
[25]:
me['weight'] = 70 # 新しい要素を追加
print(me)
{'height': 180, 'weight': 70}
2.2.5. ブーリアン¶
[26]:
hungry = True # お腹すいてる?
sleepy = False # 眠い?
type(hungry)
[26]:
bool
[27]:
not hungry
[27]:
False
[28]:
hungry and sleepy
[28]:
False
[29]:
hungry or sleepy
[29]:
True
2.2.6. if文¶
[30]:
hungry = True
if hungry:
print("I'm hungry")
I'm hungry
[31]:
hungry = False
if hungry:
print("I'm hungry")
else:
print("I'm not hungry")
print("I'm sleepy")
I'm not hungry
I'm sleepy
2.2.8. 関数¶
[33]:
def hello():
print("Hello World!")
hello()
Hello World!
[34]:
def hello(object):
print("Hello " + object + "!")
hello("cat")
Hello cat!