Difference between revisions of "CSC111 Lab 2 2015"

From dftwiki3
Jump to: navigation, search
(Single for-loops)
 
(29 intermediate revisions by the same user not shown)
Line 9: Line 9:
  
  
 +
 +
=Definite for-loops=
 +
<br />
 +
==Loops that use the '''range()''' function==
 +
<br />
 +
* For this section of the lab, open IDLE and create the different program sections below in the Python shell window. 
 +
<br />
 +
::<source lang="python">
 +
>>> for n in range( 4 ):
 +
print( n )
 +
 +
>>> for n in range( 1, 4 ):
 +
print( n )
 +
 +
>>> for n in range( -1, 4 ):
 +
print( n )
 +
 +
>>> for n in range( 5, 10 ):
 +
print( n )
 +
 +
>>> for n in range( 0, 10, 2 ):
 +
print( n )
 +
 +
>>> for n in range( 1, 10, 2 ):
 +
print( n )
 +
 +
>>> for n in range( 10, 0, -2 ):
 +
print( n )
 +
 +
</source>
 +
<br />
 +
* Do you understand how the range() function works? 
 +
** If you give it only 1 number, it will generate a series of numbers starting at 0 and going up to that number, but not including it, in steps of 1.
 +
** If you give it 2 numbers, it will use the first one as the start, and the second at the stop, and will generate all the integers between the two, in steps of 1.  The stop number is never used.
 +
** IF you give it 3 numbers, the 3rd one is the step.  It can be positive or negative.
 +
 +
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
 +
==Challenge #1: Range-Controlled Loops==
 +
|}
 +
[[Image:QuestionMark1.jpg|right|120px]]
 +
<br />
 +
Now, your turn:
 +
 +
; List of even numbers:
 +
: write a loop that prints all the even numbers between 4 and 20; 4, and 20 included.
 +
 +
;List of odd numbers:
 +
:write a loop that prints all the odd numbers between -3 and 19, -3, and 19 included.
 +
 +
;List odd numbers in reverse order:
 +
: write a loop that prints all the odd numbers starting at 9 and going down to 1, included.
 +
 +
<br />
 +
==Definite For-Loops that use Lists==
 +
<br />
 +
* We can use explicit lists to generate similar outputs.  For example, the output of the first two examples in the previous section  could have been generated by the following loops:
 +
<br />
 +
::<source lang="python">
 +
>>>for n in [0, 1, 2, 3]:
 +
            print( n )
 +
 +
>>>for n in [1, 2, 3]:
 +
            print( n )
 +
</source>
 +
<br />
 +
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
 +
==Challenge #2: List-Controlled Loops==
 +
|}
 +
[[Image:QuestionMark2.jpg|right|120px]]
 +
<br />
 +
Solve the 3 problems of Challenge 1 above, using lists instead of the '''range()''' function.
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
 +
<br />
 +
=For-Loops ready for modification=
 +
<br />
 +
* 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!
 +
::<source lang="python">
 +
# lab2seq.py
 +
#
 +
 +
# print the contents of the farm
 +
for animal in  [ "dog", "cat", "horse" ]:
 +
    print animal
 +
</source>
 +
<br />
 +
 +
*Add a '''pig''' to your list of animals, and make sure it gets listed by the program.
 +
 +
 +
;Modification #1: Change the for-loop of your program so that it reads:
 +
<br />
 +
<source lang="python">
 +
      counter = 0
 +
      for animal in  [ "dog", "cat", "horse", "pig" ]:
 +
          print( counter, animal )
 +
          counter = counter + 1
 +
</source>
 +
<br />
 +
* 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):
 +
 +
        Your farm 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 most 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.
 +
 +
Here's the beginning program which you have to modify:
 +
<br />
 +
::<source lang="python">   
 +
# display the names of the animals
 +
for animal in  [ "horse", "pig", "dog", "cat" ]:
 +
      print animal
 +
</source>
 +
<br />
 +
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
 +
==Challenge #3: Output Song Lyrics==
 +
|}
 +
[[Image:QuestionMark3.jpg|right|120px]]
 +
<br />
 +
 +
* Modify the program above so that it uses the loop, and outputs 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)
  
 
=The '''input()''' Function=
 
=The '''input()''' Function=
Line 32: Line 201:
 
>>> x
 
>>> x
  
>>> x = int( answer )
+
>>> x = eval( answer )
 
>>> x
 
>>> x
 +
>>> x + 5
  
>>> y = int(  "314.56789" )
+
>>> y = eval(  "314.56789" )
 
>>> y
 
>>> y
 
</pre></code>
 
</pre></code>
Line 69: Line 239:
 
|
 
|
  
==Challenge #5: (Challenging) Printing the student information it in a box==
+
==Challenge #5: Printing the student information it in a (half) box==
 
|}
 
|}
 
[[Image:QuestionMark5.jpg|right|120px]]
 
[[Image:QuestionMark5.jpg|right|120px]]
 
<br />
 
<br />
Same idea as with the previous challenge but after inputing the information from the user, the program outputs it in a box!
+
* Same idea as with the previous challenge but after inputing the information from the user, the program outputs it in a half-box!
 +
Example (user input in in boldface):
 +
<br />
 +
your first name?  '''Mickey'''
 +
your last name?    '''Mouse'''
 +
your box number?  '''1234'''
 +
your phone number? '''413 456 7890'''
 +
your Id number?    '''990111222'''
 +
 +
+---------------------------------------
 +
| Name:  Mickey Mouse ( 990111222 )
 +
| Box:    1234
 +
| Phone:  413 456 7890
 +
+---------------------------------------
  
Example:
 
 
<center>[[Image:Lab2_2014_boxedOutput.png]]</center>
 
 
<br />
 
<br />
 
+
* The length of the bars is unimportant.
  
 
<br />
 
<br />
Line 86: Line 266:
 
|-
 
|-
 
|
 
|
==Challenge #7: Seconds to Days, Hours, Minutes, Second converter==
+
 
 +
==Challenge #6: Temperature Converter==
 
|}
 
|}
 
[[Image:QuestionMark8.jpg|right|120px]]
 
[[Image:QuestionMark8.jpg|right|120px]]
 
<br />
 
<br />
Write a program that prompts the user for a time expressed as a '''number of seconds'''.  The program then outputs the equivalent number of days, hours, minutes, and seconds.
+
* Write a program that prompts the user for a temperature expressed in Fahrenheit, and outputs the equivalent temperature in Celsius.
  
Make the program output the result in a box, similar to the one shown below (the user input is in boldface):
+
* The equation for temperature conversion is:  Celsius  = ( Fahrenheit -32 ) * 5 / 9
  
  Please enter a time expressed in seconds: '''3662'''
+
* Here is an example of the way your program will work (the user input is in boldface):
 +
 
 +
  Please enter temperature in Fahrenheit: '''12'''
 +
 
 +
12 degrees Fahrenheit is -11.11111111111111 Celsius.
 
   
 
   
+
 
+--------------------------------------------+
+
:(We will not worry about the extra length of the Celsius number for this lab.)
| 0 day(s) 1 hour(s) 1 minute(s) 2 second(s) |
 
+--------------------------------------------+
 
 
   
 
   
 
<br />
 
<br />
  
=Single for-loops=
 
 
<br />
 
<br />
==Loops using the '''range()''' function==
+
=Moodle Submission=
 
<br />
 
<br />
* For this section of the lab, open IDLE and create the different program sections below in the edit window, or in the Python shell window.  I am using the python shell in the examples.
+
* Write a program that prompts the user for 2 integer numbers representing a low and a high temperature, expressed in Farhenheit, and outputs all the temperatures in between, with their equivalent Celsius.
  
 +
* Below is an example of interaction between the user and her program:
 
<br />
 
<br />
<source lang="python">
+
:::<source lang="text">
>>> for n in [0, 1, 2, 3]:
+
Enter low temperature: 20
print( n )
+
Enter high temperature: 40
  
>>> for n in range( 4 ):
+
Fahrenheit Celsius
print( n )
+
20        -6.66666666667
 +
21        -6.11111111111
 +
22        -5.55555555556
 +
23        -5.0
 +
24        -4.44444444444
 +
25        -3.88888888889
 +
26        -3.33333333333
 +
27        -2.77777777778
 +
28        -2.22222222222
 +
29        -1.66666666667
 +
30        -1.11111111111
 +
31        -0.555555555556
 +
32        0.0
 +
33        0.555555555556
 +
34        1.11111111111
 +
35        1.66666666667
 +
36        2.22222222222
 +
37        2.77777777778
 +
38        3.33333333333
 +
39        3.88888888889
 +
40        4.44444444444
 +
</source>
 +
<br />
 +
* Note: The space between the temperatures printed on the same line can be created by a simple string of 7 spaces.
 +
* Submit your program to Moodle, in the Lab 2 section.
  
>>> for n in range( 1, 4 ):
+
<br />
print( n )
+
<br />
 +
<showafterdate after="20150207 00:00" before="20150601 00:00">
 +
<br />
 +
=Solution Programs=
 +
<br />
 +
<source lang="python">
 +
# lab2.py
 +
# D. Thiebaut
 +
# The program prompts the user for 2 integer temperatures
 +
# and outputs a table of all temperatures ranging between the
 +
# two values, last value included.
 +
temp1 = eval( input( "Enter low temperature: " ) )
 +
temp2 = eval( input( "Enter high temperature: " ) )
 +
print()
 +
print( "Fahrenheit Celsius" )
 +
for temp in range( temp1, temp2+1 ):
 +
    print( temp, "      ", (temp-32)*5/9 )
  
>>> for n in range( -1, 4 ):
 
print( n )
 
  
>>> for n in range( 5, 10 ):
 
print( n )
 
 
>>> for n in range( 0, 10, 2 ):
 
print( n )
 
 
>>> for n in range( 1, 10, 2 ):
 
print( n )
 
 
>>> for n in range( 10, 0, -2 ):
 
print( n )
 
 
 
</source>
 
</source>
 
<br />
 
<br />
* Do you understand how the range() function works? 
+
</showafterdate>
** If you give it only 1 number, it will generate a series of numbers starting at 0 and going up to that number, but not including it, in steps of 1.
+
<br />
** If you give it 2 numbers, it will use the first one as the start, and the second at the stop, and will generate all the integers between the two, in steps of 1.  The stop number is never used.
+
<onlydft>
** IF you give it 3 numbers, the 3rd one is the step.  It can be positive or negative.
+
=Moodle VPL Module=
 +
<br />
 +
==vpl_run.sh==
 +
<br />
 +
<source lang="bash">
 +
#! /bin/bash
  
 +
cat > vpl_execution <<EOF
 +
#! /bin/bash
  
* Now, your turn:
+
prog=lab2.py
 +
python=/usr/local/bin/python3.4
  
; List of even numbers:
+
\$python \$prog
: write a loop that prints all the even numbers between 4 and 20; 4, and 20 included.
 
  
;List of odd numbers:
+
EOF
:write a loop that prints all the odd numbers between -3 and 19, -3, and 19 included.
 
  
=Lists and Operations on Lists=
+
chmod +x vpl_execution
  
* Try the following Python statements in the Python shell (interactive mode).
+
</source>
 +
<br />
 +
==vpl_evaluate.sh==
 +
<source lang="bash">
 +
#! /bin/bash
 +
# D. Thiebaut
  
      >>> students = [ "alice", "kate", "renee"]
+
cat > vpl_execution <<EEOOFF
   
+
#! /bin/bash
      >>> students
+
#set -x
 
      >>> students.append( "monique" )
 
 
      >>> students
 
 
   
 
   
      >>> students = []
+
# --- program tested (no extension) ---
+
prog=lab2.py
      >>> students
+
solutionProg=lab2sol.py
 
      >>> 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=
+
# --- Python ----
 +
#python=/usr/local/bin/python3.4
 +
python=/usr/bin/python3.3
  
* 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!
+
# =================================================
 +
# Pick 2 random inputs to test program with
 +
TEMP1=\$RANDOM
 +
let "TEMP1 %= 30"
 +
let "TEMP2 = TEMP1 + 6"
  
      # lab2seq.py
+
#echo "TEMP1 = \$TEMP1"
      #  
+
#echo "TEMP2 = \$TEMP2"
      # 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.
+
echo \$TEMP1 > input
 +
echo \$TEMP2 >> input
  
*Add a '''pig''' to your farm, and make sure it gets listed by the program.
+
# =================================================
 +
# generate user output and exptect output
 +
\$python \$prog < input > userOut
 +
\$python \$solutionProg < input > expectedOut
  
* When you are done with the addition of the pig, observe another way for the program to do the same thing:
 
  
      # lab2seq2.py
+
# =================================================
      #
+
# function that prints the difference between user and expected output
      farm = []              # create an empty farm
+
incorrectOutput() {
      farm.append( "dog" )  # add a dog to it
+
        echo "Comment :=>>- Your output is incorrect."
      farm.append( "cat" )  # then a cat
+
        #--- display test file ---
      farm.append( "horse" ) # then a horse
+
        echo "<|--"  
      farm.append( "pig" )  # and a pig
+
        echo "Your program tested with"
+
        echo "temperatures ranging from"
      # print the contents of the farm
+
        echo "\$TEMP1 to \$TEMP2"
      for animal in farm:
+
        echo "--|>"
          print animal
 
  
;Modification #1:  
+
        echo "Comment :=>> ---------------"
: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)
+
        echo "Comment :=>>- Your output:"
 +
        echo "Comment :=>> ---------------"
 +
        echo "<|--"
 +
        cat userOut
 +
        echo "--|>"
 +
        echo ""
 +
        echo "Comment :=>> ---------------"
 +
        echo "Comment :=>>- Expected output: "
 +
        echo "Comment :=>> ---------------"
 +
        echo "<|--"
 +
        cat expectedOut
 +
        echo "--|>"
  
;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
+
# function that tells user of program crash or infinite loop, and what the test was.
+
timeoutOutput() {
        animal? <u>'''sheep'''</u>
+
    if [ "\$1" ]; then  # if there's a parameter
         animal? <u>'''dog'''</u>
+
         i=\$1
         animal? <u>'''bear'''</u>
+
         echo "Comment :=>>- Your program has timed out or crashed."
        animal? <u>'''mouse'''</u>
 
 
        Your farm now contains
 
        animal #1 : a sheep
 
        animal #2 : a dog
 
        animal #3 : a bear
 
        animal #4 : a mouse
 
  
=Old MacDonald's Farm=
+
        #--- display test file ---
 +
        echo "Comment :=>>- Your program tested with:"
 +
        echo "<|--"
 +
        cat data\${i}.txt
 +
        echo "--|>"
 +
    fi
 +
}
  
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.  
+
# function that removes non-digits, extra spaces, and extra blank lines from text file.
<center>
+
cleanup () {
<videoflash>7_mol6B9z00</videoflash>
+
    if [ "\$1" ]; then  # if there's a parameter
</center>
+
       
If you don't know it, this YouTube video will get you acquainted with it. :-)
+
        #--- remove non numbers and non minus---
 +
        cat \$1 | sed 's/[^0-9*.0-9\ -]*//g' > dummy.out
 +
        mv dummy.out \$1
 +
 +
        #--- remove multiple spaces ---
 +
        cat \$1 | sed 's/  */ /g' > dummy.out
 +
        mv dummy.out \$1
  
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.
+
        #--- remove blank lines ---
 +
        cat \$1 | sed '/^\s*\$/d' > dummy.out
 +
        mv dummy.out \$1
 +
  fi
 +
}
  
Here's the beginning program which you have to modify:
+
cleanup userOut
 +
cleanup expectedOut
  
    def main():
+
#echo "userOut = "
        # start with four animals in the farm
+
#cat userOut
        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:
+
#echo "expectedOut = "
 +
#cat expectedOut
  
    Old MacDonald had a farm, E-I-E-I-O
+
#--- compute difference ---  
    And on his farm he had a horse, E-I-E-I-O
+
diff -y -w --ignore-all-space userOut expectedOut > diff.out
    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)
+
#--- reject if different ---
 +
if ((\$? > 0)); then
 +
      incorrectOutput
 +
      grade=70
 +
      # --------------------- REWARD IF CORRECT OUTPUT -----------------
 +
else
 +
      #--- good output ---
 +
      echo "Comment :=>>- Congrats, your output is correct."
 +
      echo "Comment :=>> --------------------------------."
 +
      echo "<|--"                                                                           
 +
      echo "Your program tested with"                                                       
 +
      echo "temperatures ranging from"                                                     
 +
      echo "\$TEMP1 to \$TEMP2"                                                             
 +
      echo ""
 +
      cat userOut
 +
      echo "--|>"
 +
      grade=100
 +
fi
  
==Second modification==
+
# =================================================
 +
# Report grade
 +
if (( grade > 100 )); then
 +
  grade=100
 +
fi
 +
echo "Grade :=>> \$grade"
  
* 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==
+
exit
  
* 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? <u>'''10'''</u>
+
EEOOFF
      * * * * * * * * * * ! ! ! ! ! ! ! ! ! !
 
 
   
 
   
      How many stars? <u>'''20'''</u>
+
chmod +x vpl_execution
      * * * * * * * * * * * * * * * * * * * *
 
 
      How many stars? <u>'''1'''</u>
 
      * ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
 
       
 
  
 +
</source>
 +
<br />
 +
==lab2sol.py==
 +
<br />
 +
<source lang="python">
 +
def prompt2():
 +
    temp1 = eval( input( "Enter low temperature: " ) )
 +
    temp2 = eval( input( "Enter high temperature: " ) )
 +
    print()
 +
    print( "Fahrenheit Celsius" )
 +
    for temp in range( temp1, temp2+1 ):
 +
        print( temp, "      ", (temp-32)*5/9 )
  
  
 +
prompt2()
  
 +
</source>
 +
<br />
 +
</onlydft>
 
[[Category:CSC111]][[Category:Labs]]
 
[[Category:CSC111]][[Category:Labs]]

Latest revision as of 20:18, 3 February 2015

--D. Thiebaut (talk) 17:01, 3 February 2015 (EST)


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.


Definite for-loops


Loops that use the range() function


  • For this section of the lab, open IDLE and create the different program sections below in the Python shell window.


>>> for n in range( 4 ):
	print( n )

>>> for n in range( 1, 4 ):
	print( n )

>>> for n in range( -1, 4 ):
	print( n )

>>> for n in range( 5, 10 ):
	print( n )

>>> for n in range( 0, 10, 2 ):
	print( n )

>>> for n in range( 1, 10, 2 ):
	print( n )

>>> for n in range( 10, 0, -2 ):
	print( n )


  • Do you understand how the range() function works?
    • If you give it only 1 number, it will generate a series of numbers starting at 0 and going up to that number, but not including it, in steps of 1.
    • If you give it 2 numbers, it will use the first one as the start, and the second at the stop, and will generate all the integers between the two, in steps of 1. The stop number is never used.
    • IF you give it 3 numbers, the 3rd one is the step. It can be positive or negative.


Challenge #1: Range-Controlled Loops

QuestionMark1.jpg


Now, your turn:

List of even numbers
write a loop that prints all the even numbers between 4 and 20; 4, and 20 included.
List of odd numbers
write a loop that prints all the odd numbers between -3 and 19, -3, and 19 included.
List odd numbers in reverse order
write a loop that prints all the odd numbers starting at 9 and going down to 1, included.


Definite For-Loops that use Lists


  • We can use explicit lists to generate similar outputs. For example, the output of the first two examples in the previous section could have been generated by the following loops:


>>>for n in [0, 1, 2, 3]:
            print( n )

>>>for n in [1, 2, 3]:
            print( n )



Challenge #2: List-Controlled Loops

QuestionMark2.jpg


Solve the 3 problems of Challenge 1 above, using lists instead of the range() function.








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
# 
 
# print the contents of the farm
for animal in  [ "dog", "cat", "horse" ]:
     print animal


  • Add a pig to your list of animals, and make sure it gets listed by the program.


Modification #1
Change the for-loop of your program so that it reads:


       counter = 0
       for animal in  [ "dog", "cat", "horse", "pig" ]:
           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):
       Your farm 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 most 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:

     
# display the names of the animals
for animal in  [ "horse", "pig", "dog", "cat" ]:
      print animal


Challenge #3: Output Song Lyrics

QuestionMark3.jpg


  • Modify the program above so that it uses the loop, and outputs 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)

The input() Function


Try the following statements in the console window. Again, some of these might generate errors. It is important for you to understand why these errors occur.


>>> firstName = input( "Enter your first name: " )
>>> firstName

>>> lastName = input( "Enter your last name: " )
>>> lastName

>>> print( firstName, lastName )

>>> x = input( "enter a number: " )
>>> x

>>> x + 5

>>> x = input( "Enter a number: " )
>>> x

>>> x = eval( answer )
>>> x
>>> x + 5

>>> y = eval(  "314.56789" )
>>> y



Challenge #4: Gathering student information

QuestionMark4.jpg


Write a python program that asks the user for her name, box number, 99-Id number, and phone number, and that outputs it back on the screen nicely formatted.

Example (the information entered by the user is in boldface):

your first name? Allie
your last name? Gator
your box number? 1234
your phone number? 413 456 7890
your Smith Id? 990123456


Name:   Allie Gator (990123456)
box #:  1234
phone:  413 456 7890



Challenge #5: Printing the student information it in a (half) box

QuestionMark5.jpg


  • Same idea as with the previous challenge but after inputing the information from the user, the program outputs it in a half-box!

Example (user input in in boldface):

your first name?   Mickey
your last name?    Mouse
your box number?   1234
your phone number? 413 456 7890
your Id number?    990111222

+---------------------------------------
| Name:   Mickey Mouse ( 990111222 )
| Box:     1234
| Phone:  413 456 7890 
+---------------------------------------


  • The length of the bars is unimportant.



Challenge #6: Temperature Converter

QuestionMark8.jpg


  • Write a program that prompts the user for a temperature expressed in Fahrenheit, and outputs the equivalent temperature in Celsius.
  • The equation for temperature conversion is: Celsius = ( Fahrenheit -32 ) * 5 / 9
  • Here is an example of the way your program will work (the user input is in boldface):
Please enter temperature in Fahrenheit: 12
 
12 degrees Fahrenheit is -11.11111111111111 Celsius.

(We will not worry about the extra length of the Celsius number for this lab.)



Moodle Submission


  • Write a program that prompts the user for 2 integer numbers representing a low and a high temperature, expressed in Farhenheit, and outputs all the temperatures in between, with their equivalent Celsius.
  • Below is an example of interaction between the user and her program:


Enter low temperature: 20
Enter high temperature: 40

Fahrenheit Celsius
20         -6.66666666667
21         -6.11111111111
22         -5.55555555556
23         -5.0
24         -4.44444444444
25         -3.88888888889
26         -3.33333333333
27         -2.77777777778
28         -2.22222222222
29         -1.66666666667
30         -1.11111111111
31         -0.555555555556
32         0.0
33         0.555555555556
34         1.11111111111
35         1.66666666667
36         2.22222222222
37         2.77777777778
38         3.33333333333
39         3.88888888889
40         4.44444444444


  • Note: The space between the temperatures printed on the same line can be created by a simple string of 7 spaces.
  • Submit your program to Moodle, in the Lab 2 section.



<showafterdate after="20150207 00:00" before="20150601 00:00">

Solution Programs


# lab2.py
# D. Thiebaut
# The program prompts the user for 2 integer temperatures
# and outputs a table of all temperatures ranging between the
# two values, last value included.
temp1 = eval( input( "Enter low temperature: " ) )
temp2 = eval( input( "Enter high temperature: " ) )
print()
print( "Fahrenheit Celsius" )
for temp in range( temp1, temp2+1 ):
     print( temp, "       ", (temp-32)*5/9 )


</showafterdate>


...