Review Simple Functions Exception Handling

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Objectives:

  • Review of how to define simple functions
  • Exception handling

Files Modified: pcost.py


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("`Catching Exceptions`") python/FileHandlingGroup -.-> python/file_opening_closing("`Opening and Closing Files`") python/BasicConceptsGroup -.-> python/python_shell("`Python Shell`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-132393{{"`Review Simple Functions Exception Handling`"}} python/with_statement -.-> lab-132393{{"`Review Simple Functions Exception Handling`"}} python/variables_data_types -.-> lab-132393{{"`Review Simple Functions Exception Handling`"}} python/numeric_types -.-> lab-132393{{"`Review Simple Functions Exception Handling`"}} python/type_conversion -.-> lab-132393{{"`Review Simple Functions Exception Handling`"}} python/for_loops -.-> lab-132393{{"`Review Simple Functions Exception Handling`"}} python/lists -.-> lab-132393{{"`Review Simple Functions Exception Handling`"}} python/tuples -.-> lab-132393{{"`Review Simple Functions Exception Handling`"}} python/function_definition -.-> lab-132393{{"`Review Simple Functions Exception Handling`"}} python/catching_exceptions -.-> lab-132393{{"`Review Simple Functions Exception Handling`"}} python/file_opening_closing -.-> lab-132393{{"`Review Simple Functions Exception Handling`"}} python/python_shell -.-> lab-132393{{"`Review Simple Functions Exception Handling`"}} python/build_in_functions -.-> lab-132393{{"`Review Simple Functions Exception Handling`"}} end

Defining a function

Take the program pcost.py that you wrote in the last lab and convert it into a function portfolio_cost(filename) that takes a filename as input, reads the portfolio data in that file, and returns the total cost of the portfolio as a floating point number. Once you written the function, have your program call the function by simply adding this statement at the end:

print(portfolio_cost('/home/labex/project/portfolio.dat'))

Run your program and make sure it produces the same output as before.

Adding Error Handling

When writing programs that process data, it is common to encounter errors related to bad data (malformed, missing fields, etc.). Modify your pcost.py program to read the data file portfolio3.dat and run it (hint: it should crash).

Modify your function slightly so that it is able to recover from lines with bad data. For example, the conversion functions int() and float() raise a ValueError exception if they can't convert the input. Use try and except to catch and print a warning message about lines that can't be parsed. For example:

Couldn't parse: 'C - 53.08\n'
Reason: invalid literal for int() with base 10: '-'
Couldn't parse: 'DIS - 34.20\n'
Reason: invalid literal for int() with base 10: '-'
...

Try running your program on the portfolio3.dat file again. It should run successfully despite printed warning messages.

Interactive Experimentation

Run your pcost.py program and call the portfolio_cost() function directly from the interactive interpreter.

>>> portfolio_cost('/home/labex/project/portfolio.dat')
44671.15
>>> portfolio_cost('/home/labex/project/portfolio2.dat')
19908.75
>>>

Note: To do this, you might have to run python using the -i option. For example:

python3 -i pcost.py

We are going to be writing a lot of programs where you define functions and experiment interactively. Make sure you know how to do this.

Summary

Congratulations! You have completed the Exception Handling lab. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like