# Python Fundamentals: The Basics You Need Before Anything Else

Almost everything in AI engineering is written in Python. The models, the libraries, the APIs, the tutorials. So this is where the coding starts.

This post is for people who are new to Python. If you already write loops and functions without looking things up, you can skip it. Here's a quick test. What does this print?

```python
total = 0
for n in range(1, 6):
    if n % 2 == 0:
        total += n
print(total)
```

If you said 6 without running it, skip ahead to Post 6. If that code looked like a puzzle, stay. By the end of this post you'll read it easily.

## Get Python running

You need two things: Python itself, and a place to write code.

1.  Install a recent version of Python (3.11 or newer) from python.org.
    
2.  Install [VS Code](https://code.visualstudio.com/) as your editor. It's free and works well for this.
    
3.  Open a terminal and check it worked:
    

```bash
python --version
```

If you see a version number, you're set. On some systems the command is `python3` instead of `python`. Use whichever one works.

To run a file, save your code as `hello.py` and type:

```bash
python hello.py
```

You can also type `python` on its own to open a little playground where you test one line at a time. It's perfect for quick experiments.

## Variables: names for things

A variable is a name that points to a value.

```python
name = "Asha"
age = 29
height = 1.62
is_learning = True
nothing_yet = None
```

That's five variables, and you never had to say what type each one is. Python figures it out. That's one reason people find it easy to start with.

A few habits to pick up now:

-   Use `snake_case` for names: `total_cost`, not `TotalCost` or `totalcost`.
    
-   Make names say what the thing is. `price` is better than `p`.
    
-   Names are case sensitive. `Age` and `age` are different variables.
    

## The basic types

You'll use these five constantly:

| Type | Example | What it's for |
| --- | --- | --- |
| int | 42 | whole numbers |
| float | 3.14 | numbers with decimals |
| str | "hello" | text |
| bool | True, False | yes or no |
| None | None | "nothing here yet" |

Check the type of anything with `type()`:

```python
print(type(age))      # <class 'int'>
print(type(name))     # <class 'str'>
```

One quirk you should know about early, because it surprises everyone:

```python
print(0.1 + 0.2)      # 0.30000000000000004
```

That's not a Python bug. Computers store decimals in a way that can't represent some numbers exactly, and you'll see the same thing in almost every language. It matters later when you compare numbers in AI code, so keep it in the back of your mind.

## Working with text

Text, called a string, comes up in every AI project. Prompts are strings. Model replies are strings. So get comfortable with them.

The nicest way to put values inside text is an f-string. Put an `f` before the quotes and wrap variables in curly braces:

```python
print(f"{name} is {age} years old")
# Asha is 29 years old
```

Strings also come with useful built-in tools:

```python
message = "  Hello, World  "

print(message.strip())         # Hello, World
print(message.lower())         # "  hello, world  "
print(message.split(","))      # ['  Hello', ' World  ']
print(message.strip()[0:5])    # Hello
```

`strip()` removes extra spaces from the ends. `split()` cuts a string into pieces. And `[0:5]` is a slice, which means "from position 0 up to, but not including, position 5." Python counts from zero, which feels odd for about a week and then feels normal.

## Making decisions with if

```python
score = 72

if score >= 90:
    print("Excellent")
elif score >= 60:
    print("Pass")
else:
    print("Try again")
```

Two things to notice. First, the colon at the end of each condition line. Second, the **indentation**. In Python, the spaces at the start of a line aren't decoration. They tell Python which code belongs inside the `if`. Use four spaces, and your editor will usually do it for you when you press Tab.

Here's a handy fact. Python treats some values as "false" even when they aren't literally `False`: `0`, an empty string `""`, `None`, and empty lists. Everything else counts as true. So you can write:

```python
reply = ""

if not reply:
    print("The model returned nothing")
```

You'll write checks like that all the time when handling model output.

## Repeating things with loops

A `for` loop runs code once for each item:

```python
for number in range(1, 4):
    print(number)
# 1
# 2
# 3
```

`range(1, 4)` gives 1, 2, 3. It stops _before_ the second number, the same way slices do.

You can loop over a list of things too:

```python
for word in ["python", "is", "fun"]:
    print(word.upper())
```

A `while` loop keeps going as long as something stays true:

```python
count = 3

while count > 0:
    print(count)
    count -= 1
```

Be careful with `while`. If nothing ever makes the condition false, the loop runs forever. If that happens, press `Ctrl + C` to stop it. It happens to everyone.

Two tools worth knowing: `break` leaves a loop early, and `continue` skips to the next round.

Now go back to the puzzle at the top. `range(1, 6)` gives 1 to 5, `n % 2 == 0` checks if a number is even (`%` gives the remainder after dividing), and `total += n` means "add n to total." So it adds 2 and 4, and prints 6.

## Functions: reusable chunks

A function packages some code under a name so you can use it again.

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

print(greet("Asha"))     # Hello, Asha!
```

`def` starts the function, `name` is its input (called a parameter), and `return` hands back the result.

You can give a parameter a default value:

```python
def power(base, exponent=2):
    return base ** exponent

print(power(5))        # 25
print(power(5, 3))     # 125
```

We'll go much deeper into functions in Post 6. For now, the main idea is enough: write a function whenever you catch yourself copying the same code twice.

## How Python actually runs your code

You don't need this to write programs, but it explains a lot later, so here's the short version.

When you run `python hello.py`, Python reads your file from top to bottom. Behind the scenes it first turns your code into a simpler set of instructions called bytecode, and then a program called the Python interpreter carries out those instructions one at a time.

That makes Python quick to write and easy to debug, but slower than languages like C when you're doing raw number crunching in loops.

So why is Python the language of AI? Because the heavy work doesn't happen in Python. Libraries like NumPy and PyTorch do the heavy math in fast C, C++, and GPU code. Your Python code just tells them what to do. It's a bit like a conductor, who doesn't play every instrument but makes the orchestra work together. You get the easy language and the speed.

## Reading error messages

You'll see a lot of errors. That's normal and it never fully goes away, even for experienced people. The trick is to read them properly.

```python
age = 29
print("Age: " + age)
```

```python
TypeError: can only concatenate str (not "int") to str
```

Read the **last line first**. It tells you what went wrong: you tried to join text and a number. Then look at the line number above it to see where. The fix:

```python
print(f"Age: {age}")
```

A few errors you'll meet early:

-   `NameError`: you used a name that doesn't exist, usually a typo.
    
-   `TypeError`: you mixed types that don't go together.
    
-   `IndentationError`: your spacing is off.
    
-   `SyntaxError`: something is missing, often a colon or a closing bracket.
    

We'll cover debugging properly in Post 11.

## Mini project: a token and cost estimator

Language models don't read words. They read _tokens_, which are small pieces of text. And you're charged by the token when you use most model APIs. So estimating tokens is useful from day one.

A rough rule of thumb for English is about 4 characters per token. It's not exact, but it's close enough to get a feel for size and cost.

Create a file called `token_estimator.py`:

```python
text = input("Paste some text: ")

characters = len(text)
words = len(text.split())

# Rough rule of thumb: about 4 characters per token in English
estimated_tokens = characters / 4

# Made-up price. Check your provider for real numbers.
price_per_million_tokens = 3.00
estimated_cost = estimated_tokens / 1_000_000 * price_per_million_tokens

print(f"Characters: {characters}")
print(f"Words: {words}")
print(f"Estimated tokens: {estimated_tokens:.0f}")
print(f"Estimated cost: ${estimated_cost:.6f}")
```

Run it with `python token_estimator.py`, paste in a paragraph, and see what comes out.

A few new bits in there: `len()` counts how many characters or items something has, `input()` asks the user to type something, and `:.0f` inside an f-string means "show this number with no decimals."

The price is invented on purpose. Real prices change often and differ between models, so never trust a number from a blog post. Look it up for the one you're using.

### Make it yours

Change the project so that it isn't just my example anymore:

1.  Print a warning if the estimate goes above 1,000 tokens.
    
2.  Read the text from a file instead of asking you to paste it.
    
3.  Wrap it in a `while` loop so you can check many texts, and stop when you type `quit`.
    

## Practice

Try these without looking anything up. Aim for about 20 minutes of honest effort before you ask for help.

1.  Ask for the user's name and print a greeting.
    
2.  Convert a temperature from Celsius to Fahrenheit.
    
3.  Count the vowels in a sentence.
    
4.  Print the numbers from 1 to 20, but print "Fizz" for multiples of 3.
    
5.  Write a function `is_even(n)` that returns `True` or `False`.
    

When you finish, paste your solution into an AI tutor and ask it to _review_ the code, not rewrite it. That's the habit from Post 3, and it works.

## What to take away

-   Variables are names for values, and Python figures out the type for you.
    
-   Strings, numbers, booleans, and `None` cover most of what you'll use early on.
    
-   Indentation is part of the syntax.
    
-   Functions let you reuse code instead of copying it.
    
-   Python is mostly the glue. The fast work happens in libraries underneath.
    
-   Read error messages from the last line up.
    

* * *

**Previous:** Post 3, _How to Learn AI Faster_

**Next in the series:** Post 5, _Built-in Data Structures_, where we learn lists, dictionaries, sets, and tuples, and how fast each one is.

---

*Published via [ZyVOP](https://zyvop.com/python-fundamentals-the-basics-you-need-before-anything-else-w48xn?utm_source=hashnode&utm_medium=crosspost&utm_campaign=syndication) — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.*
