Skip to content

Instantly share code, notes, and snippets.

@acbart
Last active February 14, 2023 19:30
Show Gist options
  • Select an option

  • Save acbart/7b81fc35216ece96d65a656a68cb21e2 to your computer and use it in GitHub Desktop.

Select an option

Save acbart/7b81fc35216ece96d65a656a68cb21e2 to your computer and use it in GitHub Desktop.
Example Python Code for CISC320

The first file below (basic_example.py) demonstrates a simple Python program that reads a filename from standard input and processes it. Specifically, the helper function prints all the lines and also returns the last line of the file.

The second file (student_test.py) demonstrates some very basic unit testing of the helper function.

"""
Author: acbart@udel.edu
Updated: 2/4/2021
Description: A sample of taking a filename from stdin, loading it into a string
array, and printing out the first line.
"""
def print_all_lines(lines: list[str]) -> str:
""" Print each line, then return the last one. """
latest_line = None
for line in lines:
# Readlines includes the newline character
latest_line = line.strip()
print(latest_line)
return latest_line
if __name__ == "__main__":
# Get the filename from stdin
filename = input()
# Open the file and read in its contents
with open(filename) as data_file:
lines = data_file.readlines()
# Actually do the work
print_all_lines(lines)
import unittest
import basic_example
class TestLast(unittest.TestCase):
def test_gets_last(self):
actual = basic_example.print_all_lines(["1\n", "2\n", "3\n"])
self.assertEqual(actual, "3")
def test_handles_empty(self):
actual = basic_example.print_all_lines([])
self.assertEqual(actual, None)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment