Python Handout Level5 Nit&Sod 062930
Python Handout Level5 Nit&Sod 062930
fundamentals& BDCPC301
RQF Level : 5
Credits: 10
Sector: ICT and MULTIMEDIA
Trade: NETWORKING AND INTERNET
TECHNOLOGY
Module Type: GENERAL
Code:
python --version
Code:
python3 --version
The output should display the installed version, e.g., Python 3.x.x.
Code:
python
Code:
python3
Code:
Python 3.x.x (default, Mar 1 2024, 10:24:25)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
You can now type basic Python commands in the interactive prompt.
Code:
exit()
Code:
pip --version
The output should display the version of pip and the Python directory
it's associated with, e.g., pip 23.0.1 from /path/to/python.
To further verify that pip works, try installing a small package like
requests:
Code:
pip install requests
After the installation, you can check if the package was installed
correctly:
Code:
python -m pip show requests
This ensures that Python, the interpreter, and the package manager are
properly installed and functioning.
Data Types
• Definition: Data types represent the type of data that can be stored
and manipulated within a program.
• Examples:
o Integers: Whole numbers (e.g., 5, -10, 42)
o Float: Decimal numbers (e.g., 3.14, -0.5)
o Strings: Textual data (e.g., "Hello, world!", "Python")
o Booleans: True/False values (True, False)
o Lists: Ordered collections of items (e.g., [1, 2, 3], ['a', 'b', 'c'])
o Dictionaries: Key-value pairs (e.g., {'name': 'John', 'age': 30})
2. Variables
Code
x = 10 # x is a variable storing the integer value 10
name = "Alice" # name is a variable storing the string "Alice"
3. Comments
• Definition: Comments are lines of text that are ignored by the Python
interpreter. They are used to explain code or leave notes for
developers.
• Types:
o Single-line comment: Starts with #.
Code :
# This is a single-line comment
Code :
'''
This is a multi-line comment.
It spans across several lines.
''''''
4. Operators
Code:
result = 10 + 5 # Addition
o Comparison Operators: Compare values (==, !=, >, <, >=, <=).
Code:
is_equal = 10 == 5 # False
Code:
condition = True and False # False
Code:
x = 10
x += 5 # x becomes 15
1. Conditional Statements
Code:
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
• Explanation:
o if: Checks if the condition is True.
o elif: Allows for multiple conditions to be checked.
o else: Executes if none of the above conditions are met.
2. Looping Statements
Code :
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Code:
i=1
while i < 5:
print(i)
i += 1 # Increment i
Code :
for i in range(1, 10):
if i == 5:
break # Loop stops when i is 5
print(i)
o Explanation: This loop prints numbers from 1 to 4, and stops
when i equals 5.
• Continue: Skips the current iteration and continues with the next
one.
Code:
for i in range(1, 6):
if i == 3:
continue # Skip the number 3
print(i)
Code:
for i in range(1, 6):
if i == 3:
pass # Placeholder, does nothing
print(i)
Example:
Code:
def greet(name):
return f"Hello, {name}!"
2. Types of Functions
a) Built-in Functions
• Definition: These are functions that are already provided by Python,
and you can use them directly without defining them.
• Examples:
o print(): Outputs the given argument.
o len(): Returns the length of a sequence.
o type(): Returns the type of a variable.
o max(), min(): Return the maximum and minimum values from a
sequence.
Code:
numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # Output: 5
print(max(numbers)) # Output: 5
print(type(numbers)) # Output: <class 'list'>
b) User-Defined Functions
Code:
def function_name(parameters):
# Function body
return result
• Example:
Code:
def add_numbers(a, b):
return a + b
result = add_numbers(3, 4)
print(result) # Output: 7
Create a Function
Code:
def greet(name):
print(f"Hello, {name}!")
Explanation: This greet function takes one argument (name) and prints a
greeting.
2. Arguments
Code:
• You can give parameters default values. If the caller doesn’t provide a
value for that parameter, the default will be used.
• Example:
Code:
def greet(name="Guest"):
print(f"Hello, {name}!")
Code:
def sum_list(numbers):
return sum(numbers)
my_list = [1, 2, 3, 4, 5]
result = sum_list(my_list)
print(result) # Output: 15
5. Calling a Function
Code:
def multiply(a, b):
return a * b
Complete Example
Code:
def process_list(numbers, multiplier=2):
"""
Multiplies each element of the list by the given multiplier (default is 2).
"""
return [number * multiplier for number in numbers]
my_list = [1, 2, 3, 4]
print(process_list(my_list)) # Output: [2, 4, 6, 8]
print(process_list(my_list, 3)) # Output: [3, 6, 9, 12]
• Explanation:
o process_list takes a list numbers and multiplies each element by
multiplier.
o If no multiplier is provided, it defaults to 2.
Apply special purpose functions
1. Lambda Functions
Code:
lambda arguments: expression
• Example:
Code:
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
Explanation: Here, add is a lambda function that takes two arguments (x, y)
and returns their sum.
2. Python Generators
Code:
def count_up_to(max):
count = 1
while count <= max:
yield count # Return the value, but keep the function state
count += 1
3. Python Closures
Code:
def outer_function(msg):
def inner_function():
print(msg) # `msg` is remembered by `inner_function`
return inner_function
Explanation: The inner function remembers the value of msg from the outer
function, even after outer_function has finished.
4. Python Decorators
Code:
def my_decorator(func):
def wrapper():
print("Something before the function is called.")
func()
print("Something after the function is called.")
return wrapper
@my_decorator # Using the decorator
def say_hello():
print("Hello!")
say_hello()
Output:
Code:
5. Recursive Function
Code:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
Explanation: The factorial function calls itself with a smaller value until it
reaches the base case (n == 1), where it returns 1.
6. Higher-Order Functions
Code:
def apply_function(func, value):
return func(value)
def square(x):
return x * x
Complete Example
Code:
# Higher-order function using a lambda and recursion
def apply_operation(operation, n):
if n == 0:
return 0
else:
return operation(n) + apply_operation(operation, n - 1)
1. Lists
Code:
Key Features:
• Ordered
• Mutable
• Allows duplicate values
2. Tuples
Code:
coordinates = (10, 20)
Key Features:
• Ordered
• Immutable
• Allows duplicate values
3. Dictionaries
Code:
Key Features:
4. Sets
Code:
Key Features:
• Unordered
• Mutable
• Unique elements only
5. Frozen Set
Code:
Key Features:
• Unordered
• Immutable
• Unique elements only
6. ChainMaps
Code:
Key Features:
7. Deques
Code:
dq = deque([1, 2, 3])
Key Features:
• Mutable
• Fast append and pop operations from both ends
• Used in situations where queue or stack operations are needed
These collections allow for a wide range of data storage and manipulation
techniques, depending on your needs (e.g., efficiency in adding/removing,
uniqueness, immutability).
1. Counter
Code:
fruit_counter = Counter(fruits)
print(fruit_counter["apple"]) # Output: 3
2. OrderedDict
Code:
ordered_dict = OrderedDict()
ordered_dict["apple"] = 1
ordered_dict["banana"] = 2
ordered_dict["cherry"] = 3
Key Features:
3. defaultdict
• Definition: A defaultdict is a dictionary subclass that provides a
default value for a key if the key hasn’t been set yet. This eliminates
the need to check if a key exists before adding a value.
• Example:
Code:
word_count = defaultdict(int)
words = sentence.split()
word_count[word] += 1
Key Features:
Code:
neighbors = defaultdict(list)
neighbors["A"].append("B")
neighbors["A"].append("C")
neighbors["B"].append("A")
print(neighbors)
These tools from the collections module make it easier to work with complex
data structures and can often result in more concise and readable code.
• Lists:
Code:
fruits = ["apple", "banana"]
fruits.append("orange") # Adding an element
print(fruits) # Output: ['apple', 'banana', 'orange']
• Sets:
Code:
fruits_set = {"apple", "banana"}
fruits_set.add("orange") # Adding an element
print(fruits_set) # Output: {'apple', 'orange', 'banana'}
fruits_set.discard("banana") # Removing an element (no error if not found)
print(fruits_set) # Output: {'apple', 'orange'}
• Dictionaries:
Code:
person = {"name": "Alice", "age": 30}
person["city"] = "New York" # Adding an element
print(person) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
• Deques:
Code:
from collections import deque
dq = deque([1, 2, 3])
dq.append(4) # Add to the right
dq.appendleft(0) # Add to the left
print(dq) # Output: deque([0, 1, 2, 3, 4])
Code:
• Dictionaries:
Code:
person = {"name": "Alice", "age": 30}
print(person["name"]) # Accessing a value, Output: Alice
Code:
fruits_set = {"apple", "banana", "orange"}
for fruit in fruits_set:
print(fruit) # Iterating over the set
Code:
numbers = [1, 2, 3, 4, 5]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # Output: [2, 4]
Code:
fruits = ["banana", "apple", "orange"]
fruits_sorted = sorted(fruits)
print(fruits_sorted) # Output: ['apple', 'banana', 'orange']
numbers = {3, 1, 2}
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3]
Code:
person = {"name": "Alice", "age": 30, "city": "New York"}
sorted_by_key = sorted(person) # Sorts by keys
print(sorted_by_key) # Output: ['age', 'city', 'name']
Code:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # Output: {3}
print(set1.difference(set2)) # Output: {1, 2}
Code:
Stack (Last In First Out - LIFO) and Queue (First In First Out - FIFO)
operations are typically done using lists, deques, or dedicated modules like
queue.
Code:
stack = [1, 2, 3]
stack.append(4) # Push to the stack
print(stack) # Output: [1, 2, 3, 4]
stack.pop() # Pop from the stack
print(stack) # Output: [1, 2, 3]
Code:
from collections import deque
queue = deque([1, 2, 3])
queue.append(4) # Enqueue (add to the end)
print(queue) # Output: deque([1, 2, 3, 4])
Code:
import heapq
pq = []
heapq.heappush(pq, (1, "apple")) # (priority, item)
heapq.heappush(pq, (3, "banana"))
heapq.heappush(pq, (2, "orange"))
print(heapq.heappop(pq)) # Output: (1, 'apple') -> smallest priority element
Summary of Operations:
Python provides several libraries and tools to work with files and directories.
Key libraries for file handling include os, pathlib, shutil, and pandas.
File handling in Python allows you to open, read, write, and close files. The
basic file operations can be done using Python’s built-in open() function.
File Operations
• Opening a file:
Code:
file = open('example.txt', 'r') # 'r' for reading, 'w' for writing, 'a' for appending
• Reading a file:
Code:
print(content)
• Writing to a file:
Code:
file.close()
Code:
content = file.read()
print(content)
2. os Library
Key Functions:
Code:
import os
Code:
Code:
print(files)
Code:
3. pathlib Library
• Creating a path:
Code:
path = Path('example.txt')
Code:
# Writing to a file
path.write_text("Hello, World!")
content = path.read_text()
print(content)
Code:
directory = Path('new_directory')
• Traversing directories:
Code:
print(file)
4. shutil Library
shutil is used for high-level file and directory operations such as copying,
moving, and deleting files or directories.
Key Functions:
• Copying files:
Code:
import shutil
• Moving files:
Code:
• Deleting directories:
Code:
5. pandas Library
Key Functions:
Code:
import pandas as pd
print(df)
Code:
Code:
pandas can handle very large datasets efficiently, enabling chunked reads
for large files that don’t fit in memory:
code:
chunk_size = 1000
These libraries offer a comprehensive suite of tools for working with files and
directories in Python, each suited to specific tasks, whether you’re dealing
with basic file I/O or complex data manipulation.
Open a File
You can open a file using Python’s built-in open() function. The most
common file modes include:
• r: Read (default mode)
• w: Write (overwrite if the file exists)
• a: Append (add to the end of the file)
• rb, wb: Read/Write in binary mode
code
content = file.read()
print(content)
file.close()
Using the with statement ensures that the file is automatically closed after
operations, even if an exception occurs.
code
content = file.read()
To check the permissions of a file, you can use the os or pathlib library.
Using os module:
The os module provides a function called os.access() to check for file
permissions.
• os.R_OK: Readable
• os.W_OK: Writable
• os.X_OK: Executable
Example:
code
import os
file_path = 'example.txt'
if os.access(file_path, os.R_OK):
print(f"{file_path} is readable.")
else:
if os.access(file_path, os.W_OK):
print(f"{file_path} is writable.")
else:
code
file_path = Path('example.txt')
else:
code
import os
import stat
file_stat = os.stat('example.txt')
permissions = oct(file_stat.st_mode)[-3:]
Example Output:
• 755 means the owner has read, write, and execute permissions, and
the group and others have read and execute permissions.
Summary of Steps:
python
Copy code
file.close()
Alternatively, you can use the with statement to ensure that the file is
properly closed after writing:
python
Copy code
To append to an existing file without overwriting its content, open the file in
append mode ('a'):
python
Copy code
with open('existing_file.txt', 'a') as file:
2. Delete a File
Remove a File:
python
Copy code
import os
file_path = 'new_file.txt'
if os.path.exists(file_path):
else:
You can delete directories using the os or shutil module. You need to be
careful when deleting directories to ensure you don’t accidentally delete
important data.
python
Copy code
directory = 'empty_folder'
if os.path.exists(directory):
else:
To remove a directory and all its contents (subdirectories and files), use
shutil.rmtree().
python
Copy code
import shutil
directory = 'non_empty_folder'
if os.path.exists(directory):
else:
Readability is crucial in Python. Follow the PEP 8 style guide for better code
quality.
Key Practices:
python
Copy code
def calculate_total_price(items):
total = 0
total += item['price']
return total
Code:
Code:
def fetch_user_data(user_id):
"""
"""
Python provides many built-in functions and standard libraries that are
optimized and tested, so you should prefer them over writing your own
implementations.
Key Practices:
Code:
numbers = [3, 1, 4, 1, 5, 9]
max_number = max(numbers)
• List comprehensions:
o Use list comprehensions for readability and performance over
for loops:
Code:
squares = []
for x in range(10):
squares.append(x**2)
• Dictionary comprehensions:
o Example of dictionary comprehension:
Code:
Code:
print(f"{index}. {fruit}")
Code:
Key Practices:
• Use generators for large datasets:
o Generators are memory-efficient as they yield items one at a
time instead of storing the entire sequence in memory.
Code:
def number_generator(n):
for i in range(n):
yield i
gen = number_generator(1000)
print(next(gen)) # Output: 0
print(next(gen)) # Output: 1
Code:
Code:
items = [1, 2, 3, 4, 5]
item_set = set(items)
print("Found!")
4. Error Handling and Testing
Good error handling improves the reliability of your code, while testing
ensures its correctness.
Key Practices:
Code:
try:
content = file.read()
except FileNotFoundError:
except Exception as e:
Code:
try:
content = file.read()
except FileNotFoundError:
finally:
• Testing:
o Write unit tests using the built-in unittest module or pytest.
Testing ensures that changes in your code don’t introduce bugs.
Code:
import unittest
return a + b
class TestAddFunction(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-1, 1), 0)
if __name__ == '__main__':
unittest.main()
Code:
return a / b
Defining a Class:
python
Copy code
class Car:
self.model = model
self.year = year
def start_engine(self):
2. Inheritance
Inheritance allows one class (child class) to inherit attributes and methods
from another class (parent class). This helps reuse code and create
hierarchical relationships.
Example:
python
Copy code
class Animal:
self.name = name
def make_sound(self):
class Dog(Animal):
print(f"{self.name} barks.")
# Creating instances of the classes
dog = Dog("Buddy")
Here, the Dog class inherits the properties of the Animal class and overrides
the make_sound() method to provide its own functionality.
3. Polymorphism
Example:
python
Copy code
class Bird:
def make_sound(self):
print("Chirp")
class Cat:
def make_sound(self):
print("Meow")
def animal_sound(animal):
animal.make_sound()
bird = Bird()
cat = Cat()
In this example, both Bird and Cat have the make_sound() method, but they
behave differently. The animal_sound() function can call make_sound() on
any object with that method, regardless of the class.
4. Encapsulation
Example:
python
Copy code
class BankAccount:
self.__balance += amount
def withdraw(self, amount):
self.__balance -= amount
else:
print("Insufficient balance")
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
account.withdraw(300)
Here, the __balance attribute is encapsulated within the class. It can only
be accessed or modified through methods, ensuring controlled access to the
data.
• pendulum is similar to arrow but also handles time zones and periods
efficiently. It is designed to be more intuitive and consistent.
• This package provides time zone support, which can be used with
other libraries like datetime, arrow, and pendulum.
Using datetime:
The built-in datetime module can be used with pytz or zoneinfo to manage
time zones.
python
Copy code
import pytz
utc_time = datetime.now(pytz.utc)
local_tz = pytz.timezone('Asia/Kolkata')
local_time = utc_time.astimezone(local_tz)
Using arrow:
python
Copy code
import arrow
local_time = arrow.now('America/New_York')
tokyo_time = local_time.to('Asia/Tokyo')
print("Tokyo Time:", tokyo_time)
Using pendulum:
Pendulum automatically handles time zones and provides a clear API for
conversions.
python
Copy code
import pendulum
ny_time = pendulum.now('America/New_York')
tokyo_time = ny_time.in_timezone('Asia/Tokyo')
Using datetime:
You can format and parse dates using strftime() and strptime().
python
Copy code
now = datetime.now()
formatted_time = now.strftime('%Y-%m-%d %H:%M:%S')
Using arrow:
python
Copy code
import arrow
# Formatting a date
Using pendulum:
python
Copy code
import pendulum
# Parsing a date string
dt = pendulum.parse('2024-09-08 14:30:00')
# Formatting a date
Using datetime:
The timedelta class can be used to perform relative date and time
operations.
python
Copy code
now = datetime.now()
Using dateutil.relativedelta:
python
Copy code
now = datetime.now()
Using arrow:
python
Copy code
import arrow
# Add 5 days
future_date = arrow.now().shift(days=5)
past_time = arrow.now().shift(hours=-3)
Using pendulum:
Pendulum has built-in support for relative time deltas using the add() or
subtract() methods.
python
Copy code
import pendulum
now = pendulum.now()
new_time = now.add(weeks=2).subtract(days=3)
• Set Time Zones: Manage time zones easily using pytz, arrow, or
pendulum.
• Formatting and Parsing: Use strftime and strptime for string
formatting and parsing in datetime, and use easier functions in arrow
and pendulum.
• Performing Relative Timedeltas: Add or subtract days, months, or
years using timedelta, relativedelta, or similar features in arrow and
pendulum.
Examples:
1. Matplotlib:
2. NumPy:
3. Pandas:
4. Use of Libraries
Importing Libraries
To use any library in Python, whether from the standard library or third-
party, you need to import it using the import statement.
python
Copy code
import numpy as np
import pandas as pd
Accessing Functionality
Once a library is imported, you can access its functions, classes, and
methods using dot notation.
python
Copy code
import numpy as np
mean_value = np.mean(array)
python
Copy code
import pandas as pd
df = pd.DataFrame(data)
print(df.head())
python
Copy code
x = [0, 1, 2, 3]
y = [0, 1, 4, 9]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
python
Copy code
import numpy as np
import pandas as pd
df = pd.DataFrame(array, columns=['Numbers'])
print(df)
Code:
Code:
Code:
Once the appropriate library is selected, you can start developing the
automation script. Here's an example using Fabric to automate service
restarts, database migrations, and file updates:
python
Copy code
@task
def migrate_db(c):
@task
def update_configs(c):
c.put('/local/path/config.ini', '/remote/path/config.ini')
# Restart services
@task
def restart_services(c):
print("Services restarted.")
@task
def post_deploy(c):
print("Starting post-deployment tasks...")
migrate_db(c)
update_configs(c)
restart_services(c)
In this example:
python
Copy code
import logging
# Setup logging
logging.basicConfig(filename='post_deploy.log', level=logging.INFO)
def migrate_db(c):
Here, all actions and outcomes are logged for future reference and
debugging.
There are several ways to trigger your automation script after the
deployment:
Example
Copy code
python3 post_deploy.py
yaml
Copy code
deploy:
script:
- ./deploy_script.sh
after_script:
3. Scheduled Execution:
• You can also schedule the script using cron jobs to run at specific
intervals.
bash
Copy code
0 3 * * * /usr/bin/python3 /path/to/post_deploy.py
4. Security Measures:
Thorough Testing:
python
Copy code
import logging
def restart_services(c):
try:
except Exception as e:
Summary:
1. Identify Tasks: Automate tasks like database migrations,
configuration updates, and service restarts.
2. Prioritize Tasks: Focus on repetitive, error-prone, and time-
consuming tasks.
3. Select a Library: Choose from Fabric, Ansible, Boto3, etc., based on
your environment.
4. Develop the Script: Use the library’s functionality to automate the
tasks logically and securely.
5. Integrate with Deployment: Trigger the script via CI/CD pipelines,
direct execution, or scheduling.
6. Testing and Monitoring: Ensure thorough testing and continuous
monitoring to improve reliability.