0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python備忘録2(制御構文)

Last updated at Posted at 2023-08-14

論理演算子

and

and.py
# and
pet = 'cat'
fur = 'white'

if pet == 'cat' and fur == 'white':
    print('白猫')
console
白猫
論理値A 論理値B 論理値
True True True
True False False
False True False
False False False

all

all.py
# all
pet = 'cat'
fur = 'white'

if all((pet == 'cat',fur == 'white')):
    print('白猫')
else:
    print('白猫ではない')


if all((pet == 'cat',fur == 'black')):
    print('黒猫')
else:
    print('黒猫ではない')

console
白猫
黒猫ではない
条件 論理値
すべて論理値がTrue True
1つ以上論理値がFalse False

or

or.py
# or
pet = 'rabbit'
fur = 'white'

if pet == 'cat' or fur == 'white':
    print('猫か白い毛の動物')
console
猫か白い毛の動物
論理値A 論理値B 論理値
True True True
True False True
False True True
False False False

any

any.py
# any
pet = 'rabbit'
fur = 'white'

if any((pet == 'cat',fur == 'white')):
    print('猫か白い毛の動物')
else:
    print('猫でもなく白い毛の動物でもない')

if any((pet == 'cat',fur == 'black')):
    print('猫か黒い毛の動物')
else:
    print('猫でもなく黒い毛の動物でもない')
console
猫か白い毛の動物
猫でもなく黒い毛の動物でもない
条件 論理値
1つ以上論理値がTrue True
すべて論理値がFalse False

変数の論理演算結果

behavior.py
# NoneはFlase判定
var = None
print(var)

if var:
    print('true判定')
else:
    print('false判定')


# TrueはTrue判定
var = True
print(var)

if var:
    print('true判定')
else:
    print('false判定')


# FalseはFalse判定
var = False
print(var)

if var:
    print('true判定')
else:
    print('false判定')


# 0はFalse判定
var = 0
print(var)

if var:
    print('true判定')
else:
    print('false判定')


# 0以外の数値はTrue判定
var = 1
print(var)

if var:
    print('true判定')
else:
    print('false判定')


# 空のリストはFalse判定
var = []
print(var)

if var:
    print('true判定')
else:
    print('false判定')


# 要素のあるリストはTrue判定
var = [1]
print(var)

if var:
    print('true判定')
else:
    print('false判定')


# 空のディクショナリはFalse判定
var = {}
print(var)

if var:
    print('true判定')
else:
    print('false判定')


# 要素のあるディクショナリはTrue判定
var = {'key1':'val1'}
print(var)

if var:
    print('true判定')
else:
    print('false判定')


# 空のタプルはFalse判定
var = ()
print(var)

if var:
    print('true判定')
else:
    print('false判定')


# 要素のあるタプルはTrue判定
var = ('1','2','3')
print(var)

if var:
    print('true判定')
else:
    print('false判定')


# 空のセットはFalse判定
var = set()
print(var)

if var:
    print('true判定')
else:
    print('false判定')


# 要素のあるセットはTrue判定
var = {'a','b','c'}
print(var)

if var:
    print('true判定')
else:
    print('false判定')
console
None
false判定
True
true判定
False
false判定
0
false判定
1
true判定
[]
false判定
[1]
true判定
{}
false判定
{'key1': 'val1'}
true判定
()
false判定
('1', '2', '3')
true判定
set()
false判定
{'a', 'b', 'c'}
true判定
記号 意味

比較演算子

comparisonOperator.py
# 比較演算子
val = 99

if val <= 30:
    print('30以下')

elif val < 50:
    print('30を超えて50未満')

elif val >= 100:
    print('100以上')

elif val > 80:
    print('80を超えて100未満')

elif val == 50:
    print('50')

else:
    print('それ以外(50を超えて80以下)')


val = 1

if val != 5:
    print('5以外')


if not val == 1:
    print('1以外')


console
80を超えて100未満
5以外
比較演算子 A<B A=B A>B
== False True False
< True False False
<= True True False
> False False True
>= False True True
!= True False True

if

if

if.py
# if
pet = 'cat'

if pet == 'cat':
    print('')
console
記号 意味

if/elif/else

if-elif-else.py
# if/elif/else
pet = 'dog'

if pet == 'cat':
    print('')

elif pet == 'dog':
    print('')

elif pet == 'rabbit':
    print('うさぎ')

else:
    print('それ以外')
console
記号 意味

構文のみ(コピペ用)

if-elif-else.py
if :

elif :

else:

if-elif-else.py
if all((,)):

elif all((,)):

else:

if-elif-else.py
if any((,)):

elif any((,)):

else:

for

range

for-range.py
for i in range(11):
    print(i)

for i in range(2,11):
    print(i)

for i in range(2,11,2):
    print(i)

for _ in range(3):
    print('A')
console
0
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
2
4
6
8
10
A
A
A
記号 意味
range(num1) 0から(num1-1)繰り返す
range(num1,num2) num1から(num2-1)繰り返す
range(num1,num2,num3) num1から(num2-1)まで(num3)ごとに繰り返す
  • rangeが出力する数値を使わない(ループ回数の制御のみ)場合は変数の代わりに_を指定することができる

range/continue/break/else

for-range-continue-break-else.py
for i in range(10):
    if i == 3:
        continue
    print(i)
else:
    print('else実行')

for i in range(10):
    if i == 3:
        break
    print(i)
else:
    print('else実行')
console
0
1
2
4
5
6
7
8
9
else実行
0
1
2
コマンド 意味
continue 処理を中断して次のループに移る
break 処理を中断してループを抜ける
else ループの終了時に実行する(breakで中断した場合は実行しない)

list

for-list.py
list1 = ['cat','dog','rabbit']

for member in list1:
    print(member)
console
cat
dog
rabbit
記号 意味

tuple

for-tuple.py
tuple1 = ('cat','dog','rabbit')

for member in tuple1:
    print(member)
console
cat
dog
rabbit
記号 意味

dictionary

for-dictionary.py
dict1 = {'type':'cat','fur':'white','gender':'male'}

for k in dict1:
    print(k,dict1.get(k))
console
type cat
fur white
gender male
記号 意味

構文のみ(コピペ用)

for-range-continue-break-else.py
for i in range():

else:

while

while

while.py
str1 = ''

while len(str1) < 10:
    str1 += 'a'
    print(str1)
console
a
aa
aaa
aaaa
aaaaa
aaaaaa
aaaaaaa
aaaaaaaa
aaaaaaaaa
aaaaaaaaaa
記号 意味

while/continue/break/else

while-continue-break-else.py
str1 = ''
str2 = 'a'

while len(str1) < 10:
    if str1 == 'aaaaa':
        str1 += 'z'
        str2 = 'b'
        print(str1)
        continue
    str1 += str2
    print(str1)
else:
    print('else実行')


str1 = ''
while len(str1) < 10:
    str1 += 'a'
    print(str1)

    if str1 == 'aaaaa':
        break
else:
    print('else実行')
console
a
aa
aaa
aaaa
aaaaa
aaaaaz
aaaaazb
aaaaazbb
aaaaazbbb
aaaaazbbbb
else実行
a
aa
aaa
aaaa
aaaaa
コマンド 意味
continue 処理を中断して次のループに移る
break 処理を中断してループを抜ける
else ループの終了時に実行する(breakで中断した場合は実行しない)

セイウチ演算子

walrusOperator.py
str1 = 'aaaaaa'

if (str1len := len(str1)) > 5:
    print(f'文字列は{str1len}文字')
else:
    print('文字列が短すぎます')


num1 = 0

while(num1 := num1 + 1) < 10:
    print(num1)
console
文字列は6文字
1
2
3
4
5
6
7
8
9
  • 変数の代入と使用を同時にできる(assign value to and use a variable at once)

try(例外処理)

try-exception

try-exception.py
try:
    a = 10 / 0
except Exception as e:
    print(e,type(e))

print('処理が完了しました')
console
division by zero <class 'ZeroDivisionError'>
処理が完了しました
記号 意味

try-exception-else-finally

try-exception-else-finally.py
list1 = ['a','b','c']

for i in range(4):
    try:
        if i == 0:
            print(f'{5/0}')
        elif i == 1:
            print(list1[3])
        elif i == 2:
            list1.noExsistMehtod()
        else:
            print('エラーのない処理')

    # エラーの種類によって処理を分岐できる
    except ZeroDivisionError as e:
        import traceback
        traceback.print_exc()
        print(e,type(e))

    except IndexError as e:
        import traceback
        traceback.print_exc()
        print(e,type(e))

    except AttributeError as e:
        import traceback
        traceback.print_exc()
        print(e,type(e))

    # 例外が発生しない場合実行される
    # else内で例外が発生した場合は、例外を処理できない
    else:
        print('else処理')
        
    # 例外の有無に関わらず必ず実行される
    finally:
        print('finally処理')

    print('----------')
print('処理が完了しました')
console
try-exception-else-finally.py
Traceback (most recent call last):
  File "try-exception-else-finally.py", line 6, in <module>
    print(f'{5/0}')
ZeroDivisionError: division by zero
division by zero <class 'ZeroDivisionError'>
finally処理
----------
Traceback (most recent call last):
  File "try-exception-else-finally.py", line 8, in <module>
    print(list1[3])
IndexError: list index out of range
list index out of range <class 'IndexError'>
finally処理
----------
Traceback (most recent call last):
  File "try-exception-else-finally.py", line 10, in <module>
    list1.noExsistMehtod()
AttributeError: 'list' object has no attribute 'noExsistMehtod'
'list' object has no attribute 'noExsistMehtod' <class 'AttributeError'>
finally処理
----------
エラーのない処理
else処理
finally処理
----------
処理が完了しました
説明
try 例外が発生する可能性のあるプログラムを書く
except 例外が発生した時のプログラムを書く
else try内で例外が発生しなかったときに実行するプログラムを書く
finally 例外の発生の有無に関わらず最後に実行するプログラムを書く

raise

try-raise.py
try:
    raise IndexError('例外を発生させました')

except Exception as e:
    print(e,type(e))
console
例外を発生させました <class 'IndexError'>
意味
raise 例外を発生させる

構文のみ(コピペ用)

try-exception-else-finally.py
try:

except:

except ZeroDivisionError as e:

except IndexError as e:

except AttributeError as e:

else:
        
finally:

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?