Python Functions Modules FileIO
Python Functions Modules FileIO
• Example:
• ```python
• def greet():
• print('Hello!')
• greet()
• ```
Function Parameters and Types
• • Formal vs Actual Parameters.
• • Types: Built-in, User-defined, Recursive,
Anonymous (Lambda).
• Example:
• ```python
• def add(a, b):
• return a + b
• print(add(3, 5))
Global and Local Variables
• • Local: Defined inside a function.
• • Global: Defined outside any function.
• Example:
• ```python
• x = 10 # Global
• def example():
• y = 5 # Local
• print(x + y)
Importing and Creating Modules
• • Modules help reuse code.
• • Importing modules using `import`.
• Example:
• ```python
• import math
• print(math.sqrt(25))
• ```
File I/O: Introduction
• • Python provides built-in functions for file
handling.
• • Modes: Read ('r'), Write ('w'), Append ('a').
• • Files must be opened before use and closed
after use.
Reading and Writing Files
• • Reading a file:
• ```python
• file = open('data.txt', 'r')
• print(file.read())
• file.close()
• ```
• • Writing to a file:
• ```python
• file = open('data.txt', 'w')
Manipulating Directories
• • Using `os` module for directory handling.
• Example:
• ```python
• import os
• os.mkdir('new_folder')
• os.rename('old.txt', 'new.txt')
• os.remove('unwanted.txt')
• ```
Iterators and Their Applications
• • Iterators allow sequential access to
elements.
• • Used for handling large datasets efficiently.
• Example:
• ```python
• my_list = [1, 2, 3]
• iterator = iter(my_list)
• print(next(iterator))
Conclusion
• • Functions and Modules improve code
organization.
• • File I/O helps in persistent data storage.
• • Iterators make handling large data easier.
• • Practice examples to strengthen
understanding!