Practical Manual for Python Programming
Lab 1: Introduction to Python IDEs and Writing Basic Scripts
• Aim: To familiarize students with Python IDEs and write basic scripts for simple
applications.
• Theory:
o Python IDEs and their usage (e.g., PyCharm, VSCode)
o Variables, data types, and basic operators in Python
o Basic input/output functions
o Writing and executing basic Python programs
• Python Program:
# Temperature Conversion: Celsius to Fahrenheit
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius} Celsius is {fahrenheit} Fahrenheit")
# Area of a Circle
radius = float(input("Enter radius of the circle: "))
area = 3.14 * radius**2
print(f"Area of the circle: {area}")
Practical Manual for Python Programming
Lab 2: Implementing Control Structures for Simple Agricultural Decision-Making Scenarios
• Aim: To implement control structures for agricultural decision-making (e.g., irrigation
scheduling based on soil moisture levels).
• Theory:
o Conditional statements (if-else)
o Logical operators for decision making
o Loops for repetitive tasks
o Application of control structures in real-world agricultural problems
• Python Program:
# Irrigation Scheduling based on soil moisture levels
moisture_level = float(input("Enter soil moisture level (%): "))
if moisture_level < 30:
print("Irrigation Required.")
else:
print("No Irrigation Needed.")
Practical Manual for Python Programming
Lab 3: Manipulating and Analyzing Agricultural Datasets Using Lists, Tuples, and Dictionaries
• Aim: To manipulate and analyze agricultural datasets using Python’s built-in data
structures.
• Theory:
o Lists, tuples, and dictionaries in Python
o Accessing and manipulating data in lists and dictionaries
o Basic data analysis techniques
o Use of data structures in agricultural data processing
• Python Program:
# Example agricultural dataset using a dictionary
crops = {
"Mango": {"production": 200, "area": 50},
"Wheat": {"production": 500, "area": 100},
"Rice": {"production": 400, "area": 150}
# Accessing data
crop = "Mango"
print(f"Production of {crop}: {crops[crop]['production']} tons")
Practical Manual for Python Programming
Lab 4: Writing Python Programs for File Handling
• Aim: To write Python programs that read and process crop data from text files.
• Theory:
o File handling in Python (open, read, write, close)
o Processing data from text files
o Handling different file formats (e.g., CSV, TXT)
o Applications of file handling in agriculture
• Python Program:
# Reading crop data from a text file
with open('crop_data.txt', 'r') as file:
for line in file:
print(line.strip())
# Writing data to a text file
with open('output.txt', 'w') as file:
file.write("Crop Yield: 500 tons\n")
Practical Manual for Python Programming
Lab 5: Creating and Manipulating Pandas DataFrames with Agricultural Datasets
• Aim: To create and manipulate Pandas DataFrames for agricultural datasets.
• Theory:
o Introduction to Pandas library
o Creating and indexing DataFrames
o Data cleaning and manipulation techniques
o Analyzing agricultural data using Pandas
• Python Program:
import pandas as pd
# Creating a DataFrame
data = {'Crop': ['Mango', 'Wheat', 'Rice'],
'Production': [200, 500, 400],
'Area': [50, 100, 150]}
df = pd.DataFrame(data)
# Displaying the DataFrame
print(df)
# Manipulating DataFrame (e.g., filtering data)
high_yield = df[df['Production'] > 300]
print(high_yield)
Practical Manual for Python Programming
Lab 6: Data Visualization Using Matplotlib
• Aim: To visualize crop yield trends over time using Matplotlib.
• Theory:
o Introduction to Matplotlib for plotting
o Line, bar, and scatter plots
o Customizing plots (labels, title, etc.)
o Visualizing agricultural data for better decision making
• Python Program:
import matplotlib.pyplot as plt
# Example crop yield data
years = [2018, 2019, 2020, 2021, 2022]
yields = [200, 250, 300, 350, 400]
# Plotting crop yield over time
plt.plot(years, yields, marker='o')
plt.title('Crop Yield Over Time')
plt.xlabel('Year')
plt.ylabel('Yield (in tons)')
plt.show()
Practical Manual for Python Programming
Lab 7: Object-Oriented Programming
• Aim: To design a class for farm equipment and simulate operations using Object-Oriented
Programming.
• Theory:
o Concepts of Object-Oriented Programming (OOP)
o Classes and objects
o Methods and attributes
o Simulating real-world agricultural scenarios with OOP
• Python Program:
# Farm Equipment Class
class FarmEquipment:
def __init__(self, name, type_of_equipment):
self.name = name
self.type_of_equipment = type_of_equipment
def operate(self):
print(f"Operating {self.name} ({self.type_of_equipment})")
# Creating an object
tractor = FarmEquipment("Tractor", "Plowing")
tractor.operate()
Practical Manual for Python Programming
Lab 8: Automating Data Collection: Writing Scripts to Scrape Weather Data
• Aim: To automate data collection by writing scripts to scrape weather data for a specific
region.
• Theory:
o Web scraping concepts and libraries (e.g., BeautifulSoup)
o Data extraction from websites
o Storing and processing scraped data
o Applications of automated data collection in agriculture
• Python Program:
import requests
from bs4 import BeautifulSoup
# Scraping weather data
url = 'https://weather-website.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
weather = soup.find('div', class_='weather-info').text
print(f"Weather Info: {weather}")
Practical Manual for Python Programming
Lab 9: Working with Excel Files
• Aim: To import and export crop production data from Excel files.
• Theory:
o Using Python libraries (e.g., openpyxl, pandas) to work with Excel files
o Importing data from Excel into Python
o Exporting processed data back into Excel
o Applications in agricultural data management
• Python Program:
import pandas as pd
# Importing data from Excel
df = pd.read_excel('crop_data.xlsx')
# Displaying the DataFrame
print(df)
# Exporting data to Excel
df.to_excel('processed_crop_data.xlsx', index=False)
Practical Manual for Python Programming
Lab 10: Introduction to NumPy: Array Operations for Statistical Analysis of Soil Data
• Aim: To perform statistical analysis of soil data using NumPy arrays.
• Theory:
o Introduction to NumPy library and arrays
o Basic operations on NumPy arrays (e.g., addition, subtraction)
o Statistical operations (mean, median, standard deviation)
o Using NumPy for data analysis in agriculture
• Python Program:
import numpy as np
# Example soil data
soil_data = np.array([18, 20, 19, 17, 21])
# Calculating mean and standard deviation
mean = np.mean(soil_data)
std_dev = np.std(soil_data)
print(f"Mean: {mean}, Standard Deviation: {std_dev}")
Practical Manual for Python Programming
Lab 11: Basic Image Processing with OpenCV
• Aim: To perform basic image processing and analyze leaf images for disease detection.
• Theory:
o Introduction to OpenCV and image processing techniques
o Reading and displaying images
o Basic image transformations (e.g., resizing, grayscale)
o Detecting patterns in agricultural images
• Python Program:
import cv2
# Reading and displaying an image
image = cv2.imread('leaf_image.jpg')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Displaying the image
cv2.imshow('Leaf Image', gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Practical Manual for Python Programming
Lab 12: Simple GUI Application: Developing a Crop Irrigation Scheduling Tool Using Tkinter
• Aim: To develop a graphical user interface (GUI) application for crop irrigation scheduling.
• Theory:
o Introduction to Tkinter for GUI development
o Creating windows, buttons, and labels
o Event-driven programming
o Designing applications for agricultural decision support
• Python Program:
import tkinter as tk
def irrigation_schedule():
moisture_level = int(entry.get())
if moisture_level < 30:
label_result.config(text="Irrigation Required.")
else:
label_result.config(text="No Irrigation Needed.")
root = tk.Tk()
root.title('Irrigation Scheduling')
label = tk.Label(root, text="Enter Soil Moisture Level:")
label.pack()
entry = tk.Entry(root)
entry.pack()
button = tk.Button(root, text="Check Irrigation", command=irrigation_schedule)
button.pack()
label_result = tk.Label(root, text="")
Practical Manual for Python Programming
label_result.pack()
root.mainloop()
Practical Manual for Python Programming
Lab 13: Time Series Analysis of Crop Production Data Using Python
• Aim: To perform time series analysis of crop production data using Python.
• Theory:
o Time series data structure and analysis techniques
o Plotting and visualizing trends in data over time
o Forecasting crop production
o Applications in agricultural yield prediction
• Python Program:
import matplotlib.pyplot as plt
import pandas as pd
# Time series data
data = {'Year': [2018, 2019, 2020, 2021, 2022],
'Yield': [200, 250, 300, 350, 400]}
df = pd.DataFrame(data)
# Plotting the data
plt.plot(df['Year'], df['Yield'], marker='o')
plt.title('Crop Yield Over Time')
plt.xlabel('Year')
plt.ylabel('Yield (in tons)')
plt.show()
Practical Manual for Python Programming
Lab 14: Introduction to Machine Learning
• Aim: To build a simple machine learning model for crop yield prediction.
• Theory:
o Introduction to machine learning algorithms
o Supervised learning: Regression and classification
o Model evaluation techniques
o Using machine learning for agricultural predictions
• Python Program:
from sklearn.linear_model import LinearRegression
import numpy as np
# Example data (Years vs Yield)
years = np.array([2018, 2019, 2020, 2021, 2022]).reshape(-1, 1)
yields = np.array([200, 250, 300, 350, 400])
# Creating a linear regression model
model = LinearRegression()
model.fit(years, yields)
# Predicting crop yield for 2023
predicted_yield = model.predict(np.array([[2023]]))
print(f"Predicted crop yield for 2023: {predicted_yield[0]}")
Practical Manual for Python Programming
Lab 15: GIS Data Processing: Plotting Spatial Data Related to Crop Distribution
• Aim: To process GIS data and plot spatial data related to crop distribution.
• Theory:
o Introduction to GIS data and spatial analysis
o Working with geospatial libraries in Python (e.g., GeoPandas)
o Plotting spatial data on maps
o Analyzing geographical patterns in agriculture
• Python Program:
import geopandas as gpd
import matplotlib.pyplot as plt
# Load GIS data
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
# Plotting world map
world.plot()
plt.title('World Map - Crop Distribution')
plt.show()
Practical Manual for Python Programming
Lab 16: Final Project: Developing a Python Application for a Specific Agricultural Problem
• Aim: To develop a Python application addressing a specific agricultural issue.
• Theory:
o Identifying agricultural problems and solutions
o Project development life cycle
o Integrating various Python libraries for problem-solving
o Final project application in precision farming, pest monitoring, etc.