Difference between revisions of "CSC111 While Loop Exercises"

From dftwiki3
Jump to: navigation, search
Line 69: Line 69:
 
<br />
 
<br />
 
<br />
 
<br />
<onlydft>
+
 
 
==Solution Programs==
 
==Solution Programs==
 
<source lang="python">
 
<source lang="python">
Line 222: Line 222:
 
</source>
 
</source>
 
   
 
   
</onlydft>
+
 
  
 
<br />
 
<br />

Revision as of 15:11, 15 November 2011

--D. Thiebaut 09:43, 10 November 2011 (EST)


Loop Exercises

Exercise 1
Write a function that asks the user to enter a number that is greater than 0. The function will keep on asking the user for the number until it is valid. The function will return the number.
Exercise 2
Write a function 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. The function will return True if the user entered Yes, and False otherwise.
Exercise 3
Write a function that reads lines from a file until it finds a line that contains a particular string. The function receives the name of the file, and the string.
Exercise 4
Pi can be computed by adding the following terms (http://en.wikipedia.org/wiki/Pi):

Pi expansion.png

How many terms does it take to get the first 3 digits to be correct, 3.14?
Exercise 5
Write a program that reads 2 characters from either the keyboard or a file. The characters are either PP, PR, PS, RP, RR, RS, SP, SR, SS. They correspond to the selections made by 2 players playing the game of rock-paper-scissors.
Make the program accept inputs until one player's score is more than 3 points ahead of the other.
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!" )


Exercise 6
Replace the for-loops by while-loops in the following code

         for c1 in 'ab':
             for c2 in 'abcdefghijklmnopqrstuvwxyz':
                   print "111c-" + c1 + c2








Solution Programs

 def exo1( ):
    ans = eval( input( "Please enter a number greater than 0: " ) )
    while ans < 0:
        ans = eval( input( "Invalid input. Please enter a number greater than 0: " ) )
 
    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( ):
    ans = input( "Should we continue (Yes/No)? " )
    while not ( ans.lower() in [ 'y', 'n', 'yes', 'no' ] ):
        ans = input( "Invalid answer, please enter Yes or No: " )
    return ( ans in [ 'y', 'yes' ] )
 
 def exo3( filename, key ):
    file = open( filename, 'r' )
    count = 0
    for line in file:
        if line.find( key ) != -1:
            print( "Found key: ", line )
            count += 1
            break
    file.close()
 
    if count==0:
        print( "Key not found" )
 
 def exo3b( filename, key ):
    file = open( filename, 'r' )
    count = 0
    line = file.readline()
    while line!="":
        if line.find( key )!=-1:
            print( "Found key: ", line )
            return
        line = file.readline()
 
    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():
    sum = 0
    num = 400.0
    denom = 1
    mult = 1
    count = 0
    while int( sum ) != 314:
        sum = sum + mult * num / denom
        mult = -mult
        denom = denom + 2
        count += 1
    print( count, "iterations: sum = ", sum/100.0 )
 
 def exo5():
    player1 = 0
    player2 = 0

    #--- keep on playing as long as the two players' scores is less than 3 apart---
    while abs( player1 - player2 ) < 3:
        #--- get user input and make sure it is valid ---
        play = raw_input( "Enter players draw: " ).upper()
        while not ( play in [ "PP", "RR", "SS", "PR", "PS", "RP", "RS", "SP", "SR" ] ):
            play = input( "Invalid input: try again: " ).upper()
 
        #--- check who's winning ---
        if play in [ "PR", "RS", "SP" ]:
            player1 += 1
        if play in [ "RP", "SR", "PS" ]:
            player2 += 1
        print( "Player1: %d  -- Player2: %d" % ( player1, player2 ) )
 
    #--- print winner ---
    if player1 > player2:
        print( "Player 1 wins!"  )
    else:
        print( "Player 2 wins!" )
    
 def exo6():
    c1 = 'a'
    while c1 <= 'b':
        c2 = 'a'
        while c2 <= 'z':
            print( "111a-" + c1 + c2 )
            # see http://docs.python.org/library/functions.html
            c2 = chr( ord( c2 ) + 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():
    print "Exercise 1"
    print( "exo1() returns", exo1() )
 
    print "Exercise 2"
    ans  = exo2()
    print( "exo2() returns", ans )
 
    exo3( raw_input( "file name? " ), raw_input( "keyword? " ) )
    exo3b( raw_input( "file name? " ), raw_input( "keyword? " ) )
 
    exo4()
     
    exo5()
 
    exo6()
     
 main()