Week 4 subject 1: File Operation (contd.)
- More ways to process File contents in Lists:
- List(File) is a list of lines from File,
- .readlines(hint) returns a list of lines.
- One way to avoid explicitly closing files is using
File will be automatically closed at the end of the with block.
- Opening files for output using the 'w' or 'a' modes in the open() function. Note the different behaviour vs. 'r' when the file doesn't exist.
- Output to files with the write() function.
- Files by default is a sequential media. There's a historical reason for this. However there are ways to move in a file in both directions:
- .seek(offset, from) moves forward or backward in file,
- .tell() tells the current position in file.
Week 4 subject 2: Functions
- A Function is a block of code with:
- A name,
- Zero or more parameters,
- Zero or more return values.
- Functions are useful for:
- Eliminating repetition, and
- Simplifying code, making it easier to read.
- The same number of parameters need to be provided when calling a Function, as the number of parameters in the definition of the function.
- You can specify default values of parameters in the definition. When there are default values, less parameters can be provided when calling.
- Use the return statement to return values to the caller. You can return multiple values:
- In the form of a tuple, i.e., multiple values separated by commas, or
- In a list.
Week 4 subject 3: Scope of variables
- Variables have scopes, i.e., parts of the program where they can be referenced.
- There are 2 types of variables based on their scopes:
- Global variables: those defined outside any function, and
- Local variables: those defined inside a function
- Global variables are valid inside functions, but local variables aren't valid outside functions.
- All variables must be first defined before referenced, within their respective scopes.
- Functions are like global variables, they must be defined before being called.
- Expand your knowledge by doing research of the concept Namespace.
No comments:
Post a Comment