Test Your Knowledge: Quiz

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

    >>> X = 'Spam'
    >>> def func():
            print(X)
    
    >>> func()
    
  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.X, 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.