MONT 105S, Spring 2009

Home | | Course Schedule | | Assignments | | Lecture Notes

Solutions for Review sheet for midterm

Practice Problems
The following problems are intended to help you study for the exam.

1)Given these boolean variables:

x = true, y = false, z = true
What is the value (true/false) of each of the following?
i)  x and (y or z)

Answer:	True

ii) (not x) or  (not(y and z))

Answer:	True

iii) y or (x and not z)

Answer:	False
2)Write a program that does the following:
Prompt the user to input a number.
Input the number from the keyboard
If the number is less than 100, write:
	XX is a low number.
where XX refers to the number inputted by the user.
Otherwise, write:
	XX is a high number.
Answer:
#Program lowOrHigh.py
number = input("Enter a number: ")
if number < 100:
	print number, "is a low number."
else:
	print number, "is a high number."

3) a) What is the value of sum after the execution of the following code?

	sum = 0
	counter = 1
	while counter < 6:
		sum = sum + 2 * counter
		counter = counter + 1
	print sum
Answer: 30

b) Re-write the above code using a for loop instead of a while loop

	sum = 0
	for counter in range(1, 6):
		sum = sum + 2*counter
	print sum
	

4) What is the output of the following code fragment (mySentence and partial are both strings)?

	mySentence = "It was a dark and stormy night"
	partial = mySentence[10:13]
	print partial	

Answer: ark
5) What is wrong with the following fragments of Python?


6) Consider the following while loop:
	sum = 0
	count = 5
	while count <= 12:
		sum = sum + count
		count = count + 2

a) Fill in the following table for the values of count and sum each time through the loop (there may be more rows than you need in the table):

sumcount
05
57
129
2111
3213

b)Write a for loop that does the equivalent of the above loop.

sum = 0
for count in range(5, 13, 2):
    sum = sum + count

7. Consider the following Python code:

        sum = 0
        for i in range(1, 5):
              sum = sum + i
        print sum

What is value of sum printed on the screen?

Answer: 10

 

 

  8. Fill in/write the necessary code for the following decision tree.

#program catCheck.py
answer = raw_input("Do you have a cat? ")
if answer == "yes":
	answer = raw_input("What kind is it? ")
	if answer == "Siamese":
		print "Good choice!"
	elif answer == "Tiger":
		print "Another good choice."
	elif answer == "Calico":
		print "I have never had that kind."
else:
	print "You should get one."

9. Fill in the necessary code to fill in the depositList list with deposit amounts entered by the user. You should keep track of the sum of all the deposits made, so that the print statement at the end of the program makes sense. You can assume there are exactly 100 deposits made.

#Program deposit.py
sum = 0
depositList = [ ]

for i in range(100):
    deposit = input("Please enter amount of deposit: ")
    depositList.append(deposit)
    sum = sum + deposit
    
print "The sum of the deposits: ", sum