Contents

  1. avgData.py
  2. descendSort.py
  3. file_write.py
  4. swap.py

avgData.py 1/4

[
top][prev][next]
# Computes the average high temperature from a file that contains the daily
# high temperatures for last year at one location.
# CSCI 111

DATAFILE="data/virginia.dat"

fileobj = open(DATAFILE, "r")

totalTemps = 0
numTemps = 0

# read through the file, line by line
for line in fileobj:
    totalTemps = totalTemps + float(line)
    numTemps += 1

fileobj.close() # closing the file as soon we can

average = totalTemps/numTemps

print("The average temperature is %.2f" % average)
    

descendSort.py 2/4

[
top][prev][next]
# Demonstrate passing lists to functions
# CSCI111

# this function tests the descend sort function
def main():
    # test descendSort3Nums
    list = [1,2,3]
    descendSort3Nums(list)
    print(list)

    list = [0, 5, -3]
    descendSort3Nums(list)
    print(list)
    
    list = [7,4,1]
    descendSort3Nums(list)
    print(list)
    
    list = [-1, -1, -3]
    descendSort3Nums(list)
    print(list)
    
    list = [-1, -5, -3]
    descendSort3Nums(list)
    print(list)

def descendSort3Nums(list3):
    """
    Parameter: a list containing three numbers
    Sorts the list in descending order
    Note: does not return anything, no output
    """
    if list3[1] > list3[0]:
        # swap 'em
        tmp = list3[0]
        list3[0] = list3[1]
        list3[1] = tmp

    if list3[2] > list3[1]:
        # swap 'em
        tmp = list3[1]
        list3[1] = list3[2]
        list3[2] = tmp
    
    if list3[1] > list3[0]:
        # swap 'em
        tmp = list3[0]
        list3[0] = list3[1]
        list3[1] = tmp
        
main()

file_write.py 3/4

[
top][prev][next]
# Writes content from a user to a file
# by Sara Sprenkle

PROMPT = "Enter the next line in the file: "

outfilename = input("What is the name of your output file? ")
numLines = eval(input("How many lines do you want to write? "))

# create a new file object, in "write" mode
dataFile = open(outfilename, "w")

for x in range(numLines):
    userinput = input(PROMPT)
    # write the user's input to the file
    dataFile.write(userinput)
    # write a newline after each input from the user
    dataFile.write("\n")

# close the file with the method "close"
dataFile.close()

swap.py 4/4

[
top][prev][next]
# Attempt at swapping two variables in a function
# FAIL!  Swapping within a function won't work. :(
# Why?  Only passing in *copies* of parameters, not the original variables

def swap( a, b):
    tmp = a
    a = b
    b = tmp
    print(a, b)

x = 5
y = 7

swap(x, y)

# at the end, y should be 5 and x should be 7
print("x =", x)
print("y =", y) 


Generated by GNU Enscript 1.6.6.