Difference between revisions of "CSC111 Lab 9"

From dftwiki3
Jump to: navigation, search
(More challenging Loop 3)
(Applying this method to other Web Pages)
 
(40 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
{|
 +
| width="40%" |
 +
__TOC__
 +
|
 
<bluebox>
 
<bluebox>
 
This lab deals with while loops.  You may find the [[CSC111_Exercises_on_Loops |exercises]] we did in class yesterday (and their [[CSC111_Exercises_on_Loops#Solution_Program | solutions]]) useful for some of the questions below!
 
This lab deals with while loops.  You may find the [[CSC111_Exercises_on_Loops |exercises]] we did in class yesterday (and their [[CSC111_Exercises_on_Loops#Solution_Program | solutions]]) useful for some of the questions below!
 
</bluebox>
 
</bluebox>
 +
|}
  
 
==While Loops==
 
==While Loops==
Line 21: Line 26:
 
</PRE></code>
 
</PRE></code>
  
Verify that it runs correctly and keeps on prompting the user as long as the  input is not between 3 and 9.
+
* Verify that it runs correctly and keeps on prompting the user as long as the  input is not between 3 and 9.
  
Put the input and the while loop inside a function which you will call '''input3_9()''', which will return the number entered by the user, and which will keep on prompting the user for a new number as long as it is not in the  valid range.  Your main program should look something like this:
+
* Put the input and the while statements inside a function which you will call '''input3_9()''', which will return the number entered by the user, and which will keep on prompting the user for a new number as long as it is not in the  valid range.  Your main program should look something like this:
  
 
<code><PRE>
 
<code><PRE>
Line 34: Line 39:
  
 
===Loop 2===
 
===Loop 2===
Using <b>input3_9()</b> as an example,  create another function called '''inputDollars()''' that asks the user to enter
+
* Using <b>input3_9()</b> as an example,  create another function called '''inputDollars()''' that asks the user to enter a number and returns only numbers that are multiples of 5.  Below is what
a number and returns only numbers that are multiples of 5.  Below is what
+
your main program will look like.  
your main program will look like. Make sure your new function is robust
+
 
and accepts only numbers of the form 0, 5, 10, 15, 20, etc.
+
* Make sure your new function is robust and accepts only numbers of the form 0, 5, 10, 15, 20, etc.
  
 
<code><PRE>
 
<code><PRE>
Line 50: Line 55:
  
 
===More challenging Loop 3===
 
===More challenging Loop 3===
Modify your function (or add a new one), such that it will only accept from the user numbers of the form 5, 10, 20, 50, and 100.
 
  
'' '''Hints:''' remember that lists are easy to create, and that the <b>"in"</b> operator can be used as a boolean operator, returning True if an item is <b>in</b> a list, and False otherwise...''
+
* Modify your function (or add a new one), such that it will only accept from the user numbers of the form 5, 10, 20, 50, and 100.
 +
 
 +
('''Hints:''' ''Remember that lists are easy to create, and that the <b>"in"</b> operator can be used as a boolean operator, returning True if an item is <b>in</b> a list, and False otherwise...'')
  
 
==One-and-a-half While loops==
 
==One-and-a-half While loops==
Line 58: Line 64:
 
Another way to write the loop of the previous example is to do this:
 
Another way to write the loop of the previous example is to do this:
  
<code><PRE>
+
  while True:
    while True:
 
 
         x = input( "> " )
 
         x = input( "> " )
         if <i>&lt;x is within the range--you figure out how to write it&gt;</I>
+
         if ''x is within the range--you figure out how to write it'' :
 
               break
 
               break
 
         print "Invalid input"
 
         print "Invalid input"
</pre></code>
 
  
 
Modify your previous program and use this method for implementing ''robustness''.
 
Modify your previous program and use this method for implementing ''robustness''.
Line 72: Line 76:
 
The program below computes the average of an unknown number of input data.
 
The program below computes the average of an unknown number of input data.
  
Store it in a file called '''sumNum.py''' and run it.  Verify that it  gives you the average of the series of numbers you have entered.
+
* Store it in a file called '''sumNum.py''' and run it.   
 +
 
 +
* Verify that it  gives you the average of the series of numbers you have entered.
  
 
<code><PRE>
 
<code><PRE>
Line 91: Line 97:
 
</PRE></code>
 
</PRE></code>
  
Modify the program and remove the count variable.  Instead, keep appending
+
* Modify the program and remove the count variable.  Instead, keep appending the numbers entered by the user to a list which we'll call <b>numbers</b> for simplicity.  If you have a list of numbers, you can easily find how many numbers it contains by using the <b>len()</b> function.
the numbers entered by the user to a list which we'll call <b>numbers</b>
 
for simplicity.  If you have a list of numbers, you can easily find how many
 
numbers it contains by using the <b>len()</b> function.
 
  
Go ahead and make your program print the average using <b>len( numbers )</b> instead
+
* Go ahead and make your program print the average using <b>len( numbers )</b> instead of <b>count</b>.
of <b>count</b>.
 
  
 
==Redirected input==
 
==Redirected input==
Line 122: Line 124:
 
   python sumNum.py < data.txt
 
   python sumNum.py < data.txt
  
* The output is going to be messed up because the numbers will not be typed at the keyboard and will not appear on the screen, but they will still be absorbed by the program. Verify that the average reported is correct, though!
+
:What the '''&lt; data.txt''' part of the command does is to tell Linux that it should ''redirect'' the input of the python program to use data from the file '''data.txt''' instead of getting it from the keyboard.
  
* You have just discovered how to feed huge amounts of data to your program.  Simply write the program such that it reads the information that it needs with input() or raw_input() and when you run your program you ''redirect'' its input with the "<" symbol on the command line, and provide the name of a file that contains the data formatted the way the program expects.
+
* The output of your program with the redirection is going to be '''messed up''' because the numbers will not be typed at the keyboard and will not appear on the screen.  The numbers will not be visible on the screen any longer, but they still are provided to the '''input()''' function.
  
 +
* Verify that the average reported is correct, though!
 +
 +
* You have just discovered how to feed huge amounts of data to your program.  Simply write the program such that it reads the information that it needs with '''input()''' or '''raw_input()''' and when you run your program you ''redirect'' its input with the "<" symbol on the command line, and provide the name of a file that contains the data formatted the way the program expects.
 +
 +
 +
* Use redirection for all the programs you wrote so far, today.  In each case put the input for your program in a text file, then run the program feeding it the input from the file with the '''&lt;''' operator.
 +
<!--
 
==While loops and elevators==
 
==While loops and elevators==
  
Line 132: Line 141:
  
 
<P>  
 
<P>  
<PRE>
+
<code><PRE>
 
def main():
 
def main():
     people = ["JT", 150, "TJ", 80, "TT", 120, "BT", 204, "Mike", 12, \
+
     people = [ ("JT", 150), ("TJ", 80), ("TT", 120), ("BT", 204), ("Mike", 12), \
               "AF", 27, "Lea", 78, "Leo", 180, "Al", 55, "GK", 110,  \
+
               ("AF", 27), ("Lea", 78), ("Leo", 180), ("Al", 55), ("GK", 110),  \
               "JR", 111, "VB", 76 ]
+
               ("JR", 111), ("VB", 76) ]
</pre>  
+
</pre></code>
<P>
+
 
 
Above is a list of people and their weight.  They are waiting in front
 
Above is a list of people and their weight.  They are waiting in front
 
of an elevator.  The maximum weight allowed on the elevator is 300 lbs.
 
of an elevator.  The maximum weight allowed on the elevator is 300 lbs.
<P>
+
 
 
;Question 1
 
;Question 1
:What is the maximum number of people we can fit on the elevator?
+
:What is the maximum number of people we can fit in the elevator?
 +
 
 
;Question 2
 
;Question 2
 
:What is the total weight of these people?
 
:What is the total weight of these people?
 +
 
;Question 3 (challenging)
 
;Question 3 (challenging)
 
:What is the name of the people in the elevator?
 
:What is the name of the people in the elevator?
  
 
Of course, the solution involves a while loop!
 
Of course, the solution involves a while loop!
You will find the <b>index( )</b> function useful for Question 3.
+
-->
 +
 
 +
=Accessing Web Page=
 +
<bluebox> In this Lab section we are going to write a Python program that will access this page, read this contents and extract the number representing the current temperature, and print it on the screen.</bluebox>
 +
 
 +
 
 +
[[Image:CurrentTemperatureNoho.png | frame | right]]
 +
 
 +
* Point your favorite browser to this URL: http://www.weather.com/weather/today/01060 (note that the numbers at the end of the URL represent the zip-code for Northampton).
 +
 
 +
 
 +
* Observe that it displays the ''current'' temperature for Northampton
 +
 
 +
 
 +
* Make a note of the temperature that is being currently reported (the picture on the right hand-side is not current, and was taken a few days ago).
 +
 
 +
 
 +
* Depending on the browser you are using, figure out a way to see the source code of the page, i.e. the html contents of the page.  With Firefox, this is done by right-clicking on the page and selecting '''View Page Source'''.  Wight Safari, you also right-click and select '''View Source'''. 
 +
 
 +
 
 +
* Scroll down the source code and locate where the temperature is displayed.  Searching for the words "''Feels like''" is a good way to locate the place.  This should look something like this:
 +
 
 +
  &lt;div class="cc72tempWrapRight"&gt;
 +
  &lt;div class="ccTemp">52&amp;deg; F&lt;/div&gt;
 +
  &lt;div class="cc73feelLike"&gt;Feels Like: &lt;b&gt;52&deg; F&lt;/b&gt;&lt;/div&gt;
 +
 
 +
  &lt;div class="ccWind"&gt;Wind:
 +
 
 +
* To get the temperature, then, if we can get the whole html code in a string, all we need to do is search for the strings "ccTemp"&gt;, and "&amp;deg;", and take whatever is in between, and we'll have the temperature in area code 01060.
 +
 
 +
* Let's start:
 +
*;Step 1
 +
::Create a program called getTemperature.py with the following code:
 +
 
 +
import urllib2
 +
import sys
 +
 
 +
#--- some constants used by the program ---
 +
BASEURL = "http://www.weather.com/weather/today/01060"
 +
 +
def getTemperature( ):
 +
  url = BASEURL
 +
  print url
 +
  f = urllib2.urlopen( url )
 +
  htmlText = f.read()
 +
  print htmlText
 +
 +
def main():
 +
  getTemperature()
 +
 +
main()
 +
 
 +
*; Step 2
 +
:: Run the program
 +
 
 +
 
 +
*; Step 3
 +
:: Observe that it prints out a lot of text, which, if you check carefully, should match exactly the '''source page''' in your browser.
 +
 
 +
 
 +
*; Step 4
 +
:: Read again how the string method '''find()''' works in the http://python.org pages (use Google to search for "python string methods" and open the page at '''python.org''' with title '''String Methods'''.)
 +
 
 +
 
 +
*; Step 5
 +
::Use the '''find()''' string method to ''slice away'' the temperature number from the html text.
 +
 
 +
 
 +
*; Step 6
 +
:: Make your program print it on the screen.
 +
 
 +
 
 +
*; Step 7
 +
:: Modify your program so that it prompts the user for a zip-code, then reports the temperature at that zip-code.
 +
 
 +
 
 +
==Applying this method to other Web Pages==
 +
[[Image:LeoSign.jpg | right]]
 +
Adapt this method to the astrology pages of '''Cafe Astrology''', at http://www.cafeastrology.com/.  Locate the section '''Signs of the Zodiac''' in the middle of the page, and try a few of them (Aries  Taurus  Gemini  Cancer  Leo  Virgo  Libra  Scorpio  Sagittarius  Capricorn  Aquarius  Pisces).  Check the URL for each one.  You will notice that the Url for '''Aries''' is http://www.cafeastrology.com/zodiacaries.html, the Url for '''Gemini''' is http://www.cafeastrology.com/zodiacgemini.html, etc.
 +
 
 +
So, by just inserting the lowercase version of the sign in the Url, between '''"zodiac"''' and '''".html"''', you can access the page of interest. 
 +
 +
Write a program that prompts the user for a zodiac sign, goes to the appropriate Web page at '''Cafe Astrology''' and reports some information found on that page, for example the first paragraph following "'''Comparison with its symbol...'''".
 +
<br />
 +
 
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
[[Category:CSC111]][[Category:Python]][[Category:Labs]]

Latest revision as of 21:08, 16 November 2011

This lab deals with while loops. You may find the exercises we did in class yesterday (and their solutions) useful for some of the questions below!

While Loops

Loop 1

Create the following program:

def main():
    print "Enter a number between 3 and 9: "
     
    x = input( "> " )
    while not ( 3 <= x <= 9 ):
        print "invalid input!"
        x = input( "> " )
 
    print "x = ",x
    
main()
  • Verify that it runs correctly and keeps on prompting the user as long as the input is not between 3 and 9.
  • Put the input and the while statements inside a function which you will call input3_9(), which will return the number entered by the user, and which will keep on prompting the user for a new number as long as it is not in the valid range. Your main program should look something like this:
def main():
    x = input3_9()
    print "x = ", x

main()

Loop 2

  • Using input3_9() as an example, create another function called inputDollars() that asks the user to enter a number and returns only numbers that are multiples of 5. Below is what

your main program will look like.

  • Make sure your new function is robust and accepts only numbers of the form 0, 5, 10, 15, 20, etc.
def main():
    x = input3_9()
    print "x = ", x

    dollars = inputDollars()
    print "dollars = ", dollars
main()

More challenging Loop 3

  • Modify your function (or add a new one), such that it will only accept from the user numbers of the form 5, 10, 20, 50, and 100.

(Hints: Remember that lists are easy to create, and that the "in" operator can be used as a boolean operator, returning True if an item is in a list, and False otherwise...)

One-and-a-half While loops

Another way to write the loop of the previous example is to do this:

  while True:
       x = input( "> " )
       if x is within the range--you figure out how to write it :
             break
       print "Invalid input"

Modify your previous program and use this method for implementing robustness.

While loops with sentinels

The program below computes the average of an unknown number of input data.

  • Store it in a file called sumNum.py and run it.
  • Verify that it gives you the average of the series of numbers you have entered.
def main():
    sum = 0
    count = 0
    print "Enter numbers (enter a negative number to quit)"
    x = input( "> " )
    while ( x >= 0 ):
        sum = sum + x
        count = count + 1
        x = input( "> " )

    if ( count>0 ):
        print "\n\naverage = %f" % ( float( sum )/count )

main()
  • Modify the program and remove the count variable. Instead, keep appending the numbers entered by the user to a list which we'll call numbers for simplicity. If you have a list of numbers, you can easily find how many numbers it contains by using the len() function.
  • Go ahead and make your program print the average using len( numbers ) instead of count.

Redirected input

We mentioned in class yesterday that sometimes the input is not provided at the keyboard, but from a file.

We'll see how to feed data to your program by not typing it but instead by telling the program to read the contents of a file instead of getting the data from the keyboard.

We are going to use the same program as in the previous question, so make sure it works well!

  • Create a file called data.txt using emacs. In it store the following lines:
1
2
3
4
5
-1
  • Save the file.
  • At the Linux prompt, enter the following command:
 python sumNum.py < data.txt
What the < data.txt part of the command does is to tell Linux that it should redirect the input of the python program to use data from the file data.txt instead of getting it from the keyboard.
  • The output of your program with the redirection is going to be messed up because the numbers will not be typed at the keyboard and will not appear on the screen. The numbers will not be visible on the screen any longer, but they still are provided to the input() function.
  • Verify that the average reported is correct, though!
  • You have just discovered how to feed huge amounts of data to your program. Simply write the program such that it reads the information that it needs with input() or raw_input() and when you run your program you redirect its input with the "<" symbol on the command line, and provide the name of a file that contains the data formatted the way the program expects.


  • Use redirection for all the programs you wrote so far, today. In each case put the input for your program in a text file, then run the program feeding it the input from the file with the < operator.

Accessing Web Page

In this Lab section we are going to write a Python program that will access this page, read this contents and extract the number representing the current temperature, and print it on the screen.


CurrentTemperatureNoho.png


  • Observe that it displays the current temperature for Northampton


  • Make a note of the temperature that is being currently reported (the picture on the right hand-side is not current, and was taken a few days ago).


  • Depending on the browser you are using, figure out a way to see the source code of the page, i.e. the html contents of the page. With Firefox, this is done by right-clicking on the page and selecting View Page Source. Wight Safari, you also right-click and select View Source.


  • Scroll down the source code and locate where the temperature is displayed. Searching for the words "Feels like" is a good way to locate the place. This should look something like this:
 <div class="cc72tempWrapRight">
 <div class="ccTemp">52&deg; F</div>
 <div class="cc73feelLike">Feels Like: <b>52° F</b></div>
  
 <div class="ccWind">Wind: 
  • To get the temperature, then, if we can get the whole html code in a string, all we need to do is search for the strings "ccTemp">, and "&deg;", and take whatever is in between, and we'll have the temperature in area code 01060.
  • Let's start:
    Step 1
Create a program called getTemperature.py with the following code:
import urllib2
import sys
 
#--- some constants used by the program ---
BASEURL = "http://www.weather.com/weather/today/01060"

def getTemperature( ):
  url = BASEURL 
  print url
  f = urllib2.urlopen( url )
  htmlText = f.read()
  print htmlText

def main():
  getTemperature()

main()
  • Step 2
Run the program


  • Step 3
Observe that it prints out a lot of text, which, if you check carefully, should match exactly the source page in your browser.


  • Step 4
Read again how the string method find() works in the http://python.org pages (use Google to search for "python string methods" and open the page at python.org with title String Methods.)


  • Step 5
Use the find() string method to slice away the temperature number from the html text.


  • Step 6
Make your program print it on the screen.


  • Step 7
Modify your program so that it prompts the user for a zip-code, then reports the temperature at that zip-code.


Applying this method to other Web Pages

LeoSign.jpg

Adapt this method to the astrology pages of Cafe Astrology, at http://www.cafeastrology.com/. Locate the section Signs of the Zodiac in the middle of the page, and try a few of them (Aries Taurus Gemini Cancer Leo Virgo Libra Scorpio Sagittarius Capricorn Aquarius Pisces). Check the URL for each one. You will notice that the Url for Aries is http://www.cafeastrology.com/zodiacaries.html, the Url for Gemini is http://www.cafeastrology.com/zodiacgemini.html, etc.

So, by just inserting the lowercase version of the sign in the Url, between "zodiac" and ".html", you can access the page of interest.

Write a program that prompts the user for a zodiac sign, goes to the appropriate Web page at Cafe Astrology and reports some information found on that page, for example the first paragraph following "Comparison with its symbol...".