Python for AIPython for AI
Python Basics

Code formatting

Keep your code clean and readable

What is code formatting?

Writing clean, consistent code is important. Code formatting means organizing your code so it's easy to read and follows Python's style guidelines.

Basic formatting principles

Follow these basic rules for readability:

Indentation

Use 4 spaces for indentation (not tabs):

python
def greet(name):
    if name:
        print(f"Hello, {name}!")
    else:
        print("Hello!")

Spacing

Add spaces around operators and after commas:

python
# Good
x = 1 + 2
numbers = [1, 2, 3, 4]

# Bad
x=1+2
numbers=[1,2,3,4]

Blank lines

Use blank lines to separate functions and logical sections:

python
def first_function():
    pass

def second_function():
    pass

Line length

Keep lines under 80–100 characters. Break long lines for readability:

python
# Good - readable
long_string = (
    "This is a very long string that "
    "spans multiple lines for readability"
)

# Bad - too long
long_string = "This is a very long string that spans multiple lines for readability but keeps going and going"
Later in the course, you'll learn about Ruff — a tool that automatically formats your code. But understanding these basics first helps you write better code naturally.

Automatic formatting with Ruff

Want to format your code automatically? Check out the Ruff guide in the tools section — it lints and formats your Python code in one step.

Practice

Try these exercises to lock in what you just learned.

Quiz
Not started
Which of these is an f-string?
Fill in the blanks
Not started
Complete the greeting using an f-string.
1name = "Ada"
2
Code challenge
Not started
Print exactly: Name: Ada, Age: 36

What's next?

Now that you understand formatting, let's learn about variables!