You are on page 1of 1

H OMEWORK A SSIGNMENT 2

Due date: Friday, January 27, 2017


Objective: To write and run a python program that reads in some numbers from
a data file, counts them, performs some computations involving the numbers, and
displays the results.
Problem: The program reads some numbers from a text file, computes the sum
and average of all positive numbers, the sum and average of all non-positive num-
bers, and lastly, the sum and average of all numbers. The numbers are stored in
a file, one number per line. The number of entries in the file is not known before-
hand. The program should have the following input and output.
(1) Input: A column of numbers of type float. Read the numbers from a text file
which has the name infile.dat. Your program should work correctly for an
input file containing any number of data values.
(2) Output: Display the counts, sums and averages for:
(a) the positive numbers.
(b) the non-positive numbers.
(c) all of the numbers.
Reading numbers from a text file. Assume the numbers are stored one per line in
a text file named input.dat. Use your favorite text editor to create the file and type
in the numbers. The following python script first opens the file in read-only mode.
Inside the python script, the file is referenced by the identifier f5. Using a for loop,
the script scans through the input file one line at a time. With each iteration of the
loop, one line is read from the input file. After a line of text is scanned, it is stored
in a character string which is called input_str. Using float(input_str), the
string is converted to a numerical data value. The numerical value of the number
is stored in the variable called x. Lastly, the value of x is printed to the screen.
f5 = open("input.dat","r") # open the file for reading
for input_str in f5: # read one line from f5
x = float(input_str)
print x
Test your program using a data file on your own computer, but do not submit your
data file to me.
Submit your program: A comment at the top of the program should identify
yourself and the assignment that you are submitting:
"""
Student name
Homework number 2
"""
Send an email message to Ford@fau.edu containing:
(1) For the return address, use your fau.edu email address.
(2) The subject line should be: Subject: MAD2502, HW 2
(3) Include the python program as an attachment (of type text/plain) using
this name: hw2.py.

You might also like