DataCareerHub / Python for Data Science
Functions, Modules, and File Handling
Fictional practice · Reference code executed locally · The supplied local reference was executed against the included fixture. This does not verify a production service or the learner’s own environment.
Design a function contract
Design a function contract
A function contract states inputs, outputs and errors. line_value accepts positive integer quantity and nonnegative integer price in cents; it returns integer cents. Validate the input domain before arithmetic. Explicitly reject booleans even though isinstance(True,int) is true. A function should perform one meaningful operation without reading a global website configuration or changing source files. Small functions are easier to test when their assumptions and side effects are visible. Names and docstrings support the contract but do not replace executable tests.
Follow a concrete example
For quantity2 and price1000cents, the function returns2000cents. For price0 and positive quantity it returns a legitimate zero amount. For quantityTrue it must reject the semantic mismatch, despite Python’s integer inheritance. Tests should name the contract reason so a future developer does not remove the boolean guard as apparently redundant.
Further reading: Python 3.12 tutorial, pandas 2.2 merge, NumPy 2.2 reference. The case and exercises are authored for DataCareerHub.
Your task
Write a line_value function and predict outputs for (2,1000), (1,0), (0,1000), (-1,500) and (True,100).
Use learner_worksheet.txt and the provided source/code files. Save your own artifact and compare the separate solution after attempting the task.
Worked solution
The first two return 2000 and 0. Zero or negative quantity and boolean quantity fail. A zero price is allowed by this teaching contract; a missing or noninteger price is not.
Read files with explicit context and encoding
Read files with explicit context and encoding
A with block closes a file even when an exception occurs. CSV parsing handles quoting and record boundaries that a simple split on commas misses. Use pathlib for paths and explicit UTF-8 encoding. Keep paths supplied by the local learner separate from web request parameters. A reusable module defines functions; an if __name__=="__main__" guard controls command-line execution when the file is run directly. Importing a module should not unexpectedly connect to a service or overwrite a report. The reference calculates a source hash without altering source bytes.
Follow a concrete example
A with block governs the file resource, while DictReader governs CSV quoting and fields. Neither decides the business validity of the values. Compute the source hash from bytes before any working transformation and keep it with the command/environment. An imported helper module should define functions without executing the command-line runner.
Inspect the reference implementation
Language: Python 3.12. The complete downloadable file includes the named helpers and the fresh-output command-line runner. Trace the source, transformation and result against this lesson’s contract before running it locally.
def py_functions(source,out):
def line_value(quantity,price):
if isinstance(quantity,bool) or not isinstance(quantity,int) or quantity<=0:raise ValueError('Quantity must be a positive integer')
if isinstance(price,bool) or not isinstance(price,int) or price<0:raise ValueError('Price must be nonnegative integer cents')
return quantity*price
checks=[]
for q,p in [(2,1000),(1,0),(0,1000),(-1,500),(True,100)]:
try:checks.append({'quantity':q,'price':p,'result':line_value(q,p)})
except ValueError as e:checks.append({'quantity':q,'price':p,'rejected':str(e)})
return {'checks':checks,'source_sha256':hashlib.sha256((Path(source)/'order_lines.csv').read_bytes()).hexdigest()}
Further reading: Python 3.12 tutorial, pandas 2.2 merge, NumPy 2.2 reference. The case and exercises are authored for DataCareerHub.
Your task
Read order_lines.csv through DictReader and compute its SHA-256. Import your module from a second script and confirm that its command-line path does not run automatically.
Use learner_worksheet.txt and the provided source/code files. Save your own artifact and compare the separate solution after attempting the task.
Worked solution
DictReader returns dictionaries with text values, so parsing remains explicit. The hash identifies the exact bytes used. Importing should define functions without creating output; the main guard owns the local CLI entry.
Handle expected errors without hiding defects
Handle expected errors without hiding defects
Catch an exception only when you can give it a meaningful disposition. A known invalid row may be returned for review; a missing required file should stop a run. Broad except: pass turns broken work into apparently successful output. Preserve the error type and enough context to diagnose it, while excluding credentials or private records from public logs. Test both successful and failing inputs. The local scaffold deliberately raises NotImplementedError until completed, which is honest unfinished code rather than a fake successful result.
Follow a concrete example
Test an invalid row and a missing file separately. The invalid numeric field is a known data issue whose disposition can be defined; a missing required file means the analysis cannot start. Do not use the same “return0” fallback for both. Preserve an exception that identifies the failed prerequisite without printing secrets or private records.
Further reading: Python 3.12 tutorial, pandas 2.2 merge, NumPy 2.2 reference. The case and exercises are authored for DataCareerHub.
Your task
Run the supplied validation cases and add a missing-file test. Classify each as an invalid input, fatal source problem or programmer defect.
Use learner_worksheet.txt and the provided source/code files. Save your own artifact and compare the separate solution after attempting the task.
Worked solution
Invalid quantity raises ValueError; missing files raise FileNotFoundError. Neither should silently become zero value. A test should verify the intended exception as well as valid results. An unexpected coding error remains visible for correction.
Practice evidence