Sample Midterm 2

  1. Evaluate each expression. If any cannot be evaluated, say why.
    1. 3 + 5.0
    2. "hello" + "goodbye"
    3. 7 * True
    4. 6 / "spam"
    5. True and not False or True
    6. "monty" <= "python"
  2. Convert the following into Python:
    1. “hello” follows “goodbye” in the character ordering of the computer
    2. The value of the variable answer is true or the value of the variable y is less than 126
    3. The function gleep is called with an argument of −21
  3. Convert the following into a “for” loop:
    i = 1
    while i < 10:
        print i * "x"
        i += 3
  4. What does the following function do when given a string as the first argument and a string containing only one character as the second argument?
    def f(s, c):
        i = 0
        while i < len(s):
            if s[i] == c:
                return i
            i += 1
        return -1
  5. In the following program:
        x = input("Enter a number: ");
        y = 1 / x;
    except ZeroDivisionError:
        print "Nice try: you divided by 0"
    except SyntaxError:
        print "What on earth did you type?"
    except NameError:
        print "I have no clue what that name refers to"
    except TypeError:
        print "I don't handle conversions well today"
        print "The reciprocal of", x, "is", y;
    please show five different inputs, each of which will execute a different print statement in the program.