Test Your Knowledge: Quiz

 

 
  1. What is the output of the following code, and why?

    >>> X = 'Spam'
    >>> def func():
    ...     print(X)
    ...
    >>> func()

    广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

  2. What is the output of this code, and why?

    >>> X = 'Spam'
    >>> def func():
    ...     X = 'NI!'
    ...
    >>> func()
    >>> print(X)

  3. What does this code print, and why?

    >>> X = 'Spam'
    >>> def func():
    ...     X = 'NI'
    ...     print(X)
    ...
    >>> func()
    >>> print(X)

  4. What output does this code produce? Why?

    >>> X = 'Spam'
    >>> def func():
    ...     global X
    ...     X = 'NI'
    ...
    >>> func()
    >>> print(X)

  5. What about this code—what’s the output, and why?

    >>> X = 'Spam'
    >>> def func():
    ...     X = 'NI'
    ...     def nested():
    ...         print(X)
    ...     nested()
    ...
    >>> func()
    >>> X

  6. How about this example: what is its output in Python 3.0, and why?

    >>> def func():
    ...     X = 'NI'
    ...     def nested():
    ...         nonlocal X
    ...         X = 'Spam'
    ...     nested()
    ...     print(X)
    ...
    >>> func()

  7. Name three or more ways to retain state information in a Python function.