Here is a quick outline of what will be covered on the Exam.

The solutions to the programming problems are available at the end of this document.

  1. Programming Mechanics
    1. Variables (what are they, creating them, using them, naming rules, etc)
    2. Reading input from the keyboard with the input() function
  2. Math Expressions
    1. Writing math expressions
    2. Evaluating math expressions
    3. Storing & printing the results of math expressions
  3. Data Types
    1. Strings
    2. Numeric data types
      1. Integers (int)
      2. Floating point numbers (float)
    3. The Boolean data type
    4. The List data type
    5. Mixed type expressions
    6. Type conversion (string to int, int to strings, etc)
  4. Basic String Manipulation
    1. Combining two strings (concatenation)
    2. Multiplying a string (x = 'hi' * 5)
    3. Case manipulation (x = str.lower('CRAIG') # converts the string literal 'CRAIG' to 'craig')
    4. Calculating string length using the len() function
  5. Selection Statements
    1. The structure of an IF statement (IF keyword, condition, colon, indentation)
    2. Writing a condition for an IF statement
    3. Boolean operators (<, >, ==, !=, >=, <=)
    4. Comparing numeric values using Boolean expressions
    5. Comparing string values using Boolean expressions
    6. Using the IF-ELSE statement
    7. Nesting decision structures (IF statements inside other IF statements)
    8. The IF-ELIF-ELSE statement
    9. Logical operators (and, or, not)
  6. Condition Controlled Loops (while loops)
    1. mechanics & how they work
    2. setting up conditions for a while loop
    3. infinite loops and how to avoid them
    4. sentinels (defining a value that the user enters that causes the loop to end)
    5. input validation loops (asking the user to continually enter a value until that value matches some condition)
  7. Accumulator variables
    1. setting up and using accumulator variables
    2. self referential assignment statements (i.e. counter = counter + 1)
    3. augmented assignment operators (i.e. counter += 1)
  8. Count Controlled Loops (for loops)
    1. mechanics and how they work
    2. iterating over a list (i.e. for x in [1,2,3,4,5]:)
    3. using the target variable in a for loop
    4. nested loops (i.e. loops inside of other loops)
  9. Lists
    1. Simple Variables vs. Lists (simple variables can only hold one piece of data, but lists can hold multiple values) – you can think of a list like a “book” and a variable like a “sheet of paper”
    2. Defining lists in Python (i.e. mylist = [1,2,3])
    3. Concatenating lists with the “+” operator
    4. Repeating lists with the “*” operator
    5. Referencing list items using index notation (i.e. mylist[0])
    6. Iterating through a list using a “while” loop
    7. Iterating through a list using a “for” loop
    8. Using the len() function to determine the # of items in a list
    9. Updating the value of an item in a list using bracket notation
    10. Creating empty lists
    11. Finding an item in a list using the “in” operator
    12. Adding items to a list using the append method
    13. Sorting items in a list using the sort method
    14. Reversing items in a list using the reverse method
    15. Finding the position of an item in a list using the index method
    16. Inserting an item in a list at a specific index using the insert method
    17. Finding the largest and smallest values in a list using the min and max methods
    18. Totaling the values of all elements in a list using an accumulator variable
    19. Removing an item from a list using the remove method
  10. Strings Manipulation
    1. Iterating through all characters in a string using a for loop
    2. Indexing a specific character in a string using bracket notation
    3. Iterating through all characters in a string using a while loop
    4. String immutability (you can't change a string using bracket notation like you would change a list element)
    5. Testing a string for substrings using the “in” operator
    6. Detecting character types in a string using the built-in string testing methods (isdigit, isalpha, isalnum, islower, isupper, isspace)

Sample Problems

Evaluate the following expressions. Note the data type that gets generated by each expression as well. You can check the solutions to these problems by running them to see how Python reacts.

Expression
'a' + 'b'

'a' * 5

5 * 'a' + 5 * 'b'

[1] + [2]

['a', 'b'] + ['c', 'd']

[2] * 4 + [4] * 2

[1,2,3] + 3 * [4]

99 % 3

5 + (10 % 3)

100 > 5

100 > 5 and 100 < 99

1 > 2 or 2 > 1

not (1 > 2) and not (3 < 3)

(True or False) and (False and True)

x = 'giraffe'
x[2] # evaluate the result of this line of code


'cat' + 'dog'

'cat' > 'dog'

(99 * 2) < 200 or (100 > 50 * 2)

True or False or False or True

Trace the Output

Trace the output of the following programs (each shaded box below is a separate Python program.)

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 = 45

while x < 50:
    print (x)
for x in [1,2,3,4,5]:
    print (x)
for p in range(1,10):
    print (p)
for z in range(-500,500,100):
    print (z)
x = 10
y = 5

for i in range(x-y*2):
    print ("%", i)
for x in [1,2,3]:
    for y in [4,5,6]:
        print (x,y)
for x in range(3):
    for y in range(4):
        print (x,y,x+y)
c = 0

for x in range(10):
    for y in range(5):
        c += 1

print (c)
x = [1,2,3]

counter = 0
while counter < len(x):

    print (x[counter] * '%')

    for y in x:
        print (y * '*')

    counter += 1
for x in 'lamp':
    print (str.upper(x))
x = 'one'
y = 'two'

counter = 0
while counter < len(x):
    print (x[counter], y[counter])
    counter+=1
y = ['apple','pear','peach','grapefruit'] 

for z in y:
    if z < 'm':
        print (str.lower(z))
    else:
        print (str.upper(z))
word = "pikachu"
for c in word:
    print (c)
word = "pikachu"
for i in range(0, len(word)):
    print (i, word[i])
word = "pikachu"
for i in range(len(word)-1, -1, -1):
    print (i, word[i])
word = "pikachu"
for i in range(0, len(word), 2):
    print (i, word[i])
word = "pikachu"
print (word[0:len(word):2])
word = "hello, world"
newword = word[0:2] + word[-2:]

print (newword)
# Trace the output of the following program.  Then rewrite the program using a “while” 
# loop instead of a “for” loop.  You don't need to re-write the list – just rewrite 
# the looping portion of the program.

pokemon = ["squirtle", "pikachu", "charmander",    
           "bulbasaur", "meowth"]

for i in range(0, len(pokemon), 2):
    print (i, pokemon[i])


##### solution
counter = 0

while counter < len(pokemon):
    print (counter, pokemon[counter])
    counter += 2
for name in ['apple', 'pear', 'peach', 'apricot', 'starfruit']:

    if x >= 'a' and x <= 'm':
        print (str.upper(name))

    else:
        print (str.lower(name))

Programming Challenges

Use the homework problems and programming challenges from the slides for practice as well.

  1. Write a program that asks the user for a number of days. Then prompt the user for their weight on each day they specified (i.e. if they enter 7 you should ask them for 7 weight values). When they are finished print out their average weight for the period in question. Sample running:
    Enter a number of days: 3
    Day 1: Enter a weight: 180
    Day 2: Enter a weight: 175
    Day 3: Enter a weight: 170
    
    Average weight for 3 days: 175.0
  2. Re-write the previous program so that you re-prompt them if the user enters an invalid weight y(anything 0 or less). Ensure that you don't move to the next day without getting a valid weight. Sample running:
    Enter a number of days: 3
    Day 1: Enter a weight: 180
    Day 2: Enter a weight: 0
    Invalid, try again!
    Day 2: Enter a weight: -5
    Invalid, try again!
    Day 2: Enter a weight: 175
    Day 3: Enter a weight: 170
    
    Average weight for 3 days: 175.0
  3. Write a program that determines if a NYU Student ID is valid. For the purpose of this question a valid NYU Student ID is defined as follows:
    exactly 9 characters long
    begins with the uppercase character ‘N’
    all characters beside the beginning ‘N’ character must be numbers
    Your program should ask the user for an “N number” and determine if it is valid or not. Here are some valid and invalid numbers:
    N123    invalid
    N1234567890    invalid
    P12345678    invalid
    NXYZ!5678    invalid
    N12345678    valid
  4. Write a program that prompts the user to enter in 5 colors. Print out the colors entered in alphabetical orders. Then print out the colors entered in reverse alphabetical order.
  5. Write a program that prompts the user to enter in an unlimited number of colors. Test to make sure that the user did not already enter a color before storing it (i.e. “We're sorry, but you've already added the color 'yellow'”). When the user types the string “exit” you should stop collecting colors. The print out the colors entered in alphabetical order.
  6. Rewrite the following program using a “for” loop:
    x = [1,2,3,4,5]
    
    counter = 0
    while counter < len(x):
        print (x[counter])
        counter += 1
  7. Rewrite the following program using a “while” loop:
    x = ['a','b','c','d']
    
    for y in x:
        print (y)
  8. Rewrite the following program using a “while” loop:
    x = 'python'
    
    for y in x:
        print (y)
  9. Write a program that lets a user enter in 5 price values. Ensure that the prices entered are greater than 0 (but you can assume they will be numeric and not alphanumeric). Once you have collected all the prices you should print out the following:
    1. The average price
    2. The highest price
    3. The lowest price
    4. If the user spent more than 100, you can give them the lowest priced item for free. In this case you should congratulate them, print out their total bill and average price without the lowest priced item factored in.

 

Programming Problems – Solutions

  1. total = 0
    again = "yes"
    while again == "yes":
        p = float(input("Enter a price: "))
        total += p
        again = input("Enter another price? (yes or no): ")
  2. total = 0
    days = int(input("Enter a number of days: "))
    for day in range(days):
        prompt = "Day " + str(day) + ": Enter a weight: "
        weight = input(prompt)
        total += weight
    
    print ("Average weight for", days, "days:", total/days)
  3. n_number = intput("Enter N-number ") 
    if len(n_number) != 9:
        print("invalid")
    elif n_number[0] != "N":
        print("invalid")
    elif n_number[1:].isdigit() == False:
        print("invalid")
    else:
        print("valid")
    
  4. # create an empty list
    colors = []
    
    # prompt the user for 5 colors
    counter = 0
    while counter < 5:
    
        # get a color from the user
        color = input("Give me a color: ")
    
        # put the color in the list
        colors.append(color)
    
        counter += 1
    
    # sort the list
    colors.sort()
    
    print (colors)
    
    # reverse the list
    colors.reverse()
    
    print (colors)
  5. colors = []
    
    # ask the user for an unlimited number of colors
    keepgoing = True
    
    while keepgoing == True:
    
        # ask the user for a color
        color = input('Give me a color: ')
    
        # does the user want to exit?
        if color == 'exit':
            keepgoing = False
    
        elif color in colors:
            print ("Sorry, that's already in the list.")
    
        else:
            colors.append(color)
    
    # sort the list
    colors.sort()
    
    print (colors)
  6. x = [1,2,3,4,5]
    
    for y in x:
        print (y)
  7. x = ['a','b','c','d']
    
    counter = 0
    
    while counter < len(x):
        print (x[counter])
        counter += 1
  8. x = 'python'
    
    counter = 0
    
    while counter < len(x):
    
        print (x[counter])
    
        counter += 1
  9. prices = []
    
    # grab 5 values from the user ensuring that they are
    # all greater than 0
    keepgoing = True
    
    # counter variable
    total = 0
    
    while keepgoing == True:
    
        # grab a price
        price = float(input("Give me a price: "))
    
        # is the price greater than zero?
        if price <= 0:
             print ("Sorry, too low.")
        else:
             prices.append(price)
             total += price
    
        # see if we can get out of the loop
        if len(prices) == 5:
             keepgoing = False 
    
    print ("Average: ", total / 5)
    print ("Highest: ", max(prices))
    print ("Minimum: ", min(prices)) 
    
    # special deal
    if total > 100:
    
        newtotal = total - min(prices)
    
        print ("Congrats!")
        print ("New total: ", newtotal)
    
        print ("New average: ", newtotal / 4)