Difference between revisions of "CSC111 Lab 2"

From dftwiki3
Jump to: navigation, search
(Created page with '__TOC__ <bluebox> This lab deals with loops in python. Feel free to work in pairs, share insights and help your neighbors during the lab. This is true of all labs. While some h…')
 
 
(22 intermediate revisions by the same user not shown)
Line 10: Line 10:
 
=Printing programs from Linux=
 
=Printing programs from Linux=
  
If you want to print your programs directly from your account on Beowulf to the printer in FH243 (next door to the lab), you need to use the '''cprint''' command. Here are a few examples of how you would print a file called '''programname.py'''.
+
If you want to print your programs directly from your account on Beowulf to the printer in FH243 (next door to the lab), you need to use the '''cprint''' command. Here is how you would print a file called '''programname.py'''.
  
 
* Get the list of the printers
 
* Get the list of the printers
Line 33: Line 33:
 
=Single for-loops=
 
=Single for-loops=
  
For this section of the lab, use Python in interactive mode . Once you are logged in, at the Linux prompt, just type python by itself:
+
* For this section of the lab, open two ssh/secure shell windows, edit in one of them and execute in the other.
  
python
+
* Create a new program called '''lab2.py'''
 +
 
 +
  # lab2.py
 +
 
 +
  def main():
 +
        for i in range( 3, 8 ):
 +
                print i
 
   
 
   
  Python 2.6 (r26:66714, Nov  3 2009, 17:33:38)
+
   
[GCC 4.4.1 20090725 (Red Hat 4.4.1-2)] on linux2
+
    main()
Type "help", "copyright", "credits" or "license" for more information.
 
>>>
 
  
;List of numbers
+
* Verify that you get the correct output:
* Write a for-loop that prints all the numbers between -3 and 7, 7 included, using the range function, as follows (the user input is underlined):
 
  
   >>> for i in range( 3, 8 ):
+
   <u>'''python lab2.py'''</u>
  ...    print i            (Do not forget to indent this line)
 
  ...                        (Press the ENTER key to mark the end)
 
                              (of the loop)
 
 
   3
 
   3
 
   4
 
   4
Line 54: Line 54:
 
   6
 
   6
 
   7  
 
   7  
   >>>
+
    
  
 
* Now, your turn!
 
* Now, your turn!
  
 
;List of numbers, Version 2
 
;List of numbers, Version 2
: Same question, but this time write a loop that does not use the range function. (Hint: you have to list all the values)
+
: Modify your loop so that it does not use the ''range( )'' funciton (Hint: you have to list all the values)
  
 
; List of even numbers:  
 
; List of even numbers:  
: write a loop that prints all the even numbers between 4 and 20, 4, and 20 included.
+
: write a loop that prints all the even numbers between 4 and 20, 4, and 20 included (you can use range or list all the numbers).
  
 
;List of odd numbers:  
 
;List of odd numbers:  
 
:write a loop that prints all the odd numbers between -3 and 19, -3, and 19 included.
 
:write a loop that prints all the odd numbers between -3 and 19, -3, and 19 included.
  
;User-controlled loops:  
+
;User-controlled loops (more difficult):  
:Exit python by typing Ctrl-D. Use emacs to write a Python program that prints a series of numbers, after having asked the user where the series should start, and where it should end. Here is an example of how it should run (the user input is in boldface):
+
:Write a new Python program that prints a series of numbers, after having asked the user where the series should start, and where it should end.  
 +
 
 +
:Here is an example of how it should run (the user input is iunderlined):
 
   
 
   
       Python userLoop.py
+
       <U>'''Python userLoop.py'''</U>
 +
 
 +
      I will print a list of numbers for you.
 +
 
 +
      Where should I start? <u>'''3'''</u>
 
   
 
   
       I will print a list of numbers for you.
+
       What is the last number of the series? <u>'''10'''</u>
 
   
 
   
       Where should I start? '''3'''
+
       3 4 5 6 7 8 9 10
  
      What is the last number of the series? '''10'''
+
:Go ahead and write it. What happens if you ask the program to count from -5 to 5? Does it work correctly?
  
      3 4 5 6 7 8 9 10
+
:Does your program work if you ask your program to go from 1 to 1?
 +
 
 +
:Can you predict what will be printed if you ask your program to count from 10 to 1?
 +
 
 +
=Lists and Operations on Lists=
  
:Go ahead and write it. What happens if you ask the program to count from -5 to 5? Does it work correctly?
+
* Try the following Python statements in the Python shell (interactive mode).
  
Does it work if you ask your program to go from 1 to 1?
+
      >>> students = [ "alice", "kate", "renee"]
 +
   
 +
      >>> students
 +
 +
      >>> students.append( "monique" )
 +
 +
      >>> students
 +
 +
      >>> students = []
 +
 +
      >>> students
 +
 +
      >>> students = [ "alice", "jack" ] + [ "monique", "chris", "andrea" ]
 +
 +
      >>> students
 +
 
 +
      >>> students[ 0 ]
 +
 +
      >>> students[ 1 ]
 +
 +
      >>> students[ -1 ]
 +
 +
      >>> students[ -2 ]          ''(try to figure out how negative indices work)''
  
Can you predict what will be printed if you ask your program to count from 10 to 1?
+
=For-Loops ready for modification=
  
For-Loops ready for modification
+
* Create the following python program (we're not working in interactive mode at this point). Don't hesitate to copy and paste to go faster!
  
Create the following python program (we're not working in interactive mode at this point). Don't hesitate to cut and paste to go faster!
 
 
       # lab2seq.py
 
       # lab2seq.py
 
       #  
 
       #  
 
       # initialize the farm with animals
 
       # initialize the farm with animals
 
       farm = [ "dog", "cat", "horse" ]
 
       farm = [ "dog", "cat", "horse" ]
 
+
 
       # print the contents of the farm
 
       # print the contents of the farm
 
       for animal in farm:
 
       for animal in farm:
 
         print animal
 
         print animal
  
Farm and animal are variables. One contains a list, the other one contains a string.
+
:'''Farm''' and '''animal''' are variables. One contains a list, the other one contains a string.
  
Add a pig to your farm, and make sure it gets listed by the program.
+
*Add a '''pig''' to your farm, and make sure it gets listed by the program.
  
When you are done with the addition of the pig, observe another way for the program to do the same thing:
+
* When you are done with the addition of the pig, observe another way for the program to do the same thing:
  
 
       # lab2seq2.py
 
       # lab2seq2.py
Line 111: Line 142:
 
       farm.append( "horse" ) # then a horse
 
       farm.append( "horse" ) # then a horse
 
       farm.append( "pig" )  # and a pig
 
       farm.append( "pig" )  # and a pig
 
+
 
       # print the contents of the farm
 
       # print the contents of the farm
 
       for animal in farm:
 
       for animal in farm:
 
           print animal
 
           print animal
Modification #1: Edit this second program so that instead of always adding the same animals to the farm, it will get four names of animals from the user, and add them to the farm. It will then print the contents of the farm on the screen. (Hint: use raw_input)
 
  
Modification #2: Change the for-loop of your program so that it reads:
+
;Modification #1:
 +
:Edit this second program so that instead of always adding the same animals to the farm, it will get four names of animals from the user, and add them to the farm. It will then print the contents of the farm on the screen. (Hint: use raw_input)
 +
 
 +
;Modification #2: Change the for-loop of your program so that it reads:
 
       counter = 0
 
       counter = 0
       for animal in farm
+
       for animal in farm:
           print animal
+
           print counter, animal
          print counter
 
 
           counter = counter + 1
 
           counter = counter + 1
 
            
 
            
Run the program. Observe its output. From this observation, modify the program so that its output now reads something like this (user input underlined):
+
* Run the program. Observe its output. From this observation, modify the program so that its output now reads something like this (user input is in underlined):
  
 
         python lab2seq3.py
 
         python lab2seq3.py
 
+
         animal? sheep
+
         animal? <u>'''sheep'''</u>
         animal? dog
+
         animal? <u>'''dog'''</u>
         animal? bear
+
         animal? <u>'''bear'''</u>
         animal? mouse
+
         animal? <u>'''mouse'''</u>
 
+
 
         Your farm now contains
 
         Your farm now contains
 
         animal #1 : a sheep
 
         animal #1 : a sheep
Line 138: Line 170:
 
         animal #3 : a bear
 
         animal #3 : a bear
 
         animal #4 : a mouse
 
         animal #4 : a mouse
Old MacDonald's Farm
 
  
Old MacDonald's farm is a song (almost) all American kids learn at one point in their life. I certainly never heard it when I grew up in France, but I think most of you will be familiar with it. If you can think of other lyrics that would be good for this exercise, let me know!
+
=Old MacDonald's Farm=
You can easily find the lyrics on the Web.
+
 
 +
Old MacDonald's farm is a song (almost) all American kids learn at one point in their life. I certainly never heard it when I grew up in France, but I think most of you will be familiar with it.  
 +
<center>
 +
<videoflash>7_mol6B9z00</videoflash>
 +
</center>
 +
If you don't know it, this YouTube video will get you acquainted with it. :-)
  
 
The goal of this problem is for you to add a section to the program below so that it prints parts of the lyrics of the famous song using a for-loop.
 
The goal of this problem is for you to add a section to the program below so that it prints parts of the lyrics of the famous song using a for-loop.
Line 147: Line 183:
 
Here's the beginning program which you have to modify:
 
Here's the beginning program which you have to modify:
  
 +
    def main():
 +
        # start with four animals in the farm
 +
        farm = [ "horse", "pig", "dog", "cat" ]
 +
   
 +
        # display the names of the animals
 +
        for animal in farm:
 +
            print animal
 +
 +
    main()
 +
 +
==First modification==
  
# start with four animals in the farm
+
* Modify this program so that the output looks like the lyrics of the song:
farm = [ "horse", "pig", "dog", "cat" ]
 
  
# display the names of the animals
+
    Old MacDonald had a farm, E-I-E-I-O
for animal in farm:
+
    And on his farm he had a horse, E-I-E-I-O
    print animal
+
    Here a horse, there a horse, everywhere a horse!
 +
   
 +
    Old MacDonald had a farm, E-I-E-I-O
 +
    And on his farm he had a pig, E-I-E-I-O
 +
    Here a pig, there a pig, everywhere a pig!
 +
   
 +
    Old MacDonald had a farm, E-I-E-I-O
 +
    And on his farm he had a dog, E-I-E-I-O
 +
    Here a dog, there a dog, everywhere a dog!
 +
   
 +
    Old MacDonald had a farm, E-I-E-I-O
 +
    And on his farm he had a cat, E-I-E-I-O
 +
    Here a cat, there a cat, everywhere a cat!
  
First modification
+
(don't worry if you get extra spaces in your output)
  
Modify this program so that the output looks like the lyrics of the song:
+
==Second modification==
  
Old MacDonald had a farm, E-I-E-I-O
+
* Modify your program some more, and make it prompt the user for the names of four animals first, and then make it display the lyrics as shown above with the user's selected animals.
And on his farm he had a horse, E-I-E-I-O
 
Here a horse, there a horse, everywhere a horse!
 
  
Old MacDonald had a farm, E-I-E-I-O
+
==Hard problem of the day==
And on his farm he had a pig, E-I-E-I-O
 
Here a pig, there a pig, everywhere a pig!
 
 
 
Old MacDonald had a farm, E-I-E-I-O
 
And on his farm he had a dog, E-I-E-I-O
 
Here a dog, there a dog, everywhere a dog!
 
 
 
Old MacDonald had a farm, E-I-E-I-O
 
And on his farm he had a cat, E-I-E-I-O
 
Here a cat, there a cat, everywhere a cat!
 
(don't worry if you get extra spaces in your output)
 
Second modification
 
  
Modify your program some more, and make it prompt the user for the names of four animals first, and then make it display the lyrics as shown above with the user's selected animals.
+
* This problem is a bit harder, and requires some thinking...
  
Hard problem of the day
+
* Write a program that
 +
** asks the user for number between 0 and 20
 +
** Assume the user enters 7.
 +
** The program then prints 7 stars (*) on the line, followed by 13 exclamation marks (!)
 +
** In general, the program prints a number of stars equal to the number entered by the user, and continues with exclamation marks such that the total number of stars plus exclamation marks is 20.  Always.
  
This problem is a bit harder, and requires some thinking...
+
* Examples of how your program should work (user input underlined):
Write a loop that prints 20 characters on the screen. Always 20. But it is made up of stars (*), which are printed first, and exclamation marks (!) that complete the line. Your program will first ask the user to enter a number. It will represent the number of stars that should be present in the line. The program will then print exclamation marks until the total number of characters is 20.
 
  
Examples of how your program should work (user input underlined):
+
       How many stars? <u>'''10'''</u>
       How many stars? 10
 
 
       * * * * * * * * * * ! ! ! ! ! ! ! ! ! !  
 
       * * * * * * * * * * ! ! ! ! ! ! ! ! ! !  
 
+
       How many stars? 20
+
       How many stars? <u>'''20'''</u>
 
       * * * * * * * * * * * * * * * * * * * *
 
       * * * * * * * * * * * * * * * * * * * *
 +
 +
      How many stars? <u>'''1'''</u>
 +
      * ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
 +
       
  
      How many stars? 1
+
You are now ready for [[CSC111 Homework 2 | Homework #2]]<br>
      * ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
+
[[CSC111 Solutions for Lab 2 | Lab Solutions]]
     
 
  
  
 
[[Category:CSC111]][[Category:Labs]]
 
[[Category:CSC111]][[Category:Labs]]

Latest revision as of 09:35, 5 February 2010

This lab deals with loops in python. Feel free to work in pairs, share insights and help your neighbors during the lab. This is true of all labs. While some homework assignments will have to be done as individual work, the labs are a good time to cooperate with neighbors or work in pairs.


Printing programs from Linux

If you want to print your programs directly from your account on Beowulf to the printer in FH243 (next door to the lab), you need to use the cprint command. Here is how you would print a file called programname.py.

  • Get the list of the printers
    cprint -l             (that's minus-ell)

    print 	lp queue	location
    ----- 	--------	--------
    1    	mc104          	McConnell 104                 
    2    	fh243          	Ford Hall 243                 
    3    	eng_203        	Engineering 203               
    4    	eng_203_color  	Engineering 203 Color         
  • Note that the printer in FH243 is on the line starting with 2
  • Print to Printer #2
  cprint -2 programname.py
and your listing will available at the black and white printer in FH243. Use different numbers to print to different printers, depending on which one is closest to you.

Single for-loops

  • For this section of the lab, open two ssh/secure shell windows, edit in one of them and execute in the other.
  • Create a new program called lab2.py
 # lab2.py
  
  def main():
        for i in range( 3, 8 ):
               print i


   main()
  • Verify that you get the correct output:
 python lab2.py
 3
 4
 5
 6
 7 
 
  • Now, your turn!
List of numbers, Version 2
Modify your loop so that it does not use the range( ) funciton (Hint: you have to list all the values)
List of even numbers
write a loop that prints all the even numbers between 4 and 20, 4, and 20 included (you can use range or list all the numbers).
List of odd numbers
write a loop that prints all the odd numbers between -3 and 19, -3, and 19 included.
User-controlled loops (more difficult)
Write a new Python program that prints a series of numbers, after having asked the user where the series should start, and where it should end.
Here is an example of how it should run (the user input is iunderlined):
     Python userLoop.py
  
     I will print a list of numbers for you.
 
     Where should I start? 3

     What is the last number of the series? 10

     3 4 5 6 7 8 9 10
Go ahead and write it. What happens if you ask the program to count from -5 to 5? Does it work correctly?
Does your program work if you ask your program to go from 1 to 1?
Can you predict what will be printed if you ask your program to count from 10 to 1?

Lists and Operations on Lists

  • Try the following Python statements in the Python shell (interactive mode).
     >>> students = [ "alice", "kate", "renee"]
    
     >>> students

     >>> students.append( "monique" )

     >>> students

     >>> students = []

     >>> students

     >>> students = [ "alice", "jack" ] + [ "monique", "chris", "andrea" ]

     >>> students
 
     >>> students[ 0 ]

     >>> students[ 1 ]

     >>> students[ -1 ]

     >>> students[ -2 ]           (try to figure out how negative indices work)

For-Loops ready for modification

  • Create the following python program (we're not working in interactive mode at this point). Don't hesitate to copy and paste to go faster!
     # lab2seq.py
     # 
     # initialize the farm with animals
     farm = [ "dog", "cat", "horse" ]

     # print the contents of the farm
     for animal in farm:
        print animal
Farm and animal are variables. One contains a list, the other one contains a string.
  • Add a pig to your farm, and make sure it gets listed by the program.
  • When you are done with the addition of the pig, observe another way for the program to do the same thing:
      # lab2seq2.py
      #
      farm = []              # create an empty farm
      farm.append( "dog" )   # add a dog to it
      farm.append( "cat" )   # then a cat
      farm.append( "horse" ) # then a horse
      farm.append( "pig" )   # and a pig

      # print the contents of the farm
      for animal in farm:
          print animal
Modification #1
Edit this second program so that instead of always adding the same animals to the farm, it will get four names of animals from the user, and add them to the farm. It will then print the contents of the farm on the screen. (Hint: use raw_input)
Modification #2
Change the for-loop of your program so that it reads:
      counter = 0
      for animal in farm:
          print counter, animal
          counter = counter + 1
          
  • Run the program. Observe its output. From this observation, modify the program so that its output now reads something like this (user input is in underlined):
       python lab2seq3.py

       animal? sheep
       animal? dog
       animal? bear
       animal? mouse

       Your farm now contains
       animal #1 : a sheep
       animal #2 : a dog
       animal #3 : a bear
       animal #4 : a mouse

Old MacDonald's Farm

Old MacDonald's farm is a song (almost) all American kids learn at one point in their life. I certainly never heard it when I grew up in France, but I think most of you will be familiar with it.

If you don't know it, this YouTube video will get you acquainted with it. :-)

The goal of this problem is for you to add a section to the program below so that it prints parts of the lyrics of the famous song using a for-loop.

Here's the beginning program which you have to modify:

    def main():
        # start with four animals in the farm
        farm = [ "horse", "pig", "dog", "cat" ]
    
        # display the names of the animals
        for animal in farm:
            print animal

    main()

First modification

  • Modify this program so that the output looks like the lyrics of the song:
    Old MacDonald had a farm, E-I-E-I-O
    And on his farm he had a horse, E-I-E-I-O
    Here a horse, there a horse, everywhere a horse!
    
    Old MacDonald had a farm, E-I-E-I-O
    And on his farm he had a pig, E-I-E-I-O
    Here a pig, there a pig, everywhere a pig!
    
    Old MacDonald had a farm, E-I-E-I-O
    And on his farm he had a dog, E-I-E-I-O
    Here a dog, there a dog, everywhere a dog!
    
    Old MacDonald had a farm, E-I-E-I-O
    And on his farm he had a cat, E-I-E-I-O
    Here a cat, there a cat, everywhere a cat!

(don't worry if you get extra spaces in your output)

Second modification

  • Modify your program some more, and make it prompt the user for the names of four animals first, and then make it display the lyrics as shown above with the user's selected animals.

Hard problem of the day

  • This problem is a bit harder, and requires some thinking...
  • Write a program that
    • asks the user for number between 0 and 20
    • Assume the user enters 7.
    • The program then prints 7 stars (*) on the line, followed by 13 exclamation marks (!)
    • In general, the program prints a number of stars equal to the number entered by the user, and continues with exclamation marks such that the total number of stars plus exclamation marks is 20. Always.
  • Examples of how your program should work (user input underlined):
      How many stars? 10
      * * * * * * * * * * ! ! ! ! ! ! ! ! ! ! 

      How many stars? 20
      * * * * * * * * * * * * * * * * * * * *

      How many stars? 1
      * ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
       

You are now ready for Homework #2
Lab Solutions