0
1

Pythonの便利技と注意点:変数編

Last updated at Posted at 2022-08-25

目次に戻る

予約語・キーワード

ここに挙げた単語は変数として使ってはいけない
False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield

一連の値を、各単独の変数に格納

数字
>>> num_val = 1, 2, 3
>>> num_val
(1, 2, 3)
>>> one, two, three = num_val
>>> one
1
>>> two
2
>>> three
3
文字
>>> str_val = list('abc')
>>> str_val
['a', 'b', 'c']
>>> x, y, z = str_val
>>> x
'a'
>>> y
'b'
>>> z
'c'
辞書のキーと値
>>> macdo = {'ハンバーガー':200, 'ポテト':150, 'コーラ':100}
>>> メニュー, 金額 = macdo.popitem()
>>> メニュー
'コーラ'
>>> 金額
100
左辺・右辺の数が合わないとエラー
[左辺が少ない場合]
>>> a, b = 1, 2, 3
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    a, b = 1, 2, 3
ValueError: too many values to unpack (expected 2)

[右辺が少ない場合]
>>> a, b, c = 1, 2
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    a, b, c = 1, 2
ValueError: not enough values to unpack (expected 3, got 2)
*を使うと代入する方が多くても残り全て引き取ってくれる
[最初の*変数が引き取るパターン]
>>> waza = "スーパー・ウルトラ・グレート・デリシャス・ワンダフル・ボンバー"
>>> *fst, snd, trd = waza.split("")
>>> fst
['スーパー', 'ウルトラ', 'グレート', 'デリシャス']
>>> snd
'ワンダフル'
>>> trd
'ボンバー'

[真ん中の*変数が引き取るパターン]
>>> waza = "スーパー・ウルトラ・グレート・デリシャス・ワンダフル・ボンバー"
>>> fst, *snd, trd = waza.split("")
>>> fst
'スーパー'
>>> snd
['ウルトラ', 'グレート', 'デリシャス', 'ワンダフル']
>>> trd
'ボンバー'

[最後の*変数が引き取るパターン]
>>> waza = "スーパー・ウルトラ・グレート・デリシャス・ワンダフル・ボンバー"
>>> fst, snd, *trd = waza.split("")
>>> fst
'スーパー'
>>> snd
'ウルトラ'
>>> trd
['グレート', 'デリシャス', 'ワンダフル', 'ボンバー']
*をつけた変数は、例え1文字であってもリストになる
>>> x, *y, z = "123"
>>> a, y, z
(1, ['2'], '3')

==とisの違い

==は値を比較する
>>> x = y = [1, 2, 3]
>>> z = [1, 2, 3]
>>> x == y
True
>>> x == z
True
zは同じ値をもつだけであり、同一のリストを参照しているのではない
>>> x is y
True
>>> x is z
False

関数内からグローバル変数を書き換える

関数内でglobalをつけて再宣言すると関数の中からglobal変数にアクセスできる
drink = 'orange juice'
print('関数実行前:', drink)
def example_func():
    global drink
    drink = 'cola'
    print('関数内:', drink)

example_func()
print('関数実行後:', drink)
==========================
# 出力結果
関数実行前: orange juice
関数内: cola
関数実行後: cola
globalをつけずに宣言すると、同じ変数名でも別の変数を作り出している
drink = 'orange juice'
print('関数実行前:', drink)
def example_func():
    drink = 'cola'
    print('関数内:', drink)

example_func()
print('関数実行後:', drink)
==========================
# 出力結果
関数実行前: orange juice
関数内: cola
関数実行後: orange juice

目次に戻る

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