Python "Learning Modules" Midterm 1 Exam Sample Problems

From Knowledge Kitchen
Jump to navigation Jump to search


Topics review

Basic computer concepts

  • Desktop metaphor, paper paradigm
  • Files and directories/folders
  • File naming conventions
  • File name extensions
  • Binary code!

Programming concepts

  • Variables, literals
  • Expressions, statements
  • Assignment
  • Operators
  • Comments

Errors

  • syntax
  • runtime
  • semantic/logic

Data types

  • Int
  • Float
  • String
  • Boolean
  • Ranges (essentially lists)
  • Converting from one data type to another

Control structures

  • If/elif/else
  • For loops
  • While loops

Common design patterns

  • accumulator
  • flag

Boolean logic

  • Boolean logic operators
  • Boolean comparison operators
  • Truth tables for "and", "or", and "not"

Standard input

  • inputting text from keyboard
  • checking whether numeric before converting to int
  • validating user input

Standard output

  • Printing output to console
  • One argument or multiple arguments to print
  • Using the sep and end arguments to customize output
  • Formatting output

Strings

  • String literals
  • Concatenation
  • Calculating string length
  • Converting to uppercase or lowercase
  • Checking whether they contain only numbers
  • Escape characters


Extra problem sets

In addition, here are a few sample problems that you can try in addition to the usual materials for studying. Solutions are posted below.

Evaluate expressions

Evaluate the following expressions and note the data type of the result:

Expression Evaluates To Data Type
5 * 2
5 ** 2
'5' + '2'
'5' * 2
5 / 2
5 // 2
5 % 2
5 + 2.0
5.0 * 2.0
10 > 2
2 < 1
2 != 4
4 == 2**2
'cat' < 'dog'
'Cat' < 'dog'
5 > 2 and 10 > 11
5 > 2 or 10 > 11
5 > 2 and not (10 > 11)
str.lower('HeLLo')
str.upper('HeLLo')
format(5.1, '.2f')
format(5.1, '>10.2f')
random.randint(1,5)
len('cat')
len('cat' + 'dog')
not (5>2 and 5 < 4)

Short Answers

  1. Explain what a Boolean expression is and why you would use one while programming. Give three examples.
  2. Identify three functions that convert data from one data type to another. Provide a practical example of each function and describe when you would use it in an actual program.
  3. Explain the differences and simliarities between the "if" statement and a "while" statement in Python
  4. Name and describe three different data types in Python and when they could be used in a program
  5. Imagine you have the following while loop: keepgoing = "yes"
while keepgoing == "yes":
   # statements go here Describe two different ways to stop this loop from iterating?


Trace the output

Program #1

a = 10
b = 20
c = 30

if c > b + a:
    print ("N\nY\nU\n")

else:
    if b + a >= c:
        print ("C\nO\nU\nR\nA\nN\nT\n")
    else:
        print ("S\nT\nE\nR\nN\n")

print (a,b,c)

Program #2

x = 'cupid'
z = 'arrow'

if x < z:
    t = x
    x = z
    z = t

v = x + " <--> " + z

if ( ( (5 + 2 >= 6.0) and (1.0 < 0.5) ) or True):
    print (x,z,v, sep='\t')
else:
    print (v,z,x, sep='\n')

Program #3

a = 5
b = 10
c = 25

if a + b == c:
    print ("X1")
else:
    if c == a + b*2:
        print ("Y1")
    elif a == c - 2 * b:
        print ("Y2")
    else:
        print ("Y3")


count = 0

while count < 10:
    print ('Hello')
    count += 1


x = 10
y = 0

while x > y:
    print (x, y)
    x = x - 1
    y = y + 1


keepgoing = True
x = 100

while keepgoing:
    print (x)
    x = x - 10
    if x < 50:
        keepgoing = False
x = 0
while True:
    x += 1
    print (x)
    if x ** 2 > 36:
       break
    elif x % 2 == 0:
        continue
        
    print ("looping!")


Program #4

a = 5
b = 6
c = 20
d = 24

if a < b and b * 2 < c:

    print ("Python Case 1")
    print ("A", '\t', "B", '\t', "C")
    
    if a * 2 == c:
        print (a*2, '\t', a*2, '\t', a*2)
    elif a * 3 == c:
        print (a*3, '\t', a*3, '\t', a*3)
    elif a * 4 == c:
        print (a*4, '\t', a*4, '\t', a*4)
    else:
        print ('?', '\t', '?', '\t', '?')
        
else:

    print ("Python Case 2")
    print ("a", '\t', "b", '\t', "c")
    
    if b * 2 == d:
        print (b*2, '\t', b*2, '\t', b*2)
    elif b * 3 == d:
        print (b*3, '\t', b*3, '\t', b*3)
    elif b * 4 == d:
        print (b*4, '\t', b*4, '\t', b*4)
    else:
        print ('?', '\t', '?', '\t', '?')


Write a program

Use your programming skills to solve the following programming challenges (solutions are below):

  1. Write a program that asks the user to supply two words. Sort the words in alphabetical order and print them back to the user.
  2. Write a program that asks the user to supply two words. Sort the words in size order and print them back to the user.
  3. Write a program that has the computer virtually roll two 6 sided dice. Output the result as follows: Virtual dice roll: 3 and 5
  4. Write a program that asks the user to enter in number. Then have the computer generate a random number and compare the result. If the numbers are the same print out a "You Win!" message. If not, print out a "Try Again" message.
  5. Write a program that qualfies the user for a particular credit card. Users must meet the following criteria:
    • Make at least 30,000 per yeay
    • Their rent payment must not be more than 5% of their total salary per month (i.e. 1,500 is the max rent that they can pay while making 30,000 per year)
    • However, if they own their home you do not need to take their monthly house payment into accountHere is a sample running of the program: Credit card qualifier
How much do you make per year? 30000
Do you own your home? (y/n) y
You qualify!



Credit card qualifier
How much do you make per year? 35000
Do you own your home? (y/n) n
How much do you pay in rent per month? 1000
You qualify!



Credit card qualifier
How much do you make per year? 50000
Do you own your home? (y/n) n
How much do you pay in rent per month? 5000
Sorry, you don't qualify. Your rent is too high
  1. Write a program to ask a user to enter in 3 test scores (0-100) and 1 homework score (0-100). Then calculate the user's grade using the following formula ' Tests: 50% Homework: 50%. You can assume the user will enter integer values. Print out the grade as a number (i.e. 78.56%) along with its letter equivalent (i.e. 'C'). For the purposes of this program you can assume that A = 90-100, B = 80-89.99, C = 70-79.99, D = 65-69.99 and F is less than 65
  2. A company has determined that its annual profit is typically 23 percent of total sales. Write a program that asks the user to enter in the projected amount of total sales and then displays the profit that will be made from that amount.
  3. One acre of land is equivalent to 43,560 square feet. Write a program that asks the user to enter the total square feet in a tract of land and calculate the number of acres in that tract.
  4. A customer in a store is purchasing 5 items. Write a program that asks for the price of each item, and then displays the subtotal of the sale, the amount of sales tax, and the total. Assume the sales tax is 6 percent.
  5. Write a program to input a 2 digit integer, call it x, where the rightmost digit is nonzero. Compute the integer y which has the same digits as x, but in reverse order. Print out x, y and x+y. For example: Please enter a two digit integer: 23
23 reversed is: 32 
23 + 32 is 55
  1. Write a program that prints out all numbers between 1 and 100
    1. Extension #1: write a program that prints out all EVEN numbers between 1 and 100
    2. Extension #2: write a program that prints out all ODD numbers between 1 and 100
    3. Extension #3: write a program that asks the user to indicate whether they want to see even or odd numbers. Then display the even or odd numbers between 1 and 100 based on their choice. Note: the user many not supply a valid choice! You will need to re-prompt them if necessary. Here's a sample running of the program: Enter "even" or "odd": apple
Sorry, that's not a valid choice!
Enter "even" or "odd": odd

Here we go!

1 3 5 ... 95 97 99
  1. Write a program that continually asks the user for a series of prices. Keep track of the running total as the user enters prices. Prompt the user after each price to see if they wish to continue entering prices. When they are finished, print out the total amount entered.
  2. Write a program that asks the user to guess a secret number (5). If the user guesses the number you can congratulate them. If they don't guess it you should tell them if they need to guess higher or lower, and prompt them to enter another number. Sample Running: Enter a number: 3
Too low! Try again!
Enter a number: 6
Too high! Try again!
Enter a number: 5
Congratulations!  You guessed it!
  1. Write a program that generates a series of lucky numbers for the user. The user will enter the number of numbers they want and your program should generate that number of lucky values (random numbers between 1 and 100). The user will always enter an integer, but your program should only accept positive values. Here's a sample running of the program: Lucky number generator!
How many digits do you want? -5
Invalid entry, try again
How many digits do you want?  3

Here we go!

9  75  34
  1. Write a program that uses a while loop to generate the following output. Format your output using the format function. Number Number * 2
0          0
1          2
2          4
3          6
4          8
5          10
6          12
7          14
8          16
9          18
  1. Analyze the code below and identify any problems or issues that might exist. Offer suggestions on how to re-engineer the code to prevent these errors from occurring and/or rewrite the code so that it functions correctly. rate = str(input("How much do you make per hour? '))
hours = input("How many hours did you work this week? ")

if hours < 40:
   pay = rate * hours
if hours > 40
   pay = rate * 40
   ot_pay = (hours-40) ** (rate*1.5)

print ("Your total pay is, pay + ot_pay")
  1. Write a program that lets the user figure out how many items they can purchase at a local coffee shop. Begin by asking the user to enter in amount of money as a float. Then ask the user to select a product from a pre-determined list. Figure out how many items the user can purchase, noting that the coffee shop does not sell fractional amounts (i.e. you can't buy half a donut) How much money do you have?: 10.00
What would you like to buy?
Donut  (d) ' 1.50
Coffee (c) ' 1.00
Bagel  (b) ' 2.50
Scone  (s) ' 2.75

Enter your choice (d/c/b/s): d

You can purchase 6 donuts with $ 10.0 Note that you cannot assume that the user will enter a valid product (i.e. they could type in the string "donut" instead of the string "d"). In this case you will need to present the user with some kind of error (i.e. "Sorry, that's not a valid product") ' you do not need to re-prompt them (you can just end the program). Also, you can assume that the user will input valid floating-point numbers when prompted.
  1. Write a "calculator" program that asks the user for two numbers as well as an "operation code" ("a" for add, "s" for subtract, "d" for divide or "m" for multiply). Using the information provided perform the specified operation and print the result. Here is a sample running of the program: Number 1: 2.0
Number 2: 3.0
Operation (a/s/d/m): add
Invalid operation! Try again.
Operation (a/s/d/m): a

2.0 + 3.0 = 5.0   Note that you cannot assume that the user will enter a valid operation code (i.e. they could type in the string "multiply" instead of the string "m"). In this case you will need to present the user with some kind of error (i.e. "Sorry, that's not a valid operation code") and re-prompt them. However, you can assume that the user will input valid floating-point numbers when prompted. Also note that dividing a number by 0 will result in a runtime error. Prevent this from happening in your program by providing special output in this case (i.e. 5.0 / 0.0 = undefined)
  1. A small college has asked you to write a program for their admissions department to help them determine if a student should be accepted into their school. Write a program that uses the following criteria to determine whether a given applicant should be admitted:
    • Combined SAT score of 1600 or more
    • A high school GPA of 3.0 or higher
    • At least 3 extracurricular activities However, this particular school places a heavy emphasis on extracurricular activities, so students with 5 or more activities only need a 1400 combined score on their SAT and a GPA of 2.8. Comment your code as necessary. You can assume that the user will enter floating-point values. Here is a sample running of your program. Note that you should ask the user if they want to repeat the process for additional students when you are finished. Student name: Craig Combined SAT Score: 1800 High school GPA: 3.2 # of extracurricular activities: 3 Craig should be admitted! Another student? yes Student name: John Combined SAT Score: 1500 High school GPA: 3.1 # of extracurricular activities: 7 John should be admitted! Another student? yes Student name: Chris Combined SAT Score: 1300 High school GPA: 2.9 # of extracurricular activities: 8 Chris should not be admitted. Another student? no


Solutions

The solutions to the problem sets above:

Evaluate expressions

Expression Evaluates To Data Type
5 ' 2 3 integer
5 ** 2 25 integer
'5' + '2' 52 string
'5' * 2 55 string
5 / 2 2.5 float
5 // 2 2 integer
5 % 2 1 integer
5 + 2.0 7.0 float
5.0 * 2.0 10.0 float
10 > 2 True Boolean
2 < 1 False Boolean
2 != 4 True Boolean
4 == 2**2 True Boolean
'cat' < 'dog' True Boolean
'Cat' < 'dog' True Boolean
5 > 2 and 10 > 11 False Boolean
5 > 2 or 10 > 11 True Boolean
5 > 2 and not (10 > 11) True Boolean
str.lower('HeLLo') hello string
str.upper('HeLLo') HELLO string
format(5.1, '.2f') 5.10 string
format(5.1, '>10.2f')
"      5.10"
string
random.randint(1,5) 3 integer
len('cat') 3 integer
len('cat' + 'dog') 6 integer
not (5>2 and 5 < 4) True Boolean


Short Answers

Explain what a Boolean expression is and why you would use one while programming. Give three examples.

A Boolean expression is an expression that compares two or more values. It almost always involves the use a relational operator (>, <, ==, !=, etc) and always evaluates to True or False. We use Boolean expressions in Python to ask a question (i.e. if number < 0 then print "no negative numbers allowed!"), to control a repetition structure (i.e. while keepgoing == True, perform some operation) and to store a logical value in a variable (i.e. answer = 5 > 2)

Identify three functions that convert data from one data type to another. Provide a practical example of each function and describe when you would use it in an actual program.

The float(), int() and str() functions convert data from one data type to another. Here are a few examples:

# turn the user's input into a floating point number
 answer = float(input("Enter a number: "))
 
 # turn a String into an integer
 a = "525"
 b = int(a)
 
 # convert a number into a String
 a = 525
 b = str(a)

Explain the differences and simliarities between the "if" statement and a "while" statement in Python

Both an "if" statement and a "while" statement utilize Boolean expressions. In the case of an "if" statement, if the attached Boolean expression evaluates to True then the body of the "if" statement will execute one time. In the case of a "while" statement, if the attached Boolean experession evalutes to True then the body of the "while" statement will execute, and then the condition will be re-evaluated at the end of the statement to see if it is still True - if so the body of the "while" statement will be executed again.

Name and describe three different data types in Python and when they could be used in a program

Integer: used to store whole number values. Useful for creating "counter" accumulator variables. Float: used to store floating point numbers. Useful for storing currency values. String: used to store sequences of characters, such as "Hello, World!"

Imagine you have the following while loop. Describe two different ways to stop this loop from iterating.

keepgoing = "yes"
while keepgoing == "yes":
   # statements go here

You could call the "break" statement from within the loop or you could flip the value of "keepgoing" to something other than "yes"


Trace the output

(just copy and paste the code into IDLE to see the output!)


Programming Problems

Problem #1

word1 = input("Word 1: ")
word2 = input("Word 2: ")

if word1 > word2:
    print (word2, word1)

else:
    print (word1, word2)

Problem #2

word1 = input("Word 1: ")
word2 = input("Word 2: ")


if len(word1) > len(word2):
    print (word2, word1)

else:
    print (word1, word2)

Problem #3

import random

die1 = random.randint(1,6)
die2 = random.randint(1,6)

print ("Virtual dice roll:", die1, "and", die2)

Problem #4

import random

usernum = int(input("Enter an integer (1-6): "))
compnum = random.randint(1,6)

if usernum == compnum:
    print ("you win!")

else:
    print ("try again!")

Problem #5

'''''print ("Credit card qualifier")
salary = int(input("How much do you make per year? "))
own = input("Do you own your home? (y/n) ")

if own == 'y':
    if salary >= 30000:
        print ("You qualify!")
    else:
        print ("You don't qualify.  You need to make at least 30,000 per year and own your home.")

else:
    if salary < 30000:
        print ("You don't qualify.  You need to make at least 30,000 per year and own your home.")
    else:        
        rent = int(input("How much do you pay in rent per month? "))

        if rent > 0.05 * salary:
            print ("Sorry, you don't qualify.  Your rent is too high")
        else:
            print ("You qualify!")

Problem #6

test1 = float(input("Test 1: "))
 test2 = float(input("Test 2: "))
 test3 = float(input("Test 3: "))
 homework = float(input("Homework: "))
 
 test_avg = (test1 + test2 + test3) / 3
 class_avg = (test_avg + homework) / 2
 
 print ("Class average:", format(class_avg, '.2f'))
 print ("Letter Grade: ", end='')
 
 if class_avg > 90:
     print ("A")
 
 elif class_avg > 80:
     print ("B")
 
 elif class_avg > 70:
     print ("C")
 
 elif class_avg > 65:
     print ("D")
 
 else:
     print ("F")

Problem #7

# get sales
 sales = float(input("Sales: "))
 
 # calc profit
 profit = 0.23 * sales
 
 # output
 print ("Projected profit:", profit)

Problem #8

# get square feet
 square_feet = int(input("Square feet: "))
 
 # convert to acres
 acres = square_feet / 43560
 
 # output
 print ("In acres:", acres)

Problem #9

# get 5 prices
 p1 = float(input("Price 1: "))
 p2 = float(input("Price 2: "))
 p3 = float(input("Price 3: "))
 p4 = float(input("Price 4: "))
 p5 = float(input("Price 5: "))
 
 # calc subtotal
 subtotal = p1+p2+p3+p4+p5
 
 # calc tax
 tax = 0.06 * subtotal
 
 # output
 print ("Subtotal:", subtotal)
 print ("Tax:", tax)
 print ("Total:", subtotal+tax)

Problem #10

# get 2 digit integer
 num = int(input("Number: "))
 
 # extract tens and ones
 tens = num // 10
 ones = num % 10
 
 # construct the reversed number
 rev = ones*10 + tens*1
 
 # output
 print (num, "reversed is:", rev)
 
 print (num, "+", rev, "is", num+rev)

Problem #11

counter = 1
while counter <= 100:
    print (counter, " ", end="")
    counter += 1

Problem #11 Extension #1

counter = 1
while counter <= 100:
    if counter % 2 == 0:
        print (counter, " ", end="")
    counter += 1

Problem #11 Extension #3

while True:
    choice = input("Enter \"even\" or \"odd\": ")

    if choice == "even" or choice == "odd":
        break
    else:
        print ("Sorry, that's not a valid choice!")


if choice == "even":
    counter = 2

    while counter <= 100:
        print (counter, " ", end="")
        counter += 2

if choice == "odd":
    counter = 1

    while counter <= 100:
        print (counter, " ", end="")
        counter += 2

Problem #12

total = 0

keepgoing = "yes"
while keepgoing == "yes":
    price = float(input("Enter a price value: "))
    total += price
    keepgoing = input("Go again? ")

print ("Total is", total)

Problem #13

secret = 5

while True:
    guess = int(input("Guess a number between 1 and 10: "))

    if guess == secret:
        print ("Congrats!")
        break
    elif guess < secret:
        print ("Too low")
    else:
        print ("Too high")

Problem #14

import random

while True:
    numdigits = int(input("Enter a number of digits, positive numbers only: "))
    if numdigits < 1:
        print ("Try again!")
    else:
        break

counter = 1
while counter <= numdigits:
    print (random.randint(1, 100), " ", end="")
    counter += 1

Problem #15

print (format("Number", "<10s"), format("Number*2", "<10s"))

counter = 0
while counter < 10:
    print (format(counter, "<10d"), format(counter*2, "<10d"))
    counter += 1

Problem #16

rate = float(input("How much do you make per hour? "))
hours = float(input("How many hours did you work this week? "))

if hours < 40:
    pay = rate * hours
else:
    ot_pay = (hours-40) * (rate*1.5)
    pay = rate * 40 + ot_pay

print ("Your total pay is", pay)

Problem #17

# get money from the user
 money = float(input("How much money do you have?: "))
 
 print ("What would you like to buy?")
 print ("Donut  (d) ' 1.50")
 print ("Coffee (c) ' 1.00")
 print ("Bagel  (b) ' 2.50")
 print ("Scone  (s) ' 2.75")
 
 # get user choice
 choice = input("Enter your choice (d/c/b/s): ")
 
 # evaluate choice
 if choice == 'd':
 
     # note -- the // operator performs integer division and generates the
     # integer result of a division operation.  HOWEVER, both money and the value
     # 1.5 are floats!  Remember what happens when you have a math expression with
     # floating point numbers.  the integer division operator will generate an integer,
     # but Python will cast the result as a float (essentially adding .0 to the integer)
     # casting the result as an int using the int() function fixes this
     print ("You can purchase", int(money//1.5), "donuts with", money)
 
 elif choice == 'c':
     print ("You can purchase", int(money//1.0), "cups of coffee with", money)
 elif choice == 'b':
     print ("You can purchase", int(money//1.0), "bagels with", money)
 elif choice == 's':
     print ("You can purchase", int(money//1.0), "scones with", money)
 else:
     print ("Sorry, we don't sell that!")

Problem #18

# get two numbers
 n1 = float(input("Number: "))
 n2 = float(input("number: "))
 
 # get an operation code, making sure to validate the data
 # (keep the user "caught" until they supply a good value)
 while True:
     op = input("Operation code (a/s/m/d): ")
     if op == 'a' or op == 's' or op == 'm' or op == 'd':
         break
     else:
         print ("Bad, try again")
 
 # evaluate operation
 if op == 'a':
     print (n1, "+", n2, "=", n1+n2)
 elif op == 's':
     print (n1, "-", n2, "=", n1-n2)
 elif op == 'm':
     print (n1, "*", n2, "=", n1*n2)
 elif op == 'd':
 
     # make sure we don't crash if denom is 0
     if n2 == 0:
         print (n1, "/", n2, "=", "undefined")
     else:
         print (n1, "/", n2, "=", n1/n2)
         

Problem #19

# continually ask the user for input
 while True:
 
     # get info
     name = input("Student name: ")
     sat  = float(input("SAT score: "))
     gpa  = float(input("GPA: "))
     act  = float(input("# of activities: "))
 
     # evaluate - normal admission
     if sat >= 1600 and gpa >= 3.0 and act >= 3:
         print (name, "should be admitted")
     elif act >= 5 and sat >= 1400 and gpa >= 2.8:
         print (name, "should be admitted")
     else:
         print (name, "should not be admitted")
 
     # keep going?
     again = input("Enter another student? ")
     if again == "no":
         break