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.
- Programming Mechanics
- Variables (what are they, creating them, using them, naming rules, etc)
- Reading input from the keyboard with the input() function
- Math Expressions
- Writing math expressions
- Evaluating math expressions
- Storing & printing the results of math expressions
- Data Types
- Strings
- Numeric data types
- Integers (int)
- Floating point numbers (float)
- The Boolean data type
- The List data type
- Mixed type expressions
- Type conversion (string to int, int to strings, etc)
- Basic String Manipulation
- Combining two strings (concatenation)
- Multiplying a string (x = 'hi' * 5)
- Case manipulation (x = str.lower('CRAIG') # converts the string literal 'CRAIG' to 'craig')
- Calculating string length using the len() function
- Selection Statements
- The structure of an IF statement (IF keyword, condition, colon, indentation)
- Writing a condition for an IF statement
- Boolean operators (<, >, ==, !=, >=, <=)
- Comparing numeric values using Boolean expressions
- Comparing string values using Boolean expressions
- Using the IF-ELSE statement
- Nesting decision structures (IF statements inside other IF statements)
- The IF-ELIF-ELSE statement
- Logical operators (and, or, not)
- Condition Controlled Loops (while loops)
- mechanics & how they work
- setting up conditions for a while loop
- infinite loops and how to avoid them
- sentinels (defining a value that the user enters that causes the loop to end)
- input validation loops (asking the user to continually enter a value until that value matches some condition)
- Accumulator variables
- setting up and using accumulator variables
- self referential assignment statements (i.e. counter = counter + 1)
- augmented assignment operators (i.e. counter += 1)
- Count Controlled Loops (for loops)
- mechanics and how they work
- iterating over a list (i.e. for x in [1,2,3,4,5]:)
- using the target variable in a for loop
- nested loops (i.e. loops inside of other loops)
- Lists
- 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”
- Defining lists in Python (i.e. mylist = [1,2,3])
- Concatenating lists with the “+” operator
- Repeating lists with the “*” operator
- Referencing list items using index notation (i.e. mylist[0])
- Iterating through a list using a “while” loop
- Iterating through a list using a “for” loop
- Using the len() function to determine the # of items in a list
- Updating the value of an item in a list using bracket notation
- Creating empty lists
- Finding an item in a list using the “in” operator
- Adding items to a list using the append method
- Sorting items in a list using the sort method
- Reversing items in a list using the reverse method
- Finding the position of an item in a list using the index method
- Inserting an item in a list at a specific index using the insert method
- Finding the largest and smallest values in a list using the min and max methods
- Totaling the values of all elements in a list using an accumulator variable
- Removing an item from a list using the remove method
- Strings Manipulation
- Iterating through all characters in a string using a for loop
- Indexing a specific character in a string using bracket notation
- Iterating through all characters in a string using a while loop
- String immutability (you can't change a string using bracket notation like you would change a list element)
- Testing a string for substrings using the “in” operator
- 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.
- 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
- 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
- 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
- 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.
- 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.
- 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
- Rewrite the following program using a “while” loop:
x = ['a','b','c','d']
for y in x:
print (y)
- Rewrite the following program using a “while” loop:
x = 'python'
for y in x:
print (y)
- 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:
- The average price
- The highest price
- The lowest price
- 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
-
total = 0
again = "yes"
while again == "yes":
p = float(input("Enter a price: "))
total += p
again = input("Enter another price? (yes or no): ")
-
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)
-
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")
-
# 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)
-
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)
-
x = [1,2,3,4,5]
for y in x:
print (y)
-
x = ['a','b','c','d']
counter = 0
while counter < len(x):
print (x[counter])
counter += 1
-
x = 'python'
counter = 0
while counter < len(x):
print (x[counter])
counter += 1
-
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)