CSC111 Lab 9
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
- 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:
<div class="cc72tempWrapRight"> <div class="ccTemp">52° 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 "°", 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
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...".