Lists and File Output Continued

Today we continue our discussion on both lists and file input/output. We will cover how to write to a file and look more closely at the List object, its functions, and the special syntax that goes with it.

Reading: Chapter 8

Read Chapter 8 up to and including "Lists and Functions"

Today in Class

We will discuss and learn about:

You should be able to understand these programs.

Input any number of numbers and print them out to a file sorted.

# Input numbers from the user
nums = list()
x = input()
while x != "DONE":
      nums.append(float(x))
      x = input()
# Sort and print
fout = open("sorted.csv", "w")
nums.sort()
for num in nums:
      fout.write(str(num) + ", ")
print("Numbers sorted and printed to file sorted.csv")
fout.close()

Input a sentence, split its words, and find the name "Mr. X"

# Input a sentence
words = list()
x = input("Gimme a sentence: ")
words = x.lower().split()
mr = words.index("mr.")
if mr >= 0:
      print("Found someone named Mr.", words[mr+1])
else:
      print("No misters!")

This one is a bit longer, so jump right to a working Web version here to try it out.

# Command tool to add integers to a list.
# Also allows printing the list (dump), counting how
# many times a number appears in the list, and replacing
# all occurrences of an int with another int.
nums = list()

command = input(": ")
while command != "exit":
  # add 4 to the list
  if command.startswith("add"):
    num = int(command[4:])
    nums.append(num)

  # "count 4" (counts the occurrences of 4 in the current list)
  elif command.startswith("count"):
    num = int(command[6:])
    count = 0
    for x in nums:
      if x == num:
        count = count + 1
    print(count)

  # "dump" (print the current list)
  elif command == "dump":
    for num in nums:
      print(num, end=' ')
    print()

  # "change 4 9" (change all occurrences of 4 to 9)
  elif command.startswith("change"):
    parts = command.split()
    old = int(parts[1])
    new = int(parts[2])

    print("Changing", old, "to", new)
    for i in range(len(nums)):
      if nums[i] == old:
        nums[i] = new

  else:
    print("Unknown command!")    
      
  # Get the next command
  command = input(": ")
  

Here is an example of the above program running:

: add 4
: add 2
: add 9
: add 6
: count 3
0
: count 2
1
: add 9
: add 9
: add 1
: count 9
3
: dump
4 2 9 6 9 9 1 
: change 9 11
Changing 9 to 11
: dump
4 2 11 6 11 11 1 
: count 11
3
: done
Unknown command!
: exit