1. Functions
- Types of Functions:
- Built-in Functions: Pre-defined functions that come with Python.
- Examples: print(), input(), len(), max(), min(), abs(), round(), type()
- Functions Defined in Modules: Functions that are part of external libraries.
- Examples: math.sqrt(), random.randint(), os.path.exists() (from the math, random, and os modules, respectively)
- User-Defined Functions: Functions created by the programmer.
- Creating User-Defined Functions:
Python
def
function_name(parameters):
"""Docstring: Briefly
explain what the function does"""
# Function body: Perform operations
return value #
Optional: Return a value
- Arguments and Parameters:
- Parameters:
Variables defined within the function's parentheses.
- Arguments:
Values passed to the function when it's called.
- Example:
Python
def
greet(name):
"""This function
greets the person passed in as a parameter."""
print("Hello,", name + "!")
greet("Alice")
# Calling the function with the
argument "Alice"
- Scope of Variables:
- Global Scope:
Variables defined outside any function. Accessible from anywhere in the
program.
- Local Scope:
Variables defined within a function. Only accessible within that
function.
Python
global_var = 10
def
my_function():
local_var = 5 #
Local to the function
print("Inside function:", local_var)
print("Inside function:", global_var)
my_function()
print("Outside
function:",
global_var) #
Accessing global variable
#
print("Outside function:", local_var)
# Error: local_var is not accessible here
2. Exception Handling
- Introduction:
- Exceptions are errors that occur during the execution
of a program.
- They can disrupt the normal flow of the program.
- try-except-finally Blocks:
Python
try:
# Code that might raise an exception
result = 10 / 0 # This will raise a ZeroDivisionError
except
ZeroDivisionError:
print("Error: Division by zero!")
finally:
print("This block always
executes.")
- Notes:
- The try block contains the code that might raise an
exception.
- The except block handles the specific exception type.
- The finally block always executes, regardless of whether an
exception occurred.
3. Files
- Types of Files:
- Text File:
Stores data as plain text (e.g., .txt, .py, .html)
- Binary File:
Stores data in a binary format (e.g., .jpg, .png, .mp3, .exe)
- CSV File:
Stores data in a comma-separated values format (e.g., .csv)
- File Handling:
Python
#
Opening a file in read mode
file = open("my_file.txt", "r")
contents = file.read()
print(contents)
file.close()
#
Opening a file in write mode (creates a new file or overwrites existing)
file = open("new_file.txt", "w")
file.write("This
is a new line.")
file.close()
- File Paths:
- Absolute Path:
The full path to the file, starting from the root directory.
- Relative Path:
The path to the file relative to the current working directory.
Visuals:
- Flowchart of try-except-finally:
flowchart
illustrating the execution flow of tryexceptfinally blocks
- File Structure Diagram:
file
system diagram showing absolute and relative paths
Note: These are basic concepts. You can explore more advanced
topics like reading and writing binary files, working with CSV files using the csv
module, and handling different types of exceptions in detail.
No comments:
Post a Comment