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 copying and pasting them into IDLE 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 |
x = 'G+I+R+A+F+F+E' x.split("+") # 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)
------
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
------
x = "apple,pear,peach" y = x.split(",") for z in y: print (z)
------
x = 'apple,pear,peach,grapefruit' y = x.split(',') for z in y: if z < 'm': print (str.lower(z)) else: print (str.upper(z))
------
def myfun(a): print (a * '#') x = "1-2-3-4-5" y = x.split("-") for z in y: myfun(int(z))
------
# 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]) # rewrite counter = 0 while counter < len(pokemon): print (counter, pokemon[counter]) counter += 2
------
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)
------
def foo(a): b = "" for c in a: if c.isalpha(): b+=c return b print( foo("hello there!") )
------
phrase = "4 score and 7 years ago ..." for c in phrase: if not (c.isdigit()): print (c, end="") else: x = int(c) if x % 2 == 0: print (x+1, end="") else: print (x-1, end="")
------
Programming Challenges
x = [1,2,3,4,5] counter = 0 while counter < len(x): print (x[counter]) counter += 1
x = ['a','b','c','d'] for y in x: print (y)
x = 'python' for y in x: print (y)
x = generate_bingo_letter() print (x) >> N x = generate_bingo_letter() print (x) >> O
0 GBOBI 1 OOOIG 2 NIIIN 3 BIGNN 4 OGOIN 5 BNOGB ....... 3856 BGIIO 3857 NBONN 3858 IBNGI 3859 GNOBN 3860 BINGO Finally, after 3860 tries!
symbols = ['cherry', 'pear', 'star', 'seven', 'watermelon']
Write a program that randomly selects three of these symbols and prints them out to the user. You cannot repeat a symbol (i.e. you cannot select 'cherry' twice). Here's are a few sample runnings of the program:
>> cherry star seven >> seven watermelon star >> pear star cherry
Your lottery #'s are: [19, 61, 62, 78, 99] >>> ================================ RESTART Your lottery #'s are: [1, 41, 64, 66, 78] >>> ================================ RESTART Your lottery #'s are: [19, 20, 28, 41, 97]
Write a function called "calc_bmi" that accepts two arguments - a weight value in pounds (float) and a height value in inches (float). You can assume the arguments supplied are valid floats. Using these arguments calculate BMI using the formula above, and return a the BMI (float) and a description (string). Use IPO notation to document your function.
Enter weight in pounds: none of your business Sorry, that's not a valid weight. Try again Enter weight in pounds: 150 Enter height in feet: 6 Enter height in inches: none Sorry, that's not a valid height. Try again. Enter a height in inches: 0 A 6'0 person weighting 150lbs has a BMI of 20.3414352. This is considered normal weight.
Enter a number between 1 and 10: 6 Enter a number between 1 and 10: 5 1. 5 and 1 2. 6 and 3 3. 3 and 10 4. 5 and 6 Your numbers were found on roll # 4
####
and calling line("10") will generate the following:
##########
***
and calling line("9") will generate the following:
*********
If the string provided is not a number you can simply generate and return empty string.
Once you have generated your pattern you should return the result when completed. You cannot assume anything about the supplied string, and your function should avoid raising any exceptions that will cause your program to crash. If an exception is raised you can return an empty string.
Your function should accept a test "N number" as an ARGUMENT (String) and RETURN a status value (Boolean). Here's a sample program that uses your function:
test1 = valid_n_number("N123") test2 = valid_n_number("N1234567890") test3 = valid_n_number("P12345678") test4 = valid_n_number("NXYZ!5678") test5 = valid_n_number("N12345678") print (test1, test2, test3, test4, test5)
And here's the expected output:
False False False False True
Programming Problems – Solutions
Problem #1
# 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)
Problem #2
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)
Problem #3
x = [1,2,3,4,5] for y in x: print (y)
Problem #4
x = ['a','b','c','d'] counter = 0 while counter < len(x): print (x[counter]) counter += 1
Problem #5
x = 'python' counter = 0 while counter < len(x): print (x[counter]) counter += 1
Problem #6
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)
Problem #7
def uppercase_test(s): # look at each character in s and determine # if it is uppercase or lowercase for char in s: if char.isupper() == False: return False return True x = uppercase_test("CRAIG") print (x)
Problem #8
def lowercase_converter(s): s = str.lower(s) return s
Problem #9
keepgoing = True while keepgoing: # test to see if the number is truly a number try: num = float(input("Give me a number: ")) # if there was an error, do this: except: print ("Sorry, bad number! Try again.") else: keepgoing = False print (num)
Problems #10 & #11
import random def generate_bingo_letter(): # what is the string we are using as a source? source = 'BINGO' # generate a random integer between 0 and 4 num = random.randint(0,4) # grab out the substring letter = source[num] # send it back return (letter) keepgoing = True counter = 1 while keepgoing == True: # generate 5 random characters c1 = generate_bingo_letter() c2 = generate_bingo_letter() c3 = generate_bingo_letter() c4 = generate_bingo_letter() c5 = generate_bingo_letter() # build a word out of this letter word = c1 + c2 + c3 + c4 + c5 # does this spell bingo? if word == 'BINGO': print ("got it after", counter, "tries!") keepgoing = False else: counter += 1
Problem #12
import random symbols = ['cherry', 'pear', 'star', 'seven', 'watermelon'] # select 3 symbols at random for x in range (3): # get a random number between 0 and the length of our list i = random.randint(0, len(symbols) - 1) # print out the symbol at this position print (symbols[i], ' ', end = '') # remove the symbol from the list symbols.remove(symbols[i])
Problem #13
import random lottery = [] for x in range(5): while True: num = random.randint(1,100) if num not in lottery: lottery.append(num) break lottery.sort() print (lottery)
Problems #14 and #15
def calc_bmi(weight, height): bmi = (weight*703)/(height**2) if bmi < 18.5: return bmi, "Underweight" elif bmi < 25: return bmi, "Normal weight" elif bmi < 30: return bmi, "Overweight" else: return bmi, "Obese" # get weight while True: try: weight = float(input("Enter weight in pounds: ")) except: print ("Not a valid weight, try again") else: if weight < 0: print ("Negative weight values are not allowed") else: break # get height in feet and inches while True: try: height_feet = int(input("Enter height in feet: ")) height_inches = int(input("Enter height in inches: ")) except: print ("Not a valid height, try again") else: if height_feet <= 0 or height_inches < 0 or height_inches >= 12: print ("Invalid entry, try again") else: break # calc bmi bmi, description = calc_bmi(weight, height_feet*12+height_inches) print ("A", height_feet, "'", height_inches, "person weighing", weight, "lbs has a BMI of", bmi, ". This is considered", description)
Problem #16
import random def roll_10_sided_die(): d1 = random.randint(1,10) d2 = random.randint(1,10) return d1, d2 while True: try: user_d1 = int(input("Enter a number between 1 and 10: ")) user_d2 = int(input("Enter a number between 1 and 10: ")) except: print ("Invalid number, try again") else: if user_d1 < 1 or user_d1 > 10 or user_d2 < 1 or user_d2 > 10: print ("Numbers must be between 1 and 10, try again") else: break counter = 0 while True: counter += 1 d1, d2 = roll_10_sided_die() print (counter, ". ", d1, " and ", d2, sep="") if (d1 == user_d1 and d2 == user_d2) or (d1 == user_d2 and d2 == user_d1): print ("Your numbers were found on roll #", counter) break
Problem #17
def line(x): try: if x.isdigit(): x = int(x) if x % 2 == 0: return x*"#" else: return x*"*" else: return "" except: return "" print (line("4")) print (line("5")) print (line("apple")) print (line(100))
Problems #18
def valid_n_number(number): if len(number) != 9: return False else: if number[0] != "N": return False else: testdigits = number[1:] if testdigits.isdigit(): return True else: return False print (valid_n_number("N123") ) print (valid_n_number("N1234567890") ) print (valid_n_number("P12345678") ) print (valid_n_number("NXYZ!5678") ) print (valid_n_number("N12345678") )