Python 模擬試験

Python基礎 模擬試験 第1回 問32・9章 クラス(スコープと名前空間)

nonlocal

次のコードを実行したときの出力として、正しいものを1つ選べ。

def scope_test():
    def do_local():
        spam = "local"
    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal"
    spam = "test"
    do_local()
    print(spam)
    do_nonlocal()
    print(spam)

scope_test()
  1. A

    local nonlocal(この順に1行ずつ)

  2. B

    test nonlocal(この順に1行ずつ)

  3. C

    test test(この順に1行ずつ)

  4. D

    NameError が発生する。

正解と解説を見る

正解:B

関数の中の代入はその関数のローカル変数を作り、nonlocal を宣言すると外側の関数の変数を変更できる。

順実行する行実行後の変数
1`def scope_test():`—
2`scope_test()`—
3└ `def do_local():`—
4└ `def do_nonlocal():`—
5└ `spam = "test"`spam = 'test'
6└ `do_local()`—
7└ `spam = "local"`spam = 'local'
8└ `print(spam)`spam = 'test'
9└ `do_nonlocal()`—
10└ `nonlocal spam`spam = 'test'
11└ `spam = "nonlocal"`spam = 'nonlocal'
12└ `print(spam)`spam = 'nonlocal'
結果実際の出力test / nonlocal

学習のポイント:ローカル・nonlocal・global の違いを押さえる。

この問題を演習で解く →

問題一覧へ

このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。