Lihan's

A python quiz

Posted by: lihan on: October 2, 2011

Python 2.5 is relatively recent and not supported everywhere yet, so it’s important to understand the behavior of both Python 2.5 and earlier versions.

This quiz is cited from here.

  1. (a) What number does the following code print?
    adders = []
    for i in range(0, 100):
        adders.append(lambda x: x+i)
    
    print adders[17](42)

    (b) What about the following similar-looking code?

    adders = [lambda x: x+i for i in range(0, 100)]
    print adders[17](42)
  2. (pre-Python 2.5 only) What does the following code print? Partial credit for approximately correct answers. (Hint: the function that exits a program is called sys.exit.)
    try:
        exit(0)
    except Exception, e:
        print e
  3. What number does the following code print?
    units = [1, 2]
    tens = [10, 20]
    nums = (a + b for a in units for b in tens)
    units = [3, 4]
    tens = [30, 40]
    print nums.next()
  4. Which of these lines produce the same output?
    print "word" in [] == False
    print ("word" in []) == False
    print "word" in ([] == False)

    Answer
    1. (a) 141
       (b) 141
    2. 'str' object is not callable
    3. 31
    4. None of them

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>