Learn to code in Codex
120 Python Exercises with AI: From Your First Prompt to Your First Real Project with OpenAI Codex, Codex CLI, and ChatGPT
Fran Orellana
Free sample · First chapters
This book is intended for adults with no programming experience or only basic knowledge who want to learn Python while working with Codex in ChatGPT, the app, or Codex CLI. You do not need to know how to program: all you need is a computer, an Internet connection, and a willingness to practise. The book progresses from easier to more difficult material across eight sections. Each section begins with a lesson titled “What You Need to Know,” which explains the essential concepts before you tackle the exercises. In each challenge, you will learn how to write a useful prompt for Codex, check the code it suggests, modify it, and analyse the most common errors. Try to solve each exercise on your own before asking the AI for help or looking at the solution. The annotated solutions appear at the end of the book and are intended for comparing decisions, not for replacing practice. The next chapter, “Set Up Your Environment,” explains step by step how to install Python, prepare Codex, configure Codex CLI, and get your workspace ready.
To do the exercises, you need four things:
You do not need to know how to program. You do not need to pay to install Python either. The account and Codex features available to you may depend on your ChatGPT plan.
The simplest way to get started is:
Later, you can use Codex CLI, which runs from the terminal. It is optional to begin with.
Before creating any code, prepare a folder that is easy to find.
On Windows:
Documents.learn_to_program.Enter.On macOS:
Documents.learn_to_program.Enter.Each exercise will have its own files. You can create other folders inside this folder, such as exercise_01, exercise_02, and so on.
For now, you only need to create the main folder. Do not create the exercise files yet.
Python is the program that will run the code you write. Download it from its official website:
https://www.python.org/downloads/
Choose the stable version available for your operating system.
The Add Python to PATH checkbox allows you to run Python from the terminal. If you do not check it, Python may be installed, but the computer will not know how to find it easily.
Some computers already have a version of Python installed, but it may be old. For these exercises, we will use a modern version of Python 3.
Now you will check the installation. This check is important: do not start the exercises until you get a response similar to the one shown below.
PowerShell.Command and the space bar.Terminal.Type this command and press Enter:
BASH
python --version
On macOS, if it does not work, try this one:
BASH
python3 --version
On Windows, you can also try:
BASH
py --version
You should see something similar to this:
CÓDIGO
Python 3.13.5
The numbers may be different. What matters is that it starts with Python 3.
If a message such as “python is not recognized” or “command not found” appears, Python is not available under that name. Try python3 or py. If neither works, reinstall Python and check that you selected Add Python to PATH on Windows.
A code editor is a program for writing programming files. You can use a free editor such as Visual Studio Code, available from its official website:
https://code.visualstudio.com/
Install it using the recommended options.
You can also use a simple editor that is already on your computer. However, Visual Studio Code displays indentation, quotation marks, and Python errors more clearly.
When you open Visual Studio Code:
learn_to_program folder.You do not need to install any extensions to get started. Later, you can install the official Python extension if Visual Studio Code recommends it.
Before working with Codex, you will check that you can create and run a file.
In Visual Studio Code:
check.py.Enter.PYTHON
message = "Python works" print(message)
5. Save the file with Ctrl+S on Windows or Command+S on macOS.
Now open a terminal inside Visual Studio Code:
On Windows:
BASH
python check.py
If python does not work, try:
BASH
py check.py
On macOS:
BASH
python3 check.py
You should see:
CÓDIGO
Python works
If you see this text, Python can read and run your file. You now have the basic installation ready.
You can delete check.py when you finish the check.
Codex can help you from several places. To get started, use whichever method is most convenient for you.
Option 1: ChatGPT
Open ChatGPT from its official website:
https://chatgpt.com/
Sign in and open Codex if it appears among the available tools. Depending on your account, it may appear as a workspace option, an application, or a tool for working with code.
Option 2: Codex app
If the Codex app is available for your system, download it only from the official OpenAI website or your operating system’s official store. Install it and sign in with your OpenAI account.
Option 3: Codex CLI
Codex CLI is a version that you use by typing commands in the terminal. Its installation process may change over time. Always check the current instructions in the official OpenAI documentation. A common installation uses Node.js and this command:
BASH
npm install -g @openai/codex
Then start it with:
BASH
codex
The first time, it may ask you to sign in. Follow the instructions that appear on the screen.
If you do not want to install Node.js or use the terminal to talk to Codex, use ChatGPT. You can complete the exercises by following the explanations and copying the files into your editor.
Codex works best when you give it specific information. Do not write only “make me a program.” State the language, the goal, and the limitations.
For example, a useful request would be:
CÓDIGO
I want to learn Python from scratch. Explain how to create a small program that displays a message. Do not write the complete code yet. First, tell me which concepts I will use and ask me a question to check that I understand.
The exercises in this book will ask you to make similar requests. Codex can write code, but you must read it, run it, and check it.
When Codex gives you code:
.py file.Do not assume that a program is correct just because Codex wrote it.
Always follow this order:
If the exercise says that the file is called program.py, use that exact name. In Python, the .py extension identifies a code file.
To run a file located in the current folder, use:
BASH
python program.py
On macOS, you may need to use:
BASH
python3 program.py
An error does not mean that you have failed. It is a message indicating which part needs to be reviewed.
For example, if you write:
PYTHON
print("Hello)Python may display an error because a quotation mark is missing. Opening and closing quotation marks must form a pair.
When an error appears:
You can also ask Codex for help by including the complete error:
CÓDIGO
Here is my code: [paste the code here] Here is the complete error: [paste the message here] Explain the problem in simple words. Do not change the code yet. Tell me which line I should review and why.
Do not paste only a sentence such as “it does not work.” The code and the complete message make it easier to find the cause.
A correct program is not merely a program that runs without errors. It must also do what the exercise asks.
Check these three things:
For example, if a program asks for a name, try your name and a different one. If it works only with one specific value, you still need to review it.
Save your files after every change. If a modification makes the result worse, you can undo it with Ctrl+Z on Windows or Command+Z on macOS.
You do not need any prior knowledge. During the exercises, you will learn, in order:
You only need to know how to use the keyboard, open a folder, copy and paste text, and follow instructions step by step. If you can run the test file and see Python works, you are ready to start the first exercise.
You’ll learn to ask Codex for small programs and check their results. You’ll practice the essential syntax for transforming simple data into useful programs.
Before you begin, remember the workflow with Codex: ask it for one specific thing, read the code it suggests, run it, and check the result. If an error appears, copy the complete message and ask it to explain what it means before accepting a change.
Imagine that you want to store a person’s name to use later:
PYTHON
name = "Ana" print(name)
The program stores "Ana" in a variable called name and then displays its contents.
A variable is a name that points to a piece of data. The = sign is used to store a value in a variable. It does not mean “is equal to” as it does in a mathematical operation.
PYTHON
price = 12 quantity = 3
You can change the value whenever you want:
PYTHON
quantity = 4
Use clear names, normally written in lowercase with underscores:
PYTHON
total_price = 25.50
Common mistake: writing the name in quotation marks when you want to use the variable. print("name") displays the word name; print(name) displays the stored value.
Look at these three pieces of data:
PYTHON
product = "notebook" units = 4 price = 2.50
"notebook" is text, 4 is an integer, and 2.50 is a decimal number.
Text is written inside single or double quotation marks:
PYTHON
city = "Seville" message = 'Hello'
Integers do not use quotation marks:
PYTHON
age = thirty
The previous example would be incorrect because thirty is not a valid number written in Python. You should write:
PYTHON
age = 30
Decimals use a period, not a comma:
PYTHON
temperature = 21.5
If you write 21,5, Python interprets it differently, not as a single decimal number.
Common mistake: storing a number in quotation marks, such as quantity = "4". In that case, it is text, and you will not be able to add it directly to another number.
input()You have already used input(), but you need to remember one important detail. Look at this:
PYTHON
name = input("What is your name? ")
print(name)The program displays the question, waits for you to type a response, and stores what you entered in name.
Everything that comes from input() is text, even if you enter numbers:
PYTHON
age = input("How old are you? ")If you enter 25, Python stores "25", not 25. The quotation marks do not appear on the screen, but they indicate that the data is text.
You can store the response directly in a variable and use it later:
PYTHON
color = input("Favorite color: ")
print("You chose", color)Common mistake: trying to perform a mathematical operation directly with the response from input(). For example, age + 1 fails because age is text until you convert it.
int() and float()To convert the text "25" into the integer 25, use int():
PYTHON
age = int(input("How old are you? "))
print(age + 1)To convert text into a decimal number, use float():
PYTHON
price = float(input("What is the price? "))
print(price * 2)The general form is:
PYTHON
integer = int(text) decimal = float(text)
The user must enter a value that can be converted. int("25") works, but int("twenty-five") produces an error because Python cannot transform that word into an integer.
Common mistake: entering a decimal with a comma, such as 2,50, when float() normally expects 2.50. It also fails if the response is left blank or contains letters.
This small program calculates an amount:
PYTHON
price = 10 quantity = 3 amount = price * quantity print(amount)
The main operators are:
PYTHON
+ # add - # subtract * # multiply / # divide
You can also use parentheses to make an operation clearer:
PYTHON
total = (price * quantity) + shipping_costs
Python follows a priority order similar to that used in mathematics: it first calculates what is inside parentheses, then multiplications and divisions, and finally additions and subtractions.
For example:
PYTHON
result = 2 + 3 * 4
The result is 14 because it calculates 3 * 4 first. If you wanted to add first, write:
PYTHON
result = (2 + 3) * 4
Common mistake: forgetting a parenthesis or using a decimal comma. Also check that you are not trying to divide by zero.
Suppose you want to check whether a purchase exceeds 50 euros:
PYTHON
total = 63 print(total > 50)
Python displays True because 63 is greater than 50. If the condition is not met, it displays False.
The comparison operators are:
PYTHON
== # equal to != # not equal to > # greater than < # less than >= # greater than or equal to <= # less than or equal to
The double equal sign == compares two values. The single equal sign = stores a value:
PYTHON
age = 18 # store age == 18 # check
Common mistake: using = inside a condition when you meant to compare. Python needs == to ask whether two values are equal.
if, elif, and elseLook at a simple decision:
PYTHON
age = 20
if age >= 18:
print("You can enter")
else:
print("You cannot enter")if means “if this condition is true.” else indicates what to do when it is not true.
When there are several possibilities, use elif:
PYTHON
grade = 7
if grade >= 9:
print("Outstanding")
elif grade >= 5:
print("Pass")
else:
print("Fail")Python checks the conditions from top to bottom and executes only the first block whose condition is true. The colons : and indentation are required:
PYTHON
if condition:
instructionCommon mistake: forgetting the colons or failing to leave four spaces before the inner instructions. Another frequent mistake is placing a condition that is too general first, preventing the following conditions from being checked.
To build a message with data, you can write:
PYTHON
name = "Ana"
total = 18.5
message = f"{name} must pay {total} euros"
print(message)The letter f before the quotation marks allows you to insert variables between curly braces {}.
You can also include expressions:
PYTHON
quantity = 2
price = 4.5
print(f"Total: {quantity * price} euros")f-strings are easier to read than joining many pieces of text with +.
Common mistake: forgetting the f before the quotation marks. In that case, Python would display {name} literally instead of the variable’s contents.
name = value.input() always returns text.int() or float().if, elif, else, and comparisons such as == or >=.Exercises 1 through 6.
Level: Easy
Create a file named saludo.py and write a program that displays two lines on the screen. The first should say Hola, Codex and the second should say Estoy aprendiendo Python. Run the file from your working environment and check that the text appears in exactly that order, one line below the other. You do not need to ask the user for input or store information in variables: in this exercise, you will only practice the instruction that displays messages on the screen.
Example
Execution:
CÓDIGO
Hola, Codex Estoy aprendiendo Python
HINT
Use one instruction to display each line. If you want them to appear on separate lines, write a separate instruction for each message.
Level: Easy
Write a program that stores a person's data in three variables: their name, age, and height in meters. Use a string for the name, an integer for the age, and a decimal number for the height. Then display a sentence with all three pieces of data, indicating what each one represents. Use the values Ana, 32, and 1.68. The result should be readable and appear on a single line.
Example
Execution:
CÓDIGO
Name: Ana, age: 32 years, height: 1.68 meters
HINT
Assign each piece of data to a different variable and combine the variables with an f-string to build the final sentence.
Level: Easy
Create a program that asks the user how old they are, converts the response to an integer, and calculates how old they will be next year. Then, display the result in a sentence. The prompt must be How old are you? and, for testing, enter the value 28. The program must perform the conversion before adding one year.
Example
Execution:
CÓDIGO
How old are you? 28 Next year you will be 29 years old.
HINT
input() always returns text. Convert that text to an integer before adding.
Level: Easy
Create a program that calculates the final cost of a purchase. The purchase consists of 3 units of a product that costs 12.50 euros each. First apply a 10% discount to the cost of the products, then add 3 euros for shipping. Store the data in variables and display the result with two decimal places. To calculate the discount, multiply the subtotal by 0.10; the final price will be the subtotal minus that discount plus the shipping cost.
Example
Execution:
CÓDIGO
Total: 36.75 euros
HINT
Calculate the subtotal first. Then calculate the discount based on that subtotal and combine the operations using parentheses so that the order is clear.
Level: Easy
Create a program that asks for an exam score and decides how to classify it. Convert the input to an integer. If the score is between 0 and 4, display Needs improvement. If it is between 5 and 6, display Pass. If it is between 7 and 10, display Good result. For any other value, display Invalid score. Test the program by entering 8. The comparisons must include the indicated limits.
Example
Execution:
CÓDIGO
Enter the score: 8 Good result
HINT
First check whether the value is within a valid range. Then use elif to separate the ranges and else for values that do not fit.
Level: Easy
Create a program that asks for the name of a product, the quantity purchased, and its price per unit. Then, calculate the total amount by multiplying the quantity by the price. Display a purchase summary over several lines: the product, the quantity, the price per unit, and the total. Build these messages using f-strings to insert the values into the text. For prices, keep two decimal places so the summary is easy to read. The program should produce a result equivalent to the example when the same data is entered.
Example
Input:
Product: notebook
Quantity: 3
Price per unit: 2.5
Output:
Product: notebook
Quantity: 3
Price per unit: 2.50 €
Total: 7.50 €
HINT
Store each piece of data in a variable and calculate the total before preparing the message. An f-string can contain text and variables on the same line; to display two decimal places, use the appropriate format for the numeric value.
Want to know what happens next? Get the full book:
Prices checked in the stores on 4 Nov 2026; they may change.
Back to the book page