Python for AI Agents
Python Basics
The Building Blocks
Think of a variable as a labeled box where you can store information. You give the box a name, and you put something inside it. In Python, you can create a variable and assign it a value with a single line.
# A variable named 'message' holds the text "Hello, world!"
message = "Hello, world!"
# A variable named 'agent_version' holds the number 1
agent_version = 1
# A variable named 'is_active' holds the value True
is_active = True
The type of information you store determines the variable's data type. Python is flexible, so you don't have to declare the type beforehand. It figures it out automatically.
Here are the most common data types you'll encounter:
- Strings (
str): Plain text, enclosed in quotes."Hello, I am an AI." - Integers (
int): Whole numbers, like-5,0, and42. - Floats (
float): Numbers with decimal points, like3.14or-0.001. - Booleans (
bool): Represents truth values. It can only beTrueorFalse.
Making Decisions and Repeating Actions
Programming isn't just about storing data; it's about doing things based on that data. Control structures allow you to direct the flow of your program.
To make a decision, you use an if statement. It checks if a certain condition is true and runs a block of code only if it is. You can add elif (else if) for more conditions and else for a fallback option.
temperature = 25
if temperature > 30:
print("It's hot outside.")
elif temperature < 10:
print("It's cold outside.")
else:
print("The weather is moderate.")
When you need to repeat an action, you use a loop. A for loop is great for iterating over a sequence of items, like a list. A while loop is used to repeat a block of code as long as a condition remains true.
A
forloop is like working through a checklist. Awhileloop is like stirring a pot until the sauce thickens.
# A for loop that prints each item in a list
指令 = ["Observe", "Think", "Act"]
for step in 指令:
print(step)
# A while loop that counts down from 3
countdown = 3
while countdown > 0:
print(countdown)
countdown = countdown - 1
print("Liftoff!")
Packaging Your Code
As your programs get more complex, you'll find yourself writing the same lines of code over and over. Functions solve this by letting you package a block of code, give it a name, and call it whenever you need it. Think of it as a recipe you can use anytime.
A function can take inputs, called arguments, and can return an output.
# Defines a function named 'greet' that takes one argument, 'name'
def greet(name):
return f"Hello, {name}! How can I help you?"
# Calls the function with the argument "Alex" and prints the result
response = greet("Alex")
print(response)
# Output: Hello, Alex! How can I help you?
Related functions can be grouped together into files called modules. Python has a vast standard library of modules you can use without writing them yourself. To use one, you just need to import it.
# Import the 'math' module to get access to math functions
import math
# Use the sqrt() function from the math module
root = math.sqrt(64)
print(root)
# Output: 8.0
Creating Your Own Blueprints
Object-Oriented Programming (OOP) is a way of thinking about and organizing your code. The core idea is to create blueprints, called classes, that define a type of object. An object is then a specific instance created from that blueprint.
For example, you could have a Car class. The class itself is just the design. An actual car that you build from that design—say, a specific red convertible—is an object.
Classes define two things for their objects:
- Attributes: Data or properties the object has (like
colororspeed). - Methods: Actions the object can perform (like
start_engine()ordrive()).
# Define a class named 'Agent'
class Agent:
# This is the initializer method, it runs when an object is created
def __init__(self, name, task):
self.name = name # An attribute
self.task = task # An attribute
# This is a method
def introduce(self):
print(f"I am {self.name}, and my task is {self.task}.")
# Create two different Agent objects (instances)
agent_one = Agent("Aura", "to schedule meetings")
agent_two = Agent("Bolt", "to analyze data")
# Call the introduce() method on each object
agent_one.introduce()
agent_two.introduce()
This approach helps keep your code organized, reusable, and easier to manage, which is especially important when building complex systems like AI agents.
Now that you've seen the fundamental building blocks of Python, let's test your understanding.
In Python, what determines a variable's data type?
What will the following Python code print?
temperature = 15
if temperature > 25:
print("Hot")
elif temperature > 10:
print("Warm")
else:
print("Cold")
With these basics, you have the foundation needed to start writing simple programs and, eventually, to explore the exciting world of AI development.