Beyond The Limit

はじまりは2001年

Python学習メモ1

オライリーの入門Python3より。

型確認

type(変数名) で変数の型が返ってくる

>>> a = 7
>>> type(a)
<class 'int'>

>>> a = "あいうえお"
>>> type(a)
<class 'str'>

>>> type(1.0)
<class 'float'>

こんな感じ

数値

除算 /の場合は浮動小数点で結果を返す、//の場合は結果は切り捨てになる

>>> 3/4
0.75
>>> 3//4
0

型の変換 int(値)で整数型、float(値)で浮動小数点型へ変換される

>>> int(9.1)
9

>>> int(abc)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined

True=1,Flase=0,true=エラー,false=エラーになる。

True/Falseはブール型なので0か1に変換される。

>>> int(true)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined

>>> int(True)
1

intの場合は文字列・数値を文字列扱いすると変換しない。

floatの場合は数値を文字列扱いしても変換する。

>>> int(1.0e3)
1000
---
>>> int ('1.0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.0'
>>>
---
>>> float ('1.0')
1.0
---
>>> int(1.0)
1

文字列

Pythonの文字列はイミュータブルである。

シングルクォートもダブルクォートも3つ使うことができる、文章が長い場合に始まりと終わりを表す。

>>>a = ''' abc def
... hig
... kas
... '''
>>> 

>>> print (a)
 abc def
hig
kas

>>>

こんな感じに複数行対応している、シングル/ダブルクォートもダブルクォートが1つの場合は改行時にエラーが出る。

>>> a = 'abc
  File "<stdin>", line 1
    a = 'abc
           ^
SyntaxError: EOL while scanning string literal
>>>

print()を使わない場合は改行は改行コードで表示される

>>> a
' abc def\nhig\nkas\n'
>>>

空文字列はシングル/ダブルクォートを入力することで作ることができる

他の文字列から新しく文字列を組み立てたい時に使う。

+=などの場合は予め空文字列で変数に何か代入しておく必要がある

>>> base = ""
>>> base += "あいうえお"
>>> base
'あいうえお'
>>>

>>> bake += "あいうえお"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'bake' is not defined
>>>

>>> bake = "あいうえお"
>>> bake
'あいうえお'
>>>

所感

pythonインタプリタで気になる動作があったので、調べていたらはやぶささんのブログにたどり着いた。 世界は狭い。