LoginSignup
2

More than 5 years have passed since last update.

【思い出す用】Python3の基本構文【勉強ノート】執筆途中

Last updated at Posted at 2019-02-14

自分用という程で書いているので、プログラミング初心者用の方はわかるようには書いていません。
すでにPythonを習得したことがあり、久しぶりに使わなきゃいけない時には役立つかもしれません(自分宛
自分がPythonを使いこなしていないのであまり当てにしないでください。
間違っているところがあれば、必ず教えてください(懇願
いくつかPythonの本を読んで来ましたが、再学習のために読んでいる本を自分なりにまとめたものです。
退屈なことはPythonにやらせよう Amazon

Pythonの シングルクォート(')、ダブルクォーテーション(")

基本的にPythonはシングルクォート(')、ダブルクォーテーション(")の区別がありません。(文字列と1文字で違ったかも...別の言語の話かも...
下のコードは同じ結果を示す

print('Hello')
print("Hello")

面白いものとしては

print("英語で'こんにちは'は、'Hello'です。")

シングルクォート(')、ダブルクォーテーション(")が混同したコードがエラーなく動くことです。

コメント

#1行コメント
'''
複数行コメント
'''
"""
複数行コメント
"""
#複数行コメントのこの形は文字列をコメントとして使うためにに代入せずに使っているらしいです。

いろんな値

整数型 int型

num1 = 15
num2 = 10.5
print(num1)
print(int(num2))
'''
15
10 #少数点以下は全て切り捨て(四捨五入ではない
'''

少数型(浮動小数点数 float型

num1 = 15.7
num2 = 13
print(num1)
print(float(num2))
'''
出力
15.7
13.0
'''

文字列型 str型

greeting1 = "Hello"
greeting2 = 'Hello'
programingGreeting = greeting1 + " World!"
greeting2 *= 3
print(greeting2)
print(programingGreeting)
'''
出力
HelloHelloHello
Hello World!
'''

論理型 bool型

True
False

インデックス

配列を扱う際に引数の感じで、配列の順番を指定する
インデックスに負の整数を入れることで最後から数えられる
"-1"で最後の配列
animal[インデックス]

animal = ["cat","dog","rat","elephant"]
print(animal[1])
print(animal[-1])
'''
出力
dog
elephant
'''

リスト型 []

複数の値を順番に並べた値
要素の追加、削除などの変更が可能

animal = ["cat","dog","rat","elephant"]
print(animal[-1])

for ani in animal:
    print(ani)
'''
出力
elephant #animalの最後
cat
dog
rat
elephant
'''

タプル型 ()

ほとんどリスト型と一緒
要素の追加、削除などの変更が文字列と一緒で不可能

animal = ("cat","dog","rat","elephant")

辞書型 {}

インデックスとなるキーと、その値どちらも指定ができる。まさに辞書という感じ

my_cat = {"size":"fat","color":"gray","disposition":"loud"}
print(my_cat["size"])

for v in my_cat.values():
    print(v)
for k in my_cat.keys():
    print(k)
for i in my_cat.items():
    print(i)
for i, k in cat.items():
    print(i + "\t" + k)
'''
出力
fat

fat
gray
loud

size
color
disposition

('size', 'fat')
('color', 'gray')
('disposition', 'loud')

size    fat
color   black
voice   loud
'''

辞書の呼び出し get setdefault

my_cat = {"size":"fat","color":"gray","disposition":"loud"}
print("I have " + my_cat.get("size","small") + " Dog")
#getで呼び出すことで、"size"がなかった時にエラーを起こさず、"small"を返す
"size" in my_cat.keys()でも確認できるがめんどくさい

if "height" not in my_cat:
    my_cat["height"] = 180
#上を一文でかける
my_cat.setdefault("color", "black")
#"color"のキーがなかったら"color"キーを作成し、"black"という値を代入するすでに存在する場合は何も起きない

#Example 文字数を数える
message = "Hello Python World. I am zunda.It is sunny."
count = {}
for character in message:
    count.setdefault(character,0)
    count[character] += 1
print(count)
'''
出力
{'H': 1, 'e': 1, 'l': 3, 'o': 3, ' ': 7, 'P': 1, 'y': 2, 't': 2, 'h': 1, 'n': 4, 'W': 1, 'r': 1, 'd': 2, '.': 3, 'I': 2, 'a': 2, 'm': 1, 'z': 1, 'u': 2, 'i': 1, 's': 2}
'''

配列のコピー

リスト、タプルの単純なコピーをしようとするとC言語のポインタのようになってしまいアドレスの参照をして変わったことが起きます。
copyは一次元までしか対応していない二次元はアドレスが一緒
deepcopyは二次元以降もアドレスを変更するので、二次元以降も変更しても元の配列がついてこない

from copy import copy,deepcopy
animal1 = ["dog","cat", 123, "year", 907, "Mac", "Windows"]
animal2 = ["dog","cat", 123, "year", 907, "Mac", "Windows"]
animal3 = [["dog","cat"],["year", 907],["Mac", "Windows"]]
animal4 = [["dog","cat"],["year", 907],["Mac", "Windows"]]

copy1 = animal1
copy2 = copy(animal2)
copy3 = copy(animal3)
copy4 = deepcopy(animal4)

copy1 += ["Linux"]
copy2 += ["Linux"]
copy3[0][0] = "cat" 
copy4[0][0] = "cat"


print(animal1)
print(animal2)
print(animal3)
print(animal4)
'''
出力
['dog', 'cat', 123, 'year', 907, 'Mac', 'Windows', 'Linux']
['dog', 'cat', 123, 'year', 907, 'Mac', 'Windows']
[['cat', 'cat'], ['year', 907], ['Mac', 'Windows']]#animal3とcopy3の2次限目以降はアドレスが同じなのでanimal3も変わってしまう:
[['dog', 'cat'], ['year', 907], ['Mac', 'Windows']]#animal4とcopy4の2次限目以降もアドレスが違うのでanimal4は変わらない

#animal1は変えていないのに変わってしまう。
#animal2はcopyメソットでコピーしたため変わらない
'''

リストとタプルの混同

animal = (["dog","cat"],[123,"year",907],["Mac","Windows"])
#タプルの中にリストを作りタプル要素を変更させず、リスト内だけを変更していいようにする
#これを使うといい時もある、自分は経験のなさで知らないです。教えてください。

タプル⇆リストに変更

tuple(["cat","dog","rat","elephant"])
#リストをタプルに変更
list(("cat","dog","rat","elephant"))
#タプルをリストに変更

リスト内にリスト

animal = ["cat","dog","rat","elephant"]
span = [animal,[10, 20, 30, 55]]
print(span[0])
print(span[1])
print(span[0][2])
'''
出力
['cat', 'dog', 'rat', 'elephant']
[10, 20, 30, 55]
rat
'''

リストを一気に複数代入

cat = ["fat","black","loud"]
size = cat[0]
color = cat[1]
disposition = cat[2]
#これでもいいが下のようなこともpythonでは可能
size, color, disposition = cat
#これでも同じことが可能(プログラマーっぽくなる(多分

リストの集合的な働き

#結合
span = ["animal","tomato","salad"]
span += ["Hello"] #span.append(Hello)と同じ
'''
出力 
['animal', 'tomato', 'salad', 'Hello']
'''
span += "Hello"
'''
出力
"Hello"は配列なので別れてしまう。
['animal', 'tomato', 'salad', 'H', 'e', 'l', 'l', 'o']
''

要素の探索 index

span = ['animal', 'tomato', 'salad']
print(span[2])
print(span.index("animal"))
'''
出力
salad
0
'''

要素の操作 append insert del remove

span = ['animal', 'tomato', 'salad']#スタート

span.append("Hello")
#末尾に要素を追加 ['animal', 'tomato', 'salad', 'Hello']
span.insert(1,"Good")
#指定の場所に要素を追加 ['animal', 'Good', 'tomato', 'salad']
del span[0]
#指定の場所を削除 ['tomato', 'salad',]
span.remove("tomato")
#指定の値を削除 ['animal', 'salad',]

要素の並び変える

span = ['animal', 'tomato', 'salad','Spin']#スタート

span.sort()
#要素の並びを高さ順に(数字の大きさ順、アルファベット順(ASCILLコード順のため大文字が最初))(数字と文字列は比較ができなため混合している配列はsortできない)                                    ['Spin', 'animal', 'salad', 'tomato']
span.sort(str.lower)
#要素を大文字小文字関係なく並び変える['animal', 'salad', 'Spin','tomato']
span.sort(reverse=Ture)
#要素の並びを逆に['Spin','salad', 'tomato', 'animal']

変わったindex[2:3] (スライスという

span = ['animal', 'Good', 'tomato', 'salad', 'Hello']
print(span[0:4])
# [n:m]nからm-1まで['animal', 'Good', 'tomato', 'salad']

print(span[2:])
#[n:]nから最後まで['tomato', 'salad', 'Hello']

print(span[:3])
#[:n]最初からn-1まで['animal', 'Good', 'tomato']

range

for num in range(5):
    print(rum)
'''
出力
0
1
2
3
4
'''

range(int(a), int(b), int(c))
"a"に"c"を足して"(b-1)"まで行く
"c"に負の整数を入れることで"a"を小さくすることもできる

for num in range(0, 10, 2)
    print(num)
'''
出力
0
2
4
6
8
'''

import

import random
for i in range(5):
    print(random.randint(1,10))
'''
出力 1~10の整数が出力
4
1
6
10
8
'''

from import

importよりfrom importを使う方が良いとされている
わかりやすいため

from random import randint
for I in range(5):
   print(randint(1,10))
'''
出力 print内のrandomを省略
4
5
6
2
5
'''

break

繰り返し文の中に使用し、breakで繰り返し文を抜け出す

for num in range(5):
    if num == 3:
        break
    print(num)
'''
出力
0
1
2
'''

continue

繰り返し文の中に使用し、continueで繰り返し文をスキップ

for num in range(5):
    if num == 3:
        continue
    print(num)
'''
出力
0
1
2
4
'''

基本的な関数

  • print()

  • input()

  • len()

関数の作成

defで関数を作成

def hello():
    print("Hello")
    print("Welcome to Japan!")
Hello()
Hello()
'''
出力
Hello
Welcome to Japan!
Hello
Welcome to Japan!
'''

戻り値 引数

returnで関数から値を返す
関数の名前横の()の中に変数名を入れて引数を設定
","で複数引数を設定

def area(length,height):
    return length*height
print("area is " + str(area(10,21)))
'''
出力
area is 210
'''

ローカル変数

ある関数の中に定義された変数
ローカル変数はその関数の中でしか使えない

グローバル変数

全ての関数の外に定義された変数
グローバル変数はどの関数の中でも使える

def bacon():
    global num = 1 #グローバル変数を関数の中で定義できる

スコープ

スコープとは変数の格納庫であり関数内が格納庫の大きさです。
種類としては、ローカルスコープ、グローバルスコープがある
特に覚えなくて良いが、ローカル変数、グローバル変数は大切

PythonのNull(None)

Pythonでは、nullやnilではなく"None"として表される


#ex1
num = 100
print(num)
num = None
print(num)
'''
出力
100
None
'''
#ex2
span = print("Hello!")
print(span)
'''
出力
Hello!
True
'''

例外処理 try except

エラーが起きた時にプログラムを止めずに自身のコードを実行させる

def spam(divide_by):
    try:
        return 42/divide_by #devide_byが0の場合エラーが出る
    except:
        print("エラー:不正な引数です。")
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
'''
出力
21.0
3.5
エラー:不正な引数です。
42.0
'''

例外処理が必要な場面

浅浅プログラマーのいうことですので気にしないでください。なんとなくエラーが多そうなとこだなぁーと思っただけです。
経験が少ないので実戦経験があるプログラマーの方オススメの例外処理例を教えてください。

- リストのindex、値での参照

in と not in

リストなどの中に要素が存在するかをTrue Falseで返してくれます。

"howdy" in ["hello","hi","howdy"]
"howdy" not in ["hello","hi","howdy"]
'''
出力
True
False
'''

整形表示

辞書を綺麗に表示してくれるもの
pprint.pprint(), print(pprint.pformat()) どちらも同じもの
python
from pprint import pprint
message = "Hello Python World. I am zunda.It is sunny."
count = {}
for character in message:
count.setdefault(character,0)
count[character] += 1
pprint.pprint(count)
'''
出力
{' ': 7,
'.': 3,
'H': 1,
'I': 2,
'P': 1,
'W': 1,
'a': 2,
'd': 2,
'e': 1,
'h': 1,
'i': 1,
'l': 3,
'm': 1,
'n': 4,
'o': 3,
'r': 1,
's': 2,
't': 2,
'u': 2,
'y': 2,
'z': 1}
'''

エスケープ文字(特殊文字

エスケープ文字 意味
\' '(シングルクォート
\" "(ダブルクォート
\t タブ
\n 改行
\ (バックスラッシュ

三連クォート

'''〜'''は中でエスケープ文字を気にせずに改行などを行えます。よってこれによりコメントを複数行での表示ができます。

print('''
"今日"は
いい\天気/

ですね''')
'''
出力
"今日"は
いい\天気/

ですね
'''
#下は全てコメント
#コメント
'コメント'
"コメント"
'''コメント'''
"""コメント"""

大文字,小文字

span = 'Hello World'
print(span.upper())
print(span.lower())

span = span.upper()
print(span.isupper())
print(span.islower())
'''
出力
HELLO WORLD
hello world
True
False
'''

isXメソッド

'hello'.isalpha()#isalphaは1文字以上の英文字から構成している場合True
True
'hello123'.isalnum()#isalnumは1文字以上の英文字、数字から構成されている場合True
True
'123'.isdecimal()#isdecimalは1文字以上の数字から構成されている場合True
True
''.isspace()#isspaceはスペース、タブ、改行から構成されている場合True
True
'This Is Title Case'.istitle()#istitleは大文字で始まり、他が小文字の単語のみで構成されている場合True
True

文字列の検索 startwith endwith

"Hello world!".startwith("Hello")#Helloで始まっている場合Trueを返す
True
"abc123".endwith("123")#123で終わっている場合Trueを返す
True

文字列の分割、結合 split join

", ".join(["cat","rats","bats"])#要素の間の文字を決めて要素を指定する
"cat, rats, bats"
"ABC.join(["My}

lamda

lamdaとは名前をつけるほどの関数ではない。
関数を変数としたい。時に使います。

def function(x)
    return x + 2
list(function, y)

list(lamda x:x + 2, y)#わざわざ外で関数の定義をしなくても良い(引数と返り値を設定できる
#上二つは同じ意味

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
2