Python2覚書 変数
変数の宣言
数値や文字列の宣言は以下のように行います。
x = 1 str = "ABCDE"
数値
数値型の種類は以下の4通りです。複素数を使うことができます。8進数は先頭に0を、16進数は0xを付けます。
i = 10 #integer l = 0x19323L #long f = 0.0 #float c = 3.14j #complex number
文字列
引用符号で囲みます。
str1 = 'Hello' str2 = "Hello" str3 = '''Hello''' str4 = """Hello""" print str1 print str1[0]
文字列の結合
'+'を使います。
str1 = 'Hello' str2 = 'Hello' print str1 + str2 print str1 + "World"
リスト
"[]"で囲みます。同じリストに異なる型の要素を入れることができます。
list = [ 0.1 , 0xff00 , 2, 'abc' ] print list print list[0]
リストの結合
'+'を使います。
list1 = [ 1 , 2 ] list2 = [ 'a' , 'b' , 'c' ] list = list1 + list2 print list
タプル
"()"で囲みます。リストと異なって元のタプルを書き換えることはできません。
tuple = ( 0 , 1 , 2 ) print tuple print tuple[0]
タプルの結合
'+'を使います。
tuple1 = ( 0 , 1 , 2 ) tuple2 = ( 'a' , 'b' , 'c' ) tuple3 = tuple1 + tuple2 print tuple3
辞書
"{}"で囲み、'key':'value'という形式で登録します。
dictionary = {'type': 'int','name':'func', 1: 10, 2:20 } print dictionary['type'] print dictionary[1]