Difference between revisions of "CSC111 While Loop Exercises"
(11 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
− | --[[User:Thiebaut|D. Thiebaut]] 09:43, 10 November 2011 (EST) | + | --[[User:Thiebaut|D. Thiebaut]] 09:43, 10 November 2011 (EST) <br /> |
+ | revised --[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 21:55, 16 February 2014 (EST) | ||
---- | ---- | ||
+ | ==Loop Exercises== | ||
+ | ;Exercise 1 | ||
+ | : Write a Python program that asks the user to enter an integer that is greater than 0. The function will keep on asking the user for the number until it is valid. | ||
+ | |||
+ | ;Exercise 2 | ||
+ | : Write a Python program that asks the user to respond by 'Y', 'y', 'yes', 'YES' or 'N', 'n', 'no', 'NO'. The function keeps on asking until the user enters the correct information. | ||
+ | |||
+ | ;Exercise 3 | ||
+ | :Write a program that reads a character for playing the game of Rock-Paper-Scissors. If the character entered by the user is not one of 'P', 'R' or 'S', the program keeps on prompting the user to enter a new character. | ||
+ | |||
+ | ;Exercise 4 | ||
+ | : Write a Python program that reads strings of characters until it finds the string "THE END.", in which case it stops. | ||
+ | The program will count how many times the word "mother" appears in all the strings entered. | ||
+ | |||
+ | :Demo: count the number of times the words "Amherst" or "women" appear in [http://cs.smith.edu/~thiebaut/gutenberg/12241.txt Emily Dickinson's poems] | ||
+ | |||
+ | ;Exercise 5 | ||
− | ==Loop Exercises== | + | :Write a program that asks the user for three pieces of information: a '''starting balance''', a '''target balance''', and an '''interest rate''' (entered as 0.05 for 5%, for example). The program then outputs the number of investment periods required for the starting balance to have grown larger than the target balance. While this can be computed directly mathematically, we want for this exercise to use a '''while''' loop to figure out the answer. |
+ | |||
+ | :The answer should just be a line stating something like: "To grow an initial investment of $1000 to $2000 at 4.5% will require | ||
+ | |||
+ | <!-- | ||
+ | <br /> | ||
+ | ==Solutions== | ||
+ | <br /> | ||
+ | <source lang="python"> | ||
+ | # Exercise 1 | ||
+ | x = 0 | ||
+ | while x == 0: | ||
+ | x = float( input( "Enter an integer greater than 0: " ) ) | ||
+ | |||
+ | print( "You have entered:", x ) | ||
+ | |||
+ | # Exercise 2 | ||
+ | answer = input( "Do you like ice cream? " ) | ||
+ | answer = answer[0] | ||
+ | answer = answer.lower().strip() | ||
+ | while answer != 'y' and answer != 'n': | ||
+ | print( "invalid input!" ) | ||
+ | answer = input( "Do you like ice cream? " ) | ||
+ | |||
+ | if answer=='y': | ||
+ | print( "I like ice cream too!" ) | ||
+ | else: | ||
+ | print( "This is so sad!" ) | ||
+ | |||
+ | # Exercise 3 | ||
+ | human = input( "What do you play (R, P, S)? " ) | ||
+ | human = human.strip().lower() | ||
+ | while human != 'r' and human != 's' and human != 'p': | ||
+ | print( "Invalid input!" ) | ||
+ | human = input( "What do you play( R, P, S)? " ) | ||
+ | human = human.strip().lower() | ||
+ | |||
+ | print( "You have played %s!" % human ) | ||
+ | |||
+ | # Exercise 4 | ||
+ | line = input( "" ) | ||
+ | count = 1 | ||
+ | while line.find( "THE END." )==-1: | ||
+ | line = input( "" ) | ||
+ | count = count + 1 | ||
+ | |||
+ | print( "I have counted %d lines, including the sentinel line." % count ) | ||
+ | |||
+ | # Exercise 5 | ||
+ | ) ) | ||
+ | """ | ||
+ | # initialize the 3 variables | ||
+ | initBalance = 1000 #int( input( "Initial balance: " ) ) | ||
+ | endingBalance = 2000 #int( input( "Ending balance: " ) ) | ||
+ | intRate = 0.05 #float( input( "Rate (0.05 for 5%): " ) ) | ||
+ | |||
+ | # start accumulating | ||
+ | currentBalance= initBalance | ||
+ | periods = 1 | ||
+ | |||
+ | print( "starting balance: ", initBalance ) | ||
+ | |||
+ | while currentBalance < endingBalance: | ||
+ | currentBalance = currentBalance * ( 1.0 + intRate ) | ||
+ | #print( period, initBalance ) | ||
+ | periods = periods+ 1 | ||
+ | |||
+ | # correct last addition inside while loop | ||
+ | periods = periods - 1 | ||
+ | print( "To grow $%d to $%d at a rate of %1.1f%% will take %d periods" | ||
+ | % ( initBalance, endingBalance, intRate*100, periods) ) | ||
+ | |||
+ | |||
+ | </source> | ||
+ | --> | ||
+ | <!-- | ||
+ | ==Loop Exercises With Functions== | ||
;Exercise 1 | ;Exercise 1 | ||
Line 27: | Line 121: | ||
:Make the program accept inputs until one player's score is more than 3 points ahead of the other. | :Make the program accept inputs until one player's score is more than 3 points ahead of the other. | ||
+ | <source lang="python"> | ||
+ | def Exercise5(): | ||
+ | P1 = 0 | ||
+ | P2 = 0 | ||
+ | while abs( P1 - P2 ) < 3: | ||
+ | |||
+ | |||
+ | play = input( "\n\nEnter Player1 Player2 choices: " ).upper() | ||
+ | while not ( play in ["SS", "RR", "PP", "SR", | ||
+ | "SP", "RS", "RP", "PS", "PR" ] ): | ||
+ | play = input( "Invalid! Try again: " ).upper() | ||
+ | |||
+ | if play in [ "SP", "PR" ]: P1 += 1 | ||
+ | if play in [ "PS", "RP" ]: P2 += 1 | ||
+ | |||
+ | print( "Player 1: ", P1, "points -- Player 2: ", P2, "points" ) | ||
+ | |||
+ | if P1 > P2: | ||
+ | print( "Player 1 wins!" ) | ||
+ | else: | ||
+ | print( "Player 2 wins!" ) | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | </source> | ||
+ | <br /> | ||
;Exercise 6 | ;Exercise 6 | ||
:Replace the for-loops by while-loops in the following code | :Replace the for-loops by while-loops in the following code | ||
Line 42: | Line 163: | ||
<br /> | <br /> | ||
<br /> | <br /> | ||
− | + | ||
− | ==Solution | + | ==Solution Programs== |
<source lang="python"> | <source lang="python"> | ||
def exo1( ): | def exo1( ): | ||
Line 52: | Line 173: | ||
return ans | return ans | ||
+ | def exo1b(): | ||
+ | while True: | ||
+ | try: | ||
+ | x = eval( input( "Enter a number greater than 0: " ) ) | ||
+ | if x > 0: | ||
+ | return x | ||
+ | print( "Invalid number.", x, "is negative." ) | ||
+ | except ( NameError, SyntaxError ): | ||
+ | print( "Invalid input. Try again!" ) | ||
+ | |||
def exo2( ): | def exo2( ): | ||
ans = input( "Should we continue (Yes/No)? " ) | ans = input( "Should we continue (Yes/No)? " ) | ||
Line 83: | Line 214: | ||
print( "Key not found" ) | print( "Key not found" ) | ||
+ | def exo3c( fileName, key ): | ||
+ | """this version of the function is more robust and will not crash if the | ||
+ | file does not exist""" | ||
+ | try: | ||
+ | file = open( fileName, 'r' ) | ||
+ | except IOError: | ||
+ | print( fileName, "does not exist" ) | ||
+ | return False | ||
+ | |||
+ | for line in file: | ||
+ | if line.find( key ) != -1: | ||
+ | print( "found", key, "in line:\n>>>", line ) | ||
+ | file.close() | ||
+ | return True | ||
+ | |||
+ | print( key, "not found..." ) | ||
+ | file.close() | ||
+ | return False | ||
+ | |||
+ | |||
def exo4(): | def exo4(): | ||
sum = 0 | sum = 0 | ||
Line 125: | Line 276: | ||
c2 = 'a' | c2 = 'a' | ||
while c2 <= 'z': | while c2 <= 'z': | ||
− | print( " | + | print( "111a-" + c1 + c2 ) |
# see http://docs.python.org/library/functions.html | # see http://docs.python.org/library/functions.html | ||
c2 = chr( ord( c2 ) + 1 ) | c2 = chr( ord( c2 ) + 1 ) | ||
c1 = chr( ord( c1 ) + 1 ) | c1 = chr( ord( c1 ) + 1 ) | ||
+ | def exo6b(): | ||
+ | """same as previous function, but using indexing and strings""" | ||
+ | L1 = "ab" | ||
+ | L2 = "abcdefghijklmnopqrstuvwxyz" | ||
+ | i = 0 | ||
+ | while i < len( L1 ): | ||
+ | c1 = L1[i] | ||
+ | j = 0 | ||
+ | while j < len( L2 ): | ||
+ | c2 = L2[j] | ||
+ | print( "111a-" + c1 + c2 ) | ||
+ | j += 1 | ||
+ | i += 1 | ||
+ | |||
+ | |||
def main(): | def main(): | ||
print "Exercise 1" | print "Exercise 1" | ||
Line 150: | Line 316: | ||
</source> | </source> | ||
− | + | --> | |
<br /> | <br /> |
Latest revision as of 17:47, 17 February 2014
--D. Thiebaut 09:43, 10 November 2011 (EST)
revised --D. Thiebaut (talk) 21:55, 16 February 2014 (EST)
Loop Exercises
- Exercise 1
- Write a Python program that asks the user to enter an integer that is greater than 0. The function will keep on asking the user for the number until it is valid.
- Exercise 2
- Write a Python program that asks the user to respond by 'Y', 'y', 'yes', 'YES' or 'N', 'n', 'no', 'NO'. The function keeps on asking until the user enters the correct information.
- Exercise 3
- Write a program that reads a character for playing the game of Rock-Paper-Scissors. If the character entered by the user is not one of 'P', 'R' or 'S', the program keeps on prompting the user to enter a new character.
- Exercise 4
- Write a Python program that reads strings of characters until it finds the string "THE END.", in which case it stops.
The program will count how many times the word "mother" appears in all the strings entered.
- Demo: count the number of times the words "Amherst" or "women" appear in Emily Dickinson's poems
- Exercise 5
- Write a program that asks the user for three pieces of information: a starting balance, a target balance, and an interest rate (entered as 0.05 for 5%, for example). The program then outputs the number of investment periods required for the starting balance to have grown larger than the target balance. While this can be computed directly mathematically, we want for this exercise to use a while loop to figure out the answer.
- The answer should just be a line stating something like: "To grow an initial investment of $1000 to $2000 at 4.5% will require