Weekly Programming Topics
File Handling, Static and Dynamic Typing
Week 4 - File Handling, Static and · Dynamic Typing
File Handling, Static and Dynamic Typing
Week 4 – File Handling, Static and Dynamic Typing
What isin thislesson?
- Defining and Calling a Function(Recap)
- Value-Returning Functions and Modules
- Standard Library Functions
- Write Value-Returning Functions
- File Handling
- File Input and Output
- Using Loops to Process Files
- Processing Files -> Records/Objects
- Exceptions 11th January 2026 Tram Tran
3-3
- Defining and Calling a Function(Recap)
Defining and Calling a Function def function_name(): statement statement etc. Function header Block
3-4
- Defining and Calling a Function(Recap)
Defining and Calling a Function The function definition and the function call
6-5
- Value-Returning Functions Value-returning function:
- A group of statements that performs a specific task
- Executed when called
- Returns a value back to the part of the program that called it
6-6
2.1 Standard Library Functions Standard Library Functions: prewritten functions that perform commonly needed tasks.
- Already written and come with the language
- Make a programmer’s job easier
- Perform many commonly needed tasks
- Stored in files known as modules
- Include the import statement at the top of the program For example: input() raw_input() range()
6-7
2.1. Standard Library Functions Generating Random Numbers For example: # causes the interpreter to load the contents of the random module import random # causes the interpreter to load the contents of
number = random.randint(1, 100)
- function
- 6-8
- 2.1 Standard Library Functions
- Generating Random Numbers
- Program (random_numbers2.py)
function
6-8
2.1 Standard Library Functions Generating Random Numbers Program (random_numbers2.py)
6-9
2.1. The math Module Program (square_root.py)
6-10
2.2. Writing Your Own Value-Returning Functions Concept: A value-returning function has a return statement that returns value back to the part of the program that called it.
6-11
2.2 Writing Your Own Value-Returning Functions Using IPO Charts
- A tool used for designing and documenting functions
- IPO stands for Input, Processing, and Output
- Describes the input, processing, and output of a function
6-12
2.2 Writing Your Own Value-Returning Functions def function_name(): statement statement etc. return expression
- 6-13
- 2.2 Writing Your Own Value-Returning Functions
- Program (total_ages.py)
- 6-14
- 2.3 Writing Your Own Value-Returning Functions
6-13
2.2 Writing Your Own Value-Returning Functions Program (total_ages.py)
6-14
2.3 Writing Your Own Value-Returning Functions Making the Most of the return statement
def sum(num1, num2): result = num1 + num2
return result
def sum(num1, num2): return num1 + num2 6-15
2.3 Writing Your Own Value-Returning Functions Returning Multiple Values
first_name, last_name =get_name()
def get_name(): # Get the user’s first and last name.
first = raw_input(‘Enter your first name: ‘) last = raw_input(‘Enter your last name: ‘)
# Return both names. return first, last
2.3 Storing Functions In Modules
1-16
def read_string(prompt): return input(prompt) def read_float(prompt): return float(read_string(prompt)) def read_integer(prompt): return int(read_string(prompt)) def read_integer_in_range(prompt, min_value, max_value):
value = read_integer(prompt)
while value < min_value or value > max_value: print(f"Please enter a value between {min_value} and {max_value}.")
value = read_integer(prompt)
return value def read_boolean(prompt):
value = read_string(prompt).lower()
return value in ['y', 'yes'] def print_float(value, decimal_places): print(round(value, decimal_places)) Storing Functions In Modules
- Module file names should end in.py (input_functions.py)
- Place the module in the same folder as the program
- Using: import input_functions
File Handling
1-17 7-18
3.1 Introduction to File Input and Output Concept: When a program needs to save data for later use, it writes the data in a file. The data can be read from the file at a later time.
7-19
3.1 Introduction to File Input and Output Terms
- Saving data in a file = “writing data to” the file
- Output file = file that data is written to
- Retrieving data from a file = “reading data from” the file
- Input file = file that data is read from
7-20
3.1 Introduction to File Input and Output Types of Files Two types of files:
- Text file – contains data that has been encoded as text, ASCII or Unicode
- Binary file – contains data that has not been converted to text Text file Binary file
7-21
3.1 Introduction to File Input and Output File Access Methods Two ways to access data stored in files:
- Sequential Access – access data from the beginning of the file to the end of the file
- Direct (random) Access- directly access any piece of data in the file without reading the data that comes before it
7-22
3.1 Introduction to File Input and Output Opening a File The open function:
- General format: file_variable = open(filename, mode)
- file_variable is the name of the variable that will reference the file object
- filename is a string specifying the name of the file
- mode is a string specifying the mode (reading, writing, etc.) customer_file = open(‘customers.txt’, ‘r’) sales_file = open(‘sales.txt’, ‘w’)
7-23
3.1 Introduction to File Input and Output Writing Data to a File
- Method
- function that belongs to an object
- perform operation using that object file_variable.write(string)
- file_variable – variable that references a file object
- write – file object used to write data to a file
- string – string that will be written to the file
7-24
3.1 Introduction to File Input and Output Reading Data from a File … read method Program 7-2 (file_read.py)
7-25
3.2 Using Loops to Process Files Concept: Files usually hold large amounts of data, and programs typically use a loop to process the data in a file.
7-26
3.2 Using Loops to Process Files Reading a File with a Loop and Detecting the End of the File
- Read the contents of a file without knowing the number of items that are stored in the file
- readline method returns an empty string (‘ ‘) when it attempts to read beyond the end of file
- Priming read is required to test loop condition, if using a while loop
7-27
3.2 Using Loops to Process Files Reading a File with a Loop and Detecting the End of the File
- end of a file
- 7-28
- 3.2 Using Loops to Process Files
- Using Python’s for Loop to Read Lines
- for loop automatically reads a line of text from the
end of a file
7-28
3.2 Using Loops to Process Files Using Python’s for Loop to Read Lines
- for loop automatically reads a line of text from the input file
- No special condition or testing is needed
- No priming read is needed
- Automatically stops when the end of file is reached for variable in file_object: statement statement etc.
7-29
3.2 Using Loops to Process Files Using Python’s for Loop to Read Lines Program 7-10 (read_sales2.py)
7-30
3.3 Processing Records Concept: The data that is stored in a file is frequently organized in records. A record is a complete set of data about an item, and a field is an individual piece of data within a record.
7-31
3.3 Processing Records
- A file’s data is organized into records and fields
- Record – a complete set of data that describes one item
- Field – a single piece of data within a record Figure 7-19 Records in a file
7-32
3.3 Processing Records File manipulations
- Create an employee records file
- Read an employee records file
7-33
3.3 Processing Records Creating an employee records file … employee.txt
- Get the total number of employees
- Open the file for writing
- For each employee a. Get the data for an employee b. Pad each field with newline character c. Write the employee record to the file
- Close the file
7-34
3.3 Processing Records Creating an employee records file … employee.txt Program 7-13 (save_emp_records.py)
7-35
3.3 Processing Records Reading an employee records file … employee.txt
- Open the file for reading
- Read the first line from file
- While NOT end-of-file a. Read employee record b. Strip the newlines from the each field c. Display employee record
- Close the file
7-36
3.3 Processing Records Reading an employee records file … employee.txt Program 7-14 (read_emp_records.py)
7-37
4 Exceptions Concept: An exception is an error that occurs while a program is running, causing the program to abruptly halt. You can use the try/exception statement to gracefully handle exceptions.
7-38
4 Exceptions
- Run time error
- Causes program to abruptly halt
- Error message is displayed … traceback – information regarding the cause of the exception
- For example: ZeroDivisionError – division by zero IOError – file specified does not exist
7-39
4 Exceptions
- ZeroDivisionError
- division by zero Program 7-20 (division.py)
7-40
4 Exceptions
- IOError
- file specified does not exist Program 7-22 (display_file.py)
7-41
4 Exceptions
- Exception handler prevents the program from abruptly crashing
- Use the try/except statement try: statement statement etc. except ExceptionName: statement statement etc. try block except clause handler
7-42
- Exceptions When try/except statement executes, the statements in the try block begin to execute:
- If a statement in the try block raises an exception that is specified by the ExceptionName in an except clause, then the handler that immediately follows the except clause executes. Then, the program resumes execution with the statement immediately following the try/except statement.
- If a statement in the try block raises an exception that is not specified by the ExecptionName in an except clause, then the program will halt with a traceback error message.
- If the statements in the try block execute without raising an exception, then any except clauses and handlers in the statement are skipped and the program resumes execution with the statements immediately following the try/except statement.
7-43
4 Exceptions Sequence of events in the try/except statement
7-44
4 Exceptions Program (sales_report.py)
Review
- Defining and Calling a Function(Recap)
- Value-Returning Functions and Modules
- Standard Library Functions
- Write Value-Returning Functions
- File Handling
- File Input and Output
- Using Loops to Process Files
- Processing Files -> Records/Objects
- Exceptions 11th January 2026 Tram Tran
References
Gaddis,Tony Starting out with Python. PearsonEducation Limited.Sixth Edition, 2024.