Logo

Cyber Freeze AI

1.4: Python Fundamentals for AI Part-2

Learn about functions, lists, dictionaries, file handling, and error management in Python in a simple and beginner-friendly way.

·
·4 min. read
Cover Image for 1.4: Python Fundamentals for AI Part-2

1.4: Building Blocks of Python

Welcome back! In this chapter, we’ll explore three important tools in Python—functions, lists, and dictionaries—and use them to solve simple problems. Then, we’ll learn about file handling (reading and saving files) and error handling (what to do if something goes wrong in your code). Let’s dive in!

Follow Along on Google Colab!

You can interact with this entire tutorial in a Google Colab notebook. Open the Colab notebook here to run the code yourself, experiment with examples, and see the results in real time. No setup needed—just click and start coding!


What Are Functions?

Functions are like mini-programs inside your code. They save time by letting you reuse code instead of writing it over and over again.

What Can Functions Do?

  1. Take inputs (like numbers or text).
  2. Do some work (like calculations or printing messages).
  3. Give you back a result (if needed).

Example: A Function to Say Hello

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))  # Output: Hello, Alice!

In this example:

  • greet(name) is the function.
  • name is the input.
  • The function returns a greeting message.

Why Use Functions?

They make your code cleaner and easier to understand. You can change how a function works without affecting the rest of your code.


What Are Lists?

Lists are like boxes where you can store a group of things, like numbers, words, or anything else.

How Do Lists Work?

  1. Create a List: Use square brackets [].
  2. Add to a List: Use .append() to add something new.
  3. Look at the List: Use loops to go through each item.

Example: A List of AI Frameworks

# List of AI tools
frameworks = ["TensorFlow", "PyTorch", "Scikit-learn"]

# Add a new item
frameworks.append("Hugging Face")

# Print each item
for framework in frameworks:
    print(framework)

In this example:

  • The list stores names of AI tools.
  • .append() adds a new item to the list.
  • The for loop goes through the list and prints each item.

What Are Dictionaries?

Dictionaries are like real-life dictionaries. They match keys (words) to values (meanings). In Python, they store information as key-value pairs.

Example: An AI Dictionary

# Dictionary of AI concepts
ai_concepts = {
    "ML": "Machine Learning",
    "DL": "Deep Learning",
    "NLP": "Natural Language Processing"
}

# Print a value
print(ai_concepts["NLP"])  # Output: Natural Language Processing

Here:

  • ML, DL, and NLP are the keys.
  • Machine Learning, Deep Learning, and Natural Language Processing are their values.

You can:

  1. Add new key-value pairs.
  2. Update values.
  3. Look up a value using its key.

How to Work with Files

Imagine you want to save your program’s results or load data from a file. Python can help you do this easily.

Reading Files

# Open a file and read its content
with open("data.txt", "r") as file:
    content = file.read()
    print(content)
  • The with keyword makes sure the file is properly closed after reading.
  • "r" means "read mode"—you’re opening the file to read its content.

Writing Files

# Open a file and write to it
with open("output.txt", "w") as file:
    file.write("Hello, AI World!")
  • "w" means "write mode"—you’re creating or replacing a file with new content.

What to Do When Things Go Wrong?

Sometimes, your program might break because of mistakes or unexpected situations (like a missing file). Python lets you handle these problems without crashing.

Using Try-Except

The try block lets you run risky code, and the except block tells Python what to do if something goes wrong.

Example: Dividing by Zero

try:
    result = 10 / 0  # This causes an error
except ZeroDivisionError:
    print("You can't divide by zero!")

Here, instead of crashing, the program prints a helpful message.

Using Else and Finally

  • else: Runs if there’s no error.
  • finally: Runs no matter what (good for cleanup tasks).

Example: Checking for a File

try:
    file = open("non_existent_file.txt", "r")
except FileNotFoundError:
    print("File not found!")
else:
    print(file.read())
finally:
    print("Finished trying to open the file.")

What’s Next?

Great job! You’ve learned:

  1. How to write functions.
  2. How to store and manage data using lists and dictionaries.
  3. How to work with files.
  4. How to handle errors safely.

In the next chapter, we’ll focus on cleaning and analyzing data using Python. These skills are essential for anyone working in AI. Stay tuned!

Be First to Like