No history yet

Python Basics

Python's Building Blocks

Python is the language of choice for many AI and machine learning developers, and for good reason: it’s clean, readable, and powerful. Before we can build intelligent systems, we need to master the fundamental grammar and vocabulary of Python. Think of it as learning the alphabet and basic sentence structure before writing a novel.

Python has become the go-to programming language for artificial intelligence (AI) and machine learning (ML) due to its simplicity, readability, and extensive libraries.

Variables and Data Types

In programming, we need a way to store information. We do this with variables. A variable is like a labeled box where you can keep a piece of data. You give the box a name, and you can put things in it, take them out, or replace them.

Python is smart about the type of data you store. You don't have to explicitly tell it what kind of information a variable holds; it figures it out automatically. The most common data types are:

Data TypeDescriptionExample
intInteger, a whole number.age = 30
floatFloating-point number, a number with a decimal.pi = 3.14
strString, a sequence of characters.name = "HAL 9000"
boolBoolean, a value that is either True or False.is_active = True

You can assign a value to a variable using the equals sign (=). Let's create a few:

# An integer
model_version = 4

# A float
accuracy = 0.98

# A string
model_name = "GPT-4"

# A boolean
requires_training = False

If you're ever unsure what type of data a variable holds, you can use the built-in type() function to find out.

print(type(model_name))
# Output: <class 'str'>

Making Decisions and Repeating Tasks

A program that just runs from top to bottom isn't very smart. To add intelligence, we need our code to make decisions and perform repetitive tasks. This is done with control structures.

The most common decision-making tool is the if statement. It checks if a condition is true, and if so, it runs a block of code. You can also provide alternative paths with elif (else if) and else.

temperature = 25

if temperature > 30:
    print("It's hot outside.")
elif temperature < 10:
    print("It's cold outside.")
else:
    print("The weather is moderate.")

For repetitive tasks, we use loops. A for loop is great for iterating over a sequence, like a list of items. A while loop is used to repeat a block of code as long as a certain condition remains true.

Use a for loop when you know how many times you need to repeat something. Use a while loop when you need to repeat until a condition changes.

# A for loop that prints numbers 0 through 4
for i in range(5):
    print(f"Processing item number {i}")

# A while loop that counts down from 3
countdown = 3
while countdown > 0:
    print(f"{countdown}...")
    countdown = countdown - 1
print("Liftoff!")

Organizing Your Code

As programs grow, it's important to keep them organized. Functions are reusable blocks of code that perform a specific task. You define a function once and can then call it whenever you need it, which saves you from writing the same code over and over.

# Define a function to greet a user
def greet(name):
    return f"Hello, {name}! Welcome to the system."

# Call the function
message = greet("Dave")
print(message)

# Output: Hello, Dave! Welcome to the system.

Python also allows you to use modules, which are files containing Python code. Think of them as pre-built toolkits. Python has a rich standard library of modules for all sorts of tasks. To use one, you just need to import it.

# Import the 'math' module
import math

# Use the sqrt function from the math module
square_root = math.sqrt(16)

print(square_root)
# Output: 4.0

Sometimes, code doesn't run as expected and raises an error, or an exception. Good programmers anticipate this. You can handle potential errors gracefully using a try...except block. This tells Python to try a piece of code, and if a specific error occurs, except for that case, run some other code instead of crashing.

numerator = 10
denominator = 0

try:
    result = numerator / denominator
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")

Now, let's test your understanding of these core concepts.

Quiz Questions 1/6

What will be the data type of the result variable after this code runs?

x = 10
y = 5.5
result = x + y
Quiz Questions 2/6

In Python, you must declare the data type of a variable before assigning a value to it.

These are the fundamental building blocks of Python. With a solid grasp of variables, control structures, and functions, you're ready to start building more complex programs and explore the libraries that make Python a powerhouse for AI.