Unit 11Functions and File Handling in Python
Follows IGNOU MCS-201, Unit 11
Functions let you package a task once and reuse it everywhere, which keeps programs short, readable and easy to test. Files let a program keep data after it ends. This unit covers both: how Python functions are defined and called, how variable scope works, the different ways to pass arguments and return results, why functions are objects, lambda functions with map() and filter(), and finally how to create, read, write, copy and delete files. If you studied Units 5 and 8, you will see the same ideas as in C, usually with much less code.
In this unit you will learn to
- Define and call functions, and distinguish parameters from arguments.
- Explain local, global and enclosing scope, and use
globalandnonlocal. - Pass positional, default, keyword and arbitrary arguments (
*args,**kwargs). - Return one or several values from a function, and leave a function early.
- Treat functions as objects: assign them, store them, pass them and nest them.
- Write lambda functions and use them with
map(),filter()andsorted(). - Open, read, write and append text files safely with
with, and copy, inspect and delete files withshutilandos.
Sections in this unit
- 11.1Defining and Calling FunctionsWhy functions exist, the three kinds of Python functions, how to define one with def, call it, and tell parameters from arguments.8 min
- 11.2Variable Scope: Local, Global and NonlocalWhere a variable can be used: local and global scope, the LEGB lookup rule, and how the global and nonlocal keywords let a function change outer variables.8 min
- 11.3Function ArgumentsThe ways to pass values to Python functions: positional, default, keyword and arbitrary arguments with *args and **kwargs, and the mutable default trap.10 min
- 11.4Returning ValuesHow return sends results back, returning several values as a tuple, multiple return statements, leaving a function early, and the default None.7 min
- 11.5Functions as ObjectsPython functions are first-class objects: assign them to names, store them in lists, pass them to other functions, nest them, and return them as closures.9 min
- 11.6Lambda Functions, map() and filter()Writing small anonymous functions with lambda, and using them with map(), filter() and sorted() to transform and select data from lists.10 min
- 11.7Opening, Reading and Writing FilesText and binary files, open() and its modes, reading with read, readline and readlines, writing and appending, tell and seek, and the with statement.13 min
- 11.8Copying, Deleting and Inspecting FilesManaging files and folders with the os and shutil modules: checking existence and size, copying, renaming, listing and deleting files and folders.9 min