Difference between revisions of "CSC111 Lab 7 2011"

From dftwiki3
Jump to: navigation, search
(Testing with the if statement)
(Challenge 7)
 
(30 intermediate revisions by the same user not shown)
Line 49: Line 49:
 
<br />
 
<br />
 
* Try it now!  Verify that your program is now '''robust''', i.e. you cannot make it crash (at least if you are entering numbers and not random strings!)
 
* Try it now!  Verify that your program is now '''robust''', i.e. you cannot make it crash (at least if you are entering numbers and not random strings!)
 +
<br />
 +
<br />
  
 
{| style="width:100%; background:silver"
 
{| style="width:100%; background:silver"
Line 56: Line 58:
 
|}
 
|}
 
[[Image:QuestionMark3.jpg|right|120px]]
 
[[Image:QuestionMark3.jpg|right|120px]]
 +
<br />
  
 
* Using the above code as example, modify the program so that it asks for two numbers and prints out which number is the smallest and which is the largest.   
 
* Using the above code as example, modify the program so that it asks for two numbers and prints out which number is the smallest and which is the largest.   
Line 67: Line 70:
 
|}
 
|}
 
[[Image:QuestionMark1.jpg|right|120px]]
 
[[Image:QuestionMark1.jpg|right|120px]]
 +
<br />
  
 
* Modify your code for the previous challenge and remove the two ''eval'' functions.  This way your two variables will contain strings, and not numbers.  Do not change the remaining part of your program and run it.   
 
* Modify your code for the previous challenge and remove the two ''eval'' functions.  This way your two variables will contain strings, and not numbers.  Do not change the remaining part of your program and run it.   
;Question 1
+
:;Question 1
:What does your program do?  What does it detect in the two strings you enter.  For example if you enter "chocolate" and "milk" as the two strings, which will it report as the smallest?  Why?
+
::What does your program do?  What does it detect in the two strings you enter.  For example if you enter "chocolate" and "milk" as the two strings, which will it report as the smallest?  Why?  What about "chocolate" and "MILK"?  Why?
;Question 2
+
<br />
:Think of a way to make your program report that "''chocolate''" is lower than "''milk''", and that "''chocolate''" is also lower than "''MILK''"
+
:;Question 2
 +
::Think of a way to make your program report that "''chocolate''" is lower than "''milk''", and that "''chocolate''" is also lower than "''MILK''"
 +
<br />
 
<br />
 
<br />
  
==Functions and Stick Figures==
+
==Tests and Graphics==
[[Image:StickFigureAnimated2.gif | right | 100px ]]
 
Cut and paste the following code into a python program.
 
  
 +
* Create the following program and run it.
 +
<br />
 
<br />
 
<br />
 
<source lang="python">
 
<source lang="python">
# stick.py
+
from graphics import *
# Draws sticks on the screen
+
import time
  
def head():
+
def main():
     print
+
     w = 500
     print "  o     "
+
     h = 500
      
+
     radius = 20
def body():
+
     win = GraphWin( "lab 7", w, h )
    print " /|\\  "
 
  
def legs():
+
    c = Circle( Point( w/2, h/2 ), radius )
     print " _/ \\_  "
+
     c.setFill( "magenta" )
     print
+
     c.draw( win )
  
def roundBody():
+
    dirX = 5  # speed in the horizontal direction
    print " /O\\    "
+
    for step in range( 1000 ):
 +
        c.move( dirX, 1 )       
 +
        # uncomment next line if ball moves too fast
 +
        # time.sleep( 0.05 ) # 5/100th sec.
 +
        if  c.getCenter().getX() < 0 or c.getCenter().getX() > w ):
 +
            dirX = -dirX
  
def longLegs():
+
    Text( Point( w//2, h//2 ), "Click me to quit!" ).draw( win )
     print "  / \\  "
+
     win.getMouse()
     print "_/  \\_ "
+
     win.close()
  
 +
main()
  
def main():
+
</source>
    head()
 
    body()
 
    legs()
 
  
main()
+
<br />
</source>      
+
<br />
 +
* Notice how the ball moves.  ''dirX'' is the amount of pixels it goes to the right (if ''dirX'' is positive), and 1 is the amount of pixels it goes down.
 +
* The if statement says "''if the X coordinate of the center of the circle is less than 0 or greater than w, then change the horizontal direction.''"  Changing the direction here means simply changing its sign.  If dirX is +5, that means the ball is going to the right, then making it -5 will make the ball go to the left.  If dirX is -5, then changing it to +5 means that the ball was going left, and then will go right.
 +
<br />
 +
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
===Challenge 3===
 +
|}
 +
[[Image:QuestionMark2.jpg|right|120px]]
 +
<br />
 +
* Make the ball bounce off the horizontal '''and vertical''' sides of the graphics window
 +
<br />
 +
<br />
 +
<br />
 
<br />
 
<br />
  
*  Run your program. Verify that it displays a stick figure.
+
{| style="width:100%; background:silver"
 +
|-
 +
|
  
 +
===Challenge 4===
 +
|}
 +
[[Image:QuestionMark5.jpg|right|120px]]
 
<br />
 
<br />
;Question 1
+
* Make the ball change color when it crosses the middle of the graphics window.  In other words, make it be, say, yellow, in the left half of the window, and red in the right half of the window.
: Modify the definition of the main() function only, and, this time, make it display a stick figure with a "round body" (which uses an O for the torso of the stick figure). '''<font color="magenta">Remember, you can only modify the main function.  You cannot modify any of the functions other than main().</font>'''
 
  
 
<br />
 
<br />
;Question 2
+
<br />
:Similar question: make the program draw a stick figure with a "round body" and "long legs." Again, you can only change the definition of the main function.
+
<br />
 +
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
===Challenge 5===
 +
|}
 +
[[Image:QuestionMark6.jpg|right|120px]]
 +
<br />
 +
* You will notice that the ball bounces off the "wall" when it is already half way through it (as illustrated below).   Modify your code so that the ball bounces off the side of the window when it ''"touches"'' the side.
 +
<br />
 +
<center>[[Image:CSC111HalfBall.png]]</center>
  
* Now, something a bit more complicated: create a new function called skinnyStickFigure() that will not contain a single print statement, but that will call other functions to display a skinny short stick figure (with a thin body and short legs). Your program should look something like this:
 
 
<br />
 
<br />
 
<source lang="python">
 
# newstick.py
 
# Draws sticks on the screen
 
 
def head():
 
    print
 
    print "  o    "
 
   
 
def body():
 
    print "  /|\\  "
 
 
def legs():
 
    print " _/ \\_  "
 
    print
 
 
def roundBody():
 
    print "  /O\\    "
 
 
def longLegs():
 
    print "  / \\  "
 
    print "_/  \\_ "
 
    print
 
 
def skinnyStickFigure():
 
    #add your code here
 
 
 
def main():
 
    skinnyStickFigure()
 
 
main()
 
     
 
</source>
 
 
<br />
 
<br />
 
* Verify that it works.
 
 
 
<br />
 
<br />
;Question 3
 
: Modify your program and add the definition of a new function called '''roundLongFigure()''' which will print a round-bodied long-legged stick figure.  '''<font color="magenta">Your new function should not contain print statements, but only calls to other functions that are already part of your program</font>'''.  Call it from your main program after you call '''skinnyStickFigure()''', as follows:
 
 
 
<br />
 
<br />
<source lang="python">
 
def main():
 
    skinnyStickFigure()
 
    roundLongFigure()
 
 
</source>
 
 
 
<br />
 
<br />
 +
<br />
 +
<br />
 +
<br /><br />
 
<br />
 
<br />
 
<br />
 
<br />
Line 180: Line 173:
  
 
==Happy Birthday with Functions!==
 
==Happy Birthday with Functions!==
[[Image:HappyBirthdayAnimated.gif | 150px | right]]
+
[[Image:HappyBirthdayAnimated.gif | 400px | right]]
 +
<!-- make the image 350 pixels wide to stop the animation...-->
 +
* Write a program that will use ''functions'' and that will display a  "Happy Birthday" message on the screen for somebody who's name is provided by the user.  Example
 +
 
 +
  Please enter name of birthday person:  <u>Alicia</u>
 +
 
 +
  Happy birthday to you,
 +
  Happy birthday to you,
 +
  Happy birthday to you,
 +
  Dear Alicia,
 +
  Happy birthday to you!
 +
 
  
* Write a program that will use functions and that will display a  "Happy Birthday" message on the screen.
 
 
* Requirements.  Your program should contain:
 
* Requirements.  Your program should contain:
** One function, '''hbday()''', prints "Happy birthday to you"
+
** One function, '''hbday()''', that prints "Happy birthday to you"
** One function, '''dear()''', gets the name of the person and prints "Happy birthday, dear xxxxx"
+
** One function, '''dear( ... )''', that receives the name of the person as a '''parameter''' and prints "Happy birthday, dear xxxxx", where xxxx represents that name.
** One function, '''singSong()''', gets the name of the person and prints the whole song with the name of the person.
+
** One function, '''singSong()''', that gets the name of the person and prints the whole song (as illustrated above) with the name of the person.
** The main program asks the user for a '''name''' and "sings" the song:
+
** The main program, which you cannot modify, asks the user for a '''name''' and "sings" the song:
  
  
 
               def main():
 
               def main():
                   name = raw_input( "person's name? " )
+
                   name = input( "Please enter name of birthday person: " )
 
                   singSong( name )
 
                   singSong( name )
  
 
                
 
                
;Question 4:
+
<br />
: Go ahead and write the program.
+
<br />
 
+
{| style="width:100%; background:silver"
;Question 5: Challenge of the day
+
|-
:Assume that you need to print the song for everybody in the class. We saw earlier how to write a loop that prints all the accounts of the form 111c-aa, 111c-ab, 111c-ac, ... 111c-az. Modify your program so that it prints a happy birthday song for every 111c account!
+
|
 +
===Challenge 6===
 +
|}
 +
[[Image:QuestionMark1.jpg|right|120px]]
 +
<br />
 +
* Go ahead and write the program.  
  
 
<br />
 
<br />
 
<br />
 
<br />
 
<br />
 
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
===Challenge 7===
 +
|}
 +
[[Image:QuestionMark1.jpg|right|120px]]
 
<br />
 
<br />
 +
:Assume that you need to print the song for everybody in the class. We saw earlier how to write a loop that prints all the accounts of the form 111a-aa, 111a-ab, 111a-ac, ... 111a-az.  Modify your program so that it prints a happy birthday song for every 111a account!
  
==Printing Recipes==
+
:For example, the output will look like this:
  
* Start with the following program:
+
Happy birthday to you,
<br />
+
Happy birthday to you,
<source lang="python">
+
Happy birthday to you,
  recipe.py                                                                                                           
+
Happy birthday, dear 111a-aa,
#                                                                                                                     
+
Happy birthday to you!
 +
 +
Happy birthday to you,
 +
Happy birthday to you,
 +
Happy birthday to you,
 +
Happy birthday, dear 111a-ab,
 +
Happy birthday to you!
 +
 +
Happy birthday to you,
 +
Happy birthday to you,
 +
Happy birthday to you,
 +
Happy birthday, dear 111a-ac,
 +
  Happy birthday to you!
 +
 +
...
 +
  
def printLines( recipe ):
 
    for line in recipe:
 
        print line
 
 
 
def main():
 
    recipe1 = ["Smoked Salmon Tortellini with Bechamel Sauce",
 
              "2 packages tortellini",
 
              "1 bay leaf",
 
              "2 whole cloves",
 
              "1 pinch nutmeg",
 
              "1 chopped red bell pepper",
 
              "1/2 lb fresh asparagus",
 
              "10 ounces fresh mushrooms" ]
 
 
    printLines( recipe1 )
 
 
main()
 
 
 
</source>
 
 
<br />
 
<br />
* Run the program and verify that it prints the recipe.
 
* Modify the program and add the following function to it (before the function '''printLines''').  Call '''separatorLine()''' once in your main program to see how it works.
 
 
 
 
<br />
 
<br />
<source lang="python">
 
.
 
 
def separatorLine():
 
    print  30 * '-' + 'oOo' + 30 * '-'
 
 
.
 
</source>
 
 
<br />
 
<br />
 
 
<br />
 
<br />
;Question 6
+
Done?  If so, you may start working on [[CSC111 Homework 5 2011| your homework assignment]]
: Modify the function '''printLines()''' so that it prints the recipe that it receives as shown below.  (''Hints: remember that you know how to take slices out of lists!'')
+
for this week.
 
 
------------------------------oOo------------------------------
 
Smoked Salmon Tortellini with Bechamel Sauce
 
------------------------------oOo------------------------------
 
2 packages tortellini
 
1 bay leaf
 
2 whole cloves
 
1 pinch nutmeg
 
1 chopped red bell pepper
 
1/2 lb fresh asparagus
 
10 ounces fresh mushrooms
 
------------------------------oOo------------------------------
 
  
 +
It doesn't require you to use if-statements or functions, but feel free to do so if it makes
 +
your life easier.
 
<br />
 
<br />
* Add a new recipe to your main program:
 
 
<br />
 
<br />
<source lang="python">
 
.
 
  
  recipe2 = [ "Bechamel Sauce", "1/4 cup butter", "2 tbsp flour", "1/4 cup milk"]
 
 
 
.
 
</source>
 
 
<br />
 
;Question 7
 
: Make your program print both recipes with separator lines.  The output of your program should look something like this:
 
 
------------------------------oOo------------------------------
 
Smoked Salmon Tortellini with Bechamel Sauce
 
------------------------------oOo------------------------------
 
2 packages tortellini
 
1 bay leaf
 
2 whole cloves
 
1 pinch nutmeg
 
1 chopped red bell pepper
 
1/2 lb fresh asparagus
 
10 ounces fresh mushrooms
 
------------------------------oOo------------------------------
 
 
 
------------------------------oOo------------------------------
 
Bechamel Sauce
 
------------------------------oOo------------------------------
 
1/4 cup butter
 
2 tbsp flour
 
1/4 cup milk
 
------------------------------oOo------------------------------
 
 
<br />
 
 
<br />
 
<br />
 
<br />
 
<br />

Latest revision as of 13:07, 20 October 2011

--D. Thiebaut 10:37, 19 October 2011 (EDT)


Testing with the if statement

A great reference for this part of the lab is the section on the if statement on Python.org. Take a quick look at it to see what it describes so that you will know where to go while working on this lab.



  • Create a program with the following code:



def main():
   print( "Please enter 2 numbers:" )
   x = eval( input( "> " ) )
   y = eval( input( "> " ) )

   print( x, "/", y, "=", x/y )

main()



  • Run the program a few times and check that it returns the correct information.
  • Run it again and enter 0 for the second value. See what happens.
  • Make your program robust by using an if-statement:



def main():
   print( "Please enter 2 numbers:" )
   x = eval( input( "> " ) )
   y = eval( input( "> " ) )

   if ( y != 0 ):
      print( x, "/", y, "=", x/y )
   else:
      print( "Illegal value for y: division by 0 is not allowed or defined" )

main()



  • Try it now! Verify that your program is now robust, i.e. you cannot make it crash (at least if you are entering numbers and not random strings!)



Challenge 1

QuestionMark3.jpg


  • Using the above code as example, modify the program so that it asks for two numbers and prints out which number is the smallest and which is the largest.




Challenge 2

QuestionMark1.jpg


  • Modify your code for the previous challenge and remove the two eval functions. This way your two variables will contain strings, and not numbers. Do not change the remaining part of your program and run it.
Question 1
What does your program do? What does it detect in the two strings you enter. For example if you enter "chocolate" and "milk" as the two strings, which will it report as the smallest? Why? What about "chocolate" and "MILK"? Why?


Question 2
Think of a way to make your program report that "chocolate" is lower than "milk", and that "chocolate" is also lower than "MILK"



Tests and Graphics

  • Create the following program and run it.



from graphics import *
import time

def main():
    w = 500
    h = 500
    radius = 20
    win = GraphWin( "lab 7", w, h )

    c = Circle( Point( w/2, h/2 ), radius )
    c.setFill( "magenta" )
    c.draw( win )

    dirX = 5  # speed in the horizontal direction
    for step in range( 1000 ):
        c.move( dirX, 1 )        
        # uncomment next line if ball moves too fast
        # time.sleep( 0.05 )  # 5/100th sec.
        if   c.getCenter().getX() < 0 or c.getCenter().getX() > w ):
            dirX = -dirX

    Text( Point( w//2, h//2 ), "Click me to quit!" ).draw( win )
    win.getMouse()
    win.close()

main()



  • Notice how the ball moves. dirX is the amount of pixels it goes to the right (if dirX is positive), and 1 is the amount of pixels it goes down.
  • The if statement says "if the X coordinate of the center of the circle is less than 0 or greater than w, then change the horizontal direction." Changing the direction here means simply changing its sign. If dirX is +5, that means the ball is going to the right, then making it -5 will make the ball go to the left. If dirX is -5, then changing it to +5 means that the ball was going left, and then will go right.



Challenge 3

QuestionMark2.jpg


  • Make the ball bounce off the horizontal and vertical sides of the graphics window





Challenge 4

QuestionMark5.jpg


  • Make the ball change color when it crosses the middle of the graphics window. In other words, make it be, say, yellow, in the left half of the window, and red in the right half of the window.





Challenge 5

QuestionMark6.jpg


  • You will notice that the ball bounces off the "wall" when it is already half way through it (as illustrated below). Modify your code so that the ball bounces off the side of the window when it "touches" the side.


CSC111HalfBall.png













Happy Birthday with Functions!

HappyBirthdayAnimated.gif
  • Write a program that will use functions and that will display a "Happy Birthday" message on the screen for somebody who's name is provided by the user. Example
 Please enter name of birthday person:  Alicia
 Happy birthday to you, 
 Happy birthday to you, 
 Happy birthday to you, 
 Dear Alicia,
 Happy birthday to you!


  • Requirements. Your program should contain:
    • One function, hbday(), that prints "Happy birthday to you"
    • One function, dear( ... ), that receives the name of the person as a parameter and prints "Happy birthday, dear xxxxx", where xxxx represents that name.
    • One function, singSong(), that gets the name of the person and prints the whole song (as illustrated above) with the name of the person.
    • The main program, which you cannot modify, asks the user for a name and "sings" the song:


              def main():
                  name = input( "Please enter name of birthday person: " )
                  singSong( name )




Challenge 6

QuestionMark1.jpg


  • Go ahead and write the program.




Challenge 7

QuestionMark1.jpg


Assume that you need to print the song for everybody in the class. We saw earlier how to write a loop that prints all the accounts of the form 111a-aa, 111a-ab, 111a-ac, ... 111a-az. Modify your program so that it prints a happy birthday song for every 111a account!
For example, the output will look like this:
Happy birthday to you,
Happy birthday to you,
Happy birthday to you,
Happy birthday, dear 111a-aa,
Happy birthday to you!

Happy birthday to you,
Happy birthday to you,
Happy birthday to you,
Happy birthday, dear 111a-ab,
Happy birthday to you!

Happy birthday to you,
Happy birthday to you,
Happy birthday to you,
Happy birthday, dear 111a-ac,
Happy birthday to you!

...





Done? If so, you may start working on your homework assignment for this week.

It doesn't require you to use if-statements or functions, but feel free to do so if it makes your life easier.