0% found this document useful (0 votes)
4 views10 pages

CS Python Notes

The document provides comprehensive notes on Python programming and its application in agriculture, covering topics such as flowchart design, data types, control constructs, input/output operations, and various data structures like lists and dictionaries. It emphasizes the importance of program design, basic programming concepts, and practical examples relevant to agricultural contexts. Additionally, it introduces functions and their significance in promoting code reuse and modularity.

Uploaded by

adjacentruvengo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

CS Python Notes

The document provides comprehensive notes on Python programming and its application in agriculture, covering topics such as flowchart design, data types, control constructs, input/output operations, and various data structures like lists and dictionaries. It emphasizes the importance of program design, basic programming concepts, and practical examples relevant to agricultural contexts. Additionally, it introduces functions and their significance in promoting code reuse and modularity.

Uploaded by

adjacentruvengo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Computer Science & Technology

Python Programming & AI in Agriculture — Course Notes

1. Program Design Using Flowcharts


What is a Flowchart?
• A flowchart is a visual diagram that represents the steps of an algorithm or program using standardised
symbols connected by arrows.
• Used in the design phase before writing code — helps the programmer plan logic clearly.

Standard Flowchart Symbols


• Oval / Rounded Rectangle: START or END of the program.
• Parallelogram: INPUT (receiving data) or OUTPUT (displaying results).
• Rectangle: PROCESS — a calculation or operation (e.g., total = price * qty).
• Diamond: DECISION — a yes/no question that branches the flow (e.g., Is x > 10?).
• Arrow: Shows the direction of flow between steps.

Data Input, Processing and Output


• Input: Data entered by the user or read from a file (e.g., entering a name or temperature reading).
• Processing: The program performs operations on the input (e.g., calculating an average, comparing
values).
• Output: The result is displayed to the user or written to a file (e.g., printing a result or saving to a
database).
💡 Every program follows this IPO cycle: Input → Process → Output.

The 3 Basic Programming Control Constructs


• 1. Sequence: Instructions executed one after another in order, from top to bottom. No branching.
• Example: Read name → Calculate age → Print greeting.
• 2. Selection (Decision/Branching): The program checks a condition and follows different paths
depending on True or False. Represented by the diamond shape in a flowchart.
• Example: IF age >= 18 THEN print 'Adult' ELSE print 'Minor'.
• 3. Iteration (Looping/Repetition): A block of instructions is repeated until a condition is met or for a set
number of times.
• Example: Keep asking for a password until the correct one is entered.
💡 All programs — no matter how complex — are built from combinations of these 3 constructs.

2. Input, Output and Variables in Python


Our First Python Program
• Python is a high-level, interpreted, general-purpose programming language known for its simple,
readable syntax.
• Python files are saved with the .py extension and run using the Python interpreter.
print("Hello, World!")
💡 print() is the built-in function for displaying output to the screen.

Output – print()
• Used to display text, numbers, or variable values on screen.
print("Welcome to Python")
print("The answer is:", 42)
name = "Rudo"
print("Hello,", name)

Input – input()
• Used to receive data from the user during program execution.
• input() always returns a string — you must convert it if you need a number.
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print("Hello", name, "you are", age, "years old.")

Variables
• A variable is a named storage location in memory that holds a value.
• In Python, variables are created by assignment — no need to declare a type first.
• Variable names must start with a letter or underscore, contain no spaces, and are case-sensitive.
crop_name = "Maize"
yield_per_hectare = 4.5
season_count = 3
is_irrigated = True
💡 Use descriptive variable names to make your code readable (e.g., total_rainfall, not tr).

A Complete Input-Process-Output Program


length = float(input("Enter field length (m): "))
width = float(input("Enter field width (m): "))
area = length * width # PROCESS
print("Field area:", area, "m2") # OUTPUT

3. The Various Python Data Types


Core Data Types
• int (Integer): Whole numbers, positive or negative, with no decimal point.
num_cows = 15
temperature = -3
• float (Floating-point): Numbers with a decimal point. Used for measurements and calculations.
rainfall = 23.7
soil_ph = 6.5
• str (String): A sequence of characters enclosed in single or double quotes. Used for text.
crop = "Sorghum"
region = 'Mashonaland'
• bool (Boolean): Represents one of two values: True or False. Used in conditions and logic.
is_raining = True
has_irrigation = False

Checking the Data Type – type()


• The built-in type() function returns the data type of any variable or value.
x = 10
print(type(x)) # <class 'int'>
y = 3.14
print(type(y)) # <class 'float'>
z = "Hello"
print(type(z)) # <class 'str'>
b = True
print(type(b)) # <class 'bool'>

Type Conversion (Casting)


• Changing a value from one data type to another is called type conversion or casting.
• int() — converts to integer (truncates decimals, does not round).
• float() — converts to floating-point number.
• str() — converts to string.
• bool() — converts to boolean (0, empty string, None = False; anything else = True).
age_str = "25"
age_int = int(age_str) # str to int
price = float("19.99") # str to float
label = str(100) # int to str
print(int(7.9)) # Output: 7 (truncated, not rounded)
💡 Type errors are common bugs. Always ensure the correct type before arithmetic operations.

4. Python Operators
Arithmetic (Maths) Operators
• + (Addition): 5 + 3 = 8
• - (Subtraction): 10 - 4 = 6
• * (Multiplication): 6 * 7 = 42
• ** (Exponentiation / Power): 2 ** 8 = 256
• / (Division — always returns float): 10 / 3 = 3.333...
• // (Floor Division — rounds down to integer): 10 // 3 = 3
• % (Modulus — returns the remainder): 10 % 3 = 1
area = length * width
bmi = weight / (height ** 2)
remainder = 17 % 5 # Result: 2

Relational (Comparison) Operators


• Comparison operators compare two values and return True or False.
• > Greater than: 10 > 5 → True
• < Less than: 3 < 7 → True
• == Equal to: 5 == 5 → True (note: double equals, not single)
• != Not equal to: 4 != 5 → True
• >= Greater than or equal to: 10 >= 10 → True
• <= Less than or equal to: 3 <= 2 → False
💡 = is assignment (x = 5). == is comparison (x == 5). These are NOT interchangeable.
Logical Operators
• Logical operators combine multiple conditions and return True or False.
• AND: Returns True only if BOTH conditions are True.
if age >= 18 and has_id == True:
print("Access granted")
• OR: Returns True if AT LEAST ONE condition is True.
if score >= 50 or bonus == True:
print("Passed")
• NOT: Reverses the boolean value — True becomes False, False becomes True.
if not is_raining:
print("Good day to irrigate")

5. Conditional Statements
IF Statement
• Executes a block of code only if a given condition is True.
• Python uses indentation (4 spaces) to define the code block — no braces like other languages.
score = 75
if score >= 50:
print("You passed!")

IF ... ELSE Statement


• Provides an alternative block to execute when the condition is False.
rainfall = 12
if rainfall >= 20:
print("Sufficient rain")
else:
print("Irrigation needed")

IF ... ELIF ... ELSE Statement


• ELIF (else if) allows checking multiple conditions in sequence. Only the first True branch executes.
mark = 68
if mark >= 80:
grade = "A"
elif mark >= 70:
grade = "B"
elif mark >= 60:
grade = "C"
elif mark >= 50:
grade = "D"
else:
grade = "F"
print("Grade:", grade) # Output: Grade: C
💡 Always end an IF/ELIF chain with ELSE to handle all remaining cases.

6. Looping Statements
The WHILE Loop
• Repeats a block of code as long as a condition remains True.
• Used when the number of repetitions is not known in advance.
• DANGER: If the condition never becomes False, you get an infinite loop.
count = 1
while count <= 5:
print("Count:", count)
count = count + 1 # MUST update the variable to avoid infinite loop
# Output: Count: 1, Count: 2 ... Count: 5
• Agricultural example — keep collecting readings until acceptable:
ph = float(input("Enter soil pH: "))
while ph < 5.5 or ph > 7.5:
print("pH out of range. Apply treatment.")
ph = float(input("Re-enter pH: "))
print("pH acceptable:", ph)

The FOR Loop


• Repeats a block of code a fixed number of times, or over each item in a sequence.
• The range() function generates a sequence of numbers: range(start, stop, step).
for i in range(1, 6):
print("Week", i)
# Output: Week 1, Week 2, Week 3, Week 4, Week 5
• Looping over a list:
crops = ["Maize", "Wheat", "Sorghum"]
for crop in crops:
print("Crop:", crop)
💡 Use FOR when you know how many times to repeat. Use WHILE when you repeat until a condition changes.

7. Strings in Python
What is a String?
• A string is a sequence of characters enclosed in single quotes, double quotes, or triple quotes.
• Strings are immutable — you cannot change individual characters; you create a new string instead.
greeting = "Hello, Farmer!"
multi = """This is a
multi-line string."""

String Indexing and Slicing


• Each character has an index starting at 0 from the left (or -1 from the right).
word = "Python"
print(word[0]) # P
print(word[-1]) # n
print(word[0:3]) # Pyt (start inclusive, end exclusive)
print(word[2:]) # thon (from index 2 to end)

Common String Methods


• len(s) — returns the number of characters.
• [Link]() — converts all characters to uppercase.
• [Link]() — converts all characters to lowercase.
• [Link]() — removes leading and trailing whitespace.
• [Link](old, new) — replaces all occurrences of a substring.
• [Link](delimiter) — splits a string into a list of substrings.
• [Link](sub) — returns the index of the first occurrence of sub (-1 if not found).
• [Link](sub) — counts how many times sub appears in s.
name = " Maize Crop "
print([Link]()) # "Maize Crop"
print([Link]().upper()) # "MAIZE CROP"
print(len("Agriculture")) # 11

String Formatting
• f-strings (formatted string literals) are the modern, clean way to embed variables in strings.
crop = "Maize"
yield_t = 4.5
print(f"Crop: {crop}, Yield: {yield_t} tonnes/ha")
# Output: Crop: Maize, Yield: 4.5 tonnes/ha

String Concatenation
• Strings can be joined with the + operator, or repeated with *.
first = "Agri"
second = "culture"
print(first + second) # Agriculture
print("-" * 20) # --------------------

8. Lists in Python
What is a List?
• A list is an ordered, mutable (changeable) collection of items enclosed in square brackets [ ].
• Lists can hold items of different data types including strings, numbers, booleans, and even other lists.
crops = ["Maize", "Wheat", "Sorghum", "Millet"]
yields = [4.5, 3.2, 2.8, 1.9]
mixed = ["Maize", 4.5, True, 2024]

Accessing List Items


• Use the index number in square brackets. Indexing starts at 0.
print(crops[0]) # Maize
print(crops[-1]) # Millet (last item)
print(crops[1:3]) # ["Wheat", "Sorghum"] (slicing)

Modifying Lists
• Lists are mutable — items can be added, changed, or removed.
crops[1] = "Barley" # Change item
[Link]("Sunflower") # Add to end
[Link](1, "Cotton") # Insert at index 1
[Link]("Millet") # Remove by value
[Link]() # Remove and return last item
[Link](0) # Remove item at index 0
Useful List Methods and Functions
• len(list) — number of items in the list.
• [Link]() — sorts the list in ascending order (in-place).
• [Link]() — reverses the list order (in-place).
• [Link](x) — counts how many times x appears.
• [Link](x) — returns the index of the first occurrence of x.
• sum(list) — returns the total of all numeric items.
• min(list) / max(list) — returns the smallest / largest item.
yields = [4.5, 3.2, 2.8, 1.9]
print(sum(yields)) # 12.4
print(max(yields)) # 4.5
print(len(yields)) # 4

Iterating Over a List


for crop in crops:
print("Growing:", crop)

9. Dictionaries in Python
What is a Dictionary?
• A dictionary is an unordered collection of key-value pairs enclosed in curly braces { }.
• Each key must be unique and immutable (usually a string or number). Values can be any data type.
• Dictionaries are ideal for storing labelled data (like a record or profile).
farm = {
"name": "Green Valley Farm",
"location": "Masvingo",
"hectares": 50,
"irrigated": True
}

Accessing and Modifying Values


print(farm["name"]) # Green Valley Farm
print(farm["hectares"]) # 50
farm["hectares"] = 65 # Update a value
farm["crop"] = "Maize" # Add a new key-value pair
del farm["irrigated"] # Delete a key-value pair

Useful Dictionary Methods


• [Link]() — returns all keys.
• [Link]() — returns all values.
• [Link]() — returns all key-value pairs as tuples.
• [Link](key) — returns value or None if key doesn't exist (safer than direct access).
• key in dict — checks if a key exists (returns True/False).
for key, value in [Link]():
print(key, ":", value)
💡 Use a dictionary when data has labels (name, age, yield). Use a list when data is a simple ordered sequence.
10. Functions in Python
What is a Function?
• A function is a named, reusable block of code that performs a specific task.
• Functions promote code reuse, readability, and modular design.
• Defined with the def keyword, followed by the function name and parentheses.

Built-in (Inbuilt) Functions


• Python comes with many built-in functions ready to use without importing anything.
• print() — displays output to the screen.
• input() — reads user input as a string.
• int(), float(), str(), bool() — type conversion functions.
• len() — returns the length of a string, list, or other sequence.
• range() — generates a sequence of numbers for loops.
• sum(), min(), max() — mathematical functions for sequences.
• type() — returns the data type of a value.
• abs() — returns the absolute (positive) value of a number.
• round(x, n) — rounds x to n decimal places.
print(abs(-15)) # 15
print(round(3.14159, 2)) # 3.14

User-Defined Functions
• Programmers create their own functions using the def keyword.
• Parameters are variables listed in the function definition that receive input values.
• Arguments are the actual values passed when calling the function.
• The return statement sends a result back to the caller.
def calculate_area(length, width):
area = length * width
return area

field_area = calculate_area(10, 25)


print("Area:", field_area, "m2") # Area: 250 m2
• A function with a default parameter:
def greet_farmer(name, language="English"):
if language == "Shona":
print(f"Mhoro, {name}!")
else:
print(f"Hello, {name}!")

greet_farmer("Tendai", "Shona") # Mhoro, Tendai!


greet_farmer("John") # Hello, John!
💡 A function should do ONE thing and do it well. Keep functions short and focused.

Agricultural Example – Full Program


def crop_recommendation(rainfall, soil_ph):
if rainfall > 600 and 5.5 <= soil_ph <= 7.0:
return "Maize"
elif rainfall > 400:
return "Sorghum"
else:
return "Millet"

rain = float(input("Annual rainfall (mm): "))


ph = float(input("Soil pH: "))
print("Recommended crop:", crop_recommendation(rain, ph))

11. Artificial Intelligence in Agriculture


What is Artificial Intelligence?
• Artificial Intelligence (AI) is the simulation of human intelligence by computer systems — enabling
machines to learn, reason, perceive, and make decisions.
• In agriculture, AI analyses large datasets from sensors, satellites, images, and historical records to
provide actionable insights.

Applications of AI in Agriculture
• Crop Yield Prediction: AI models (Random Forests, neural networks) predict expected yields based on
soil, weather, and historical data, helping farmers and governments plan ahead.
• Disease and Pest Detection: Computer vision and CNNs analyse drone and smartphone images to
identify crop diseases, pest infestations, and nutrient deficiencies early.
• Precision Irrigation: AI-driven systems analyse soil moisture data and weather forecasts to automate
irrigation, applying water only when and where needed.
• Weed Detection and Removal: AI-powered robots and drones identify weeds from crops using image
recognition and apply targeted herbicides, reducing chemical use by up to 90%.
• Livestock Health Monitoring: AI analyses sensor data from collars and cameras to detect early signs of
disease, stress, or abnormal behaviour in animals.
• Market Price Forecasting: AI models predict commodity prices based on supply, demand, weather, and
global market trends, helping farmers decide when to sell.
• Soil Analysis and Mapping: AI processes satellite imagery and sensor data to create detailed soil fertility
maps, guiding variable-rate fertiliser application.
• Automated Machinery: Self-driving tractors and harvesters guided by GPS and AI reduce labour costs
and improve operational precision.
• Chatbots & Advisory Systems: AI-powered chatbots deliver personalised farming advice to smallholder
farmers via SMS or smartphone apps in local languages.

Real-World Examples
• PlantVillage (Penn State, USA): AI platform providing crop disease diagnosis and agricultural advice to
smallholder farmers in Africa via smartphone — used in Kenya, Ethiopia, and Zambia.
• IBM Watson Decision Platform for Agriculture: Integrates weather data, satellite imagery, and IoT sensor
data to provide AI-driven field insights.
• Taranis (Israel): Uses ultra-high-resolution aerial imaging and AI to detect early crop stress, disease, and
pest damage at individual plant level.
• Blue River Technology – See & Spray: AI-powered robot identifies and sprays individual weeds,
drastically reducing herbicide use.
• Aerobotics (South Africa): Drone-based AI platform used across sub-Saharan Africa for orchard
monitoring, pest detection, and yield estimation.
Benefits of AI in Agriculture
• Increased efficiency — optimal use of inputs (water, fertiliser, pesticides).
• Early warning systems — detect problems before visible damage occurs.
• Labour savings — automation reduces dependence on manual labour.
• Data-driven decisions — replace guesswork with evidence-based recommendations.
• Food security — better yield planning supports national and regional food supply.

Challenges of AI Adoption in Developing Countries


• High cost of technology — sensors, drones, and AI platforms are expensive for smallholder farmers.
• Digital literacy gap — many rural farmers lack skills to use AI tools effectively.
• Data scarcity — AI models need large local datasets; data from African farms is limited.
• Connectivity — AI cloud systems require internet access, which is unreliable in rural areas.
• Relevance — many AI tools are developed for large-scale Western agriculture and don't suit smallholder
African farming contexts.

End of Notes — Good luck with your assignment!

You might also like