Welcome. This book assumes you know nothing about programming. If you have never written a single line of code, you are exactly who it was written for. If you already know a little, the early chapters will still fill gaps you didn't know you had, and the later parts go all the way down to how Python works inside.
Before we write any code, we need two things: a clear picture of what programming is, and a working Python on your computer. That is all this chapter does.
0.1 What is a program?
A program is a list of instructions that a computer follows, one after another.
Think of a recipe for making a cup of tea:
Boil one cup of water.
Put a tea bag in a mug.
Pour the hot water into the mug.
Wait three minutes, then take out the tea bag.
Add milk and sugar.
A recipe works because each step is clear and the steps happen in order. A program is the same idea, with one big difference: a computer has no common sense. A person reading "add sugar" knows not to add a kilogram. A computer does exactly what it is told — nothing more, nothing less. If the instruction is wrong, the computer will happily do the wrong thing, very fast.
That is the whole game of programming: writing instructions so precise that a machine with zero common sense does the right thing.
Why can't we just talk to the computer in English?
Deep down, a computer's processor only understands machine code: long sequences of numbers that mean things like "add these two numbers" or "copy this value to that place in memory". Writing programs directly in machine code is possible, but painfully slow and error-prone.
So people invented programming languages. A programming language is a halfway point between human language and machine code. It is strict and precise like machine code, but readable like English. A separate program then translates your code into something the processor can run.
English is too vague for this job. "Print the list of students sorted by marks" — ascending or descending? What if two students have the same marks? A programming language forces you to answer those questions.
Practice 0.1
Multiple choice
A recipe says "add sugar" and a person knows how much is sensible. What is the big difference between a person and a computer, according to this section?
Think about what a computer does with an instruction that is wrong.
The section says a computer does exactly what it is told, nothing more and nothing less.
The answer is: A computer has no common sense
A computer follows each instruction exactly as written. It does not notice that an instruction is silly, so the instructions must be precise.
Multiple choice
What is the only thing that a computer's processor understands directly?
It is made of long sequences of numbers.
A programming language sits halfway between human language and this.
The answer is: Machine code
The processor runs machine code only. A separate program translates the code you write into something the processor can run.
0.2 What is Python?
Python is a programming language created by Guido van Rossum and first released in 1991. Its name comes from the British comedy group Monty Python, not the snake (though the snake logo stuck).
Here is a complete Python program that adds up the marks of three subjects and shows the total:
Even without knowing any Python, you can probably guess what every line does. That readability is Python's biggest strength. You don't need to understand this code yet — variables come in → Chapter 3 and print in → Chapter 1.
Where Python is used
Python is one of the most widely used programming languages in the world. You will find it in:
Area
What Python does there
Artificial intelligence and machine learning
Training and running models (PyTorch, TensorFlow, scikit-learn)
Data science
Cleaning, analysing and charting data (pandas, NumPy, Matplotlib)
Web development
The server side of websites and apps (Django, Flask, FastAPI)
The first language taught in many universities, including IIT Madras's online BS degree
Why Python is a great first language
Readable. Python code looks close to plain English and uses very few symbols.
Forgiving setup. You can type a line and see the result instantly, without a long build step.
Huge standard library. Python comes with tools for maths, dates, files, the internet and much more already built in. People call this "batteries included".
Massive community. Almost any question you have has already been asked and answered online.
It grows with you. The same language you use for your first print is used to build AI systems at the world's biggest companies.
Practice 0.2
Multiple choice
Where does the name Python come from?
The logo shows a snake, but the logo came later.
The name comes from a group of comedy performers.
The answer is: A British comedy group
Python is named after the comedy group Monty Python. The snake logo was added because of the name, not the other way round.
Multiple choice
People say that Python has "batteries included". What do they mean?
Read the list of reasons why Python is a great first language.
The phrase describes the standard library.
The answer is: Python comes with many tools already built in
Python comes with a huge standard library: tools for maths, dates, files, the internet and more are ready to use.
Multiple choice
An old tutorial uses Python 2. What does this chapter say about Python 2?
Look at the note at the end of the section.
Python 2 is no longer used for new code.
The answer is: It was officially retired in 2020
Python 2 was retired in 2020. This book uses Python 3.15, and new code is written in Python 3.
0.3 How to read this book
Every chapter follows the same pattern so you always know where you are.
Code you can run appears in a box with a blue edge. What it prints appears right below it, in a box marked OUTPUT:
print("Hello from the book!")
Output
Hello from the book!
Every one of these examples was actually run on Python 3.15 before the book was built, and the output you see is the real output — not typed from memory.
The Python shell (you will meet it in section 0.5) appears in a dark box. Lines starting with >>> are what you type; the lines without >>> are Python's reply:
>>> 7*6
42
Output
The terminal (the black window where you type commands to your computer) appears in a dark box marked TERMINAL. You type the line after the > or $:
Terminal
> python --version
Python 3.15.2
Boxes with a coloured label highlight special things:
Chapter markers like → Chapter 7 appear whenever something shows up before it is properly taught. When you see one, don't worry about the details yet — just know that a full explanation is coming in that chapter.
At the end of every chapter you will find a recap, practice questions, coding problems from easy to hard, and full answers. Try each problem before looking at the answer. Struggling for ten minutes teaches you more than reading an answer in ten seconds.
Practice 0.3
Multiple choice
In this book you sometimes see a marker such as "→ Chapter 7" beside a new idea. What does the marker tell you?
The marker is about something that shows up before its own lesson.
You can keep reading. The full explanation comes later.
The answer is: The idea appears here early and Chapter 7 explains it fully
A chapter marker says that a full explanation is coming in that chapter. You do not need the details yet.
Predict the output
This small script is saved in a file and run. What does it print?
print("Hello from Tokyo!")print(7*6)
The first line shows its text without the quotes.
The second line shows the result of the multiplication.
It prints
Hello from Tokyo!
42
Each print shows one line. Text is shown as it is written, and a calculation is worked out first.
0.4 Installing Python
Let's get Python 3.15 onto your computer. Follow the section for your system and skip the others.
Windows
On Windows, Python is installed with a small tool called the Python install manager. It installs Python for you, keeps it updated, and lets you have more than one version side by side.
Get the install manager. Either:
open the Microsoft Store, search for Python install manager, and click Install; or
go to python.org/downloads, download the Windows installer, and double-click it.
Both are the same tool, so pick one — don't install both.
Open a terminal. Press the Windows key, type Terminal (or PowerShell), and open it.
Install Python 3.15 by typing this and pressing Enter:
> py install 3.15
The first time, it may ask a few yes/no setup questions, such as whether to add a folder to your PATH. Type y and press Enter. PATH is the list of folders Windows searches when you type a command; adding Python to it lets you type python from anywhere.
Check it worked:
> python --version
Python 3.15.2
The last number may be different (3.15.3, 3.15.4 …). Any 3.15 is fine.
After installing, three commands are available: python (runs your default Python — use this one), py (the same, plus extra management commands) and pymanager. To see which versions you have, type py list.
macOS
Go to python.org/downloads and download the macOS installer for Python 3.15.
Open the downloaded .pkg file and click through the installer.
Install the security certificates. Open Applications → Python 3.15 and double-click Install Certificates.command. A Terminal window opens; wait until it says update complete, then close it. Without this step, Python can fail when it downloads things over the internet.
Open the Terminal app (press ⌘ + Space, type Terminal, press Enter) and check:
$ python3 --version
Python 3.15.2
On a Mac, the command is python3, not python. Whenever this book says python, type python3 instead.
Linux
Most Linux systems already include Python 3. Check which version you have:
Terminal
$ python3 --version
Python 3.12.3
If you see 3.10 or newer, you can follow almost the whole book right away. To get 3.15 itself, the simplest route on any distribution is a tool called uv, which installs Python versions into your home folder without touching the system one. You will learn uv properly in → Chapter 43; for now you can use your system Python and come back to this.
No computer? Online editors
If you're on a phone, a school computer, or just want to start right now, you can use an online Python editor in your browser — search for "online Python editor". These work well for Parts 0–2 of this book. From Part 5 onwards (files, modules, packages) you will want Python installed on a real computer.
Practice 0.4
Multiple choice
You follow this book on a Mac. The book says to type python. What do you type?
Read the macOS part of the section again.
The command on a Mac has a digit at the end.
The answer is: python3
On a Mac the command is python3. Whenever the book says python, a Mac user types python3.
Multiple choice
During the Windows setup you are asked about your PATH. What is PATH?
It explains why you can type python from any folder.
It is a list, and Windows searches it.
The answer is: The list of folders Windows searches when you type a command
When you type a command, Windows looks for it in the folders listed in PATH. With Python in that list, python works from anywhere.
Multiple choice
Which tool installs Python on Windows in the way this chapter recommends?
You can get it from the Microsoft Store or from python.org.
After it is installed, you type py install 3.15.
The answer is: The Python install manager
The Python install manager installs Python, keeps it updated and lets you have more than one version side by side.
0.5 Two ways to run Python
There are two ways to give Python instructions. You will use both all the time.
Way 1: the interactive shell (the REPL)
Open your terminal and type python (or python3 on Mac/Linux), then press Enter:
Terminal
> python
Python 3.15.2 (main, ...) on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
The >>> is Python's prompt. It means "I'm ready, type something." Type a calculation and press Enter:
>>> 2+3
5
>>> 365*24
8760
>>> 10/4
2.5
Output
Python reads what you typed, evaluates it (works out the answer), prints the result, and loops back to >>> to wait for more. Read, Evaluate, Print, Loop — that's why this is also called the REPL.
The shell is perfect for quick experiments: "what does this do?" You type, you see, instantly.
To leave the shell, type exit and press Enter. (Keyboard shortcuts also work: Ctrl + Z then Enter on Windows, Ctrl + D on Mac and Linux.)
Way 2: script files
The shell forgets everything when you close it. Real programs are saved in files so you can run them again, change them, and share them. A Python file is just a plain text file whose name ends in .py. Such a file is called a script.
Make a new folder for your work, for example python-book on your Desktop or D:\python-book.
Inside it, create a file called hello.py containing this one line:
print("Hello, Python!")
In the terminal, go into that folder with cd ("change directory"), then run the file:
> cd D:\python-book
> python hello.py
Hello, Python!
Python opened hello.py, ran every line from top to bottom, and stopped at the end of the file. That's what running a program means.
The shell and scripts behave differently
Here's an important difference that confuses many beginners. In the shell, Python shows the value of anything you type:
>>> 10+5
15
Output
But in a script, that same line shows nothing:
10+5
Output
Python does calculate 15, but in a script it only shows things when you explicitly ask with print:
print(10+5)
Output
15
The shell echoes values to be helpful while you experiment. A script stays quiet unless told otherwise — imagine a program that printed every single calculation it did; you would drown in output.
Practice 0.5
Multiple choice
The letters in REPL stand for Read, Evaluate, Print, Loop. What does Python do in the "Evaluate" step?
The step comes after reading and before printing.
Something must be calculated before it can be shown.
The answer is: It works out the answer
Python reads what you typed, evaluates it (works out the answer), prints the result and loops back to the prompt.
Multiple choice
What is a Python script?
A script is something you can save, change and share.
Think of hello.py.
The answer is: A plain text file whose name ends in .py
A script is a plain text file with a name that ends in .py. Python runs its lines from top to bottom.
Multiple choice
These three lines are saved in a file, and the file is run from the terminal. What appears?
365*24print(10+5)print("Done")
This is a script, not the shell. Does a script show the value of every line?
Only the lines with print show something.
The answer is: Two lines: 15, then Done
In a script, Python does calculate 365 * 24, but it shows nothing for that line. A script shows only what you ask for with print.
Predict the output
This script is run from the terminal. What does it print?
print(2+3)print(10/4)print("2 + 3")
The shell session in this section shows what 10 / 4 gives.
Look at the quotes in the last line. Text inside quotes is shown as it is written.
It prints
5
2.5
2 + 3
The first two lines are calculations, so Python works them out. The last line is text, so it is shown without any calculation.
Fix the bug
This script should show the number of hours in a year of 365 days. When you run it, nothing appears. Fix it.
The program prints the lines below. Your program must print exactly these lines.
Example run
8760
Output
The calculation is correct. Why does a script stay quiet?
Wrap the calculation in print( ).
print(365*24)
The shell shows the value of anything you type. A script shows a value only when you ask with print.
Fill in the blank
Fill in the blank so that the script shows its text.
("Hello, Python!")
The finished program prints:
Target
Hello, Python!
Which word asks Python to show something?
It is the word used in hello.py.
print("Hello, Python!")
print shows what is inside its brackets. Without it, a script shows nothing.
Put the lines in order
Put the lines in order so that the script prints the target.
The program in the right order prints:
Target
Start
8760
End
print("End")
print(365*24)
print("Start")
Python runs a script from the top line to the bottom line.
The first line of the target comes from the first line of the script.
print("Start")print(365*24)print("End")
Python opens the file and runs every line from top to bottom, so the order of the lines is the order of the output.
0.6 Setting up your editor: VS Code
You can write Python in Notepad, but a proper code editor colours your code, spots mistakes as you type, and runs files with one click. This book uses Visual Studio Code (VS Code): free, works on Windows, macOS and Linux, and used by professional developers everywhere.
Download VS Code from code.visualstudio.com/download and install it. On Windows, choose the User Installer and keep Add to PATH ticked on the Select Additional Tasks page; on a Mac, drag Visual Studio Code into Applications; on Ubuntu or Debian, install the .deb file with sudo apt install ./<file>.deb.
Open VS Code. On the left, click the Extensions icon (four small squares).
Search for Python and install the extension published by Microsoft.
Choose File → Open Folder… and open your python-book folder.
Open hello.py. In the top-right corner there is a ▷ Run button. Click it.
VS Code opens a terminal at the bottom of the window and runs your file. You should see Hello, Python!.
Practice 0.6
Multiple choice
In VS Code you search the Extensions for Python. Several results appear. Which one do you install?
Read step 3 of the list in this section.
Look at the name of the publisher.
The answer is: The one published by Microsoft
The Python extension published by Microsoft is the one this book uses. It lets VS Code run your file with the Run button.
Multiple choice
VS Code asks you to "select an interpreter". What is the interpreter?
Look at the tip near the end of the section.
You choose the one that mentions Python 3.15.
The answer is: The Python program that will run your code
The interpreter is the Python program itself. If you have more than one version, VS Code needs to know which one to use.
Fill in the blank
Fill in the blank so that the script prints the target. Write the text with its quotes.
print()
The finished program prints:
Target
Hello, Python!
The target is text, so it goes inside quotes.
Copy the target exactly, with the comma and the exclamation mark, and put quotes round it.
print("Hello, Python!")
Text inside quotes is shown exactly as it is written. This is the one line of hello.py.
0.7 Getting help
You will get stuck. Everyone does — professionals included. Here is how to get unstuck:
Read the error message. It almost always says what went wrong and on which line. Chapter 1 shows you how to read one.
Use Python's built-in help. In the shell, help(print) shows how print works. Press q to get out of the help screen.
Read the official documentation at docs.python.org. It is complete, accurate and free.
Search the exact error message online. Somebody has almost certainly hit it before you.
Experiment in the shell. "What happens if…?" is answered fastest by trying it.
Practice 0.7
Multiple choice
You typed help(print) in the shell and a help screen opened. Which key gets you out of the help screen?
It is a single letter.
It is the first letter of the word "quit".
The answer is: q
The help screen stays open until you press q. After that you are back at the >>> prompt.
0.8 Your setup checklist
Before moving to Chapter 1, make sure you can tick every box:
[ ] python --version (or python3 --version) prints a 3.15 version
[ ] You can open the shell, calculate 2 + 3, and exit
[ ] You have a folder for your book work
[ ] hello.py runs from the terminal and prints Hello, Python!
[ ] VS Code with the Python extension runs hello.py with the ▷ button
Practice 0.8
Put the lines in order
The checklist says that you can calculate 2 + 3 and that hello.py prints its greeting. Put the lines in order so that the script prints the target.
The program in the right order prints:
Target
My setup works
5
Hello, Python!
print(2+3)
print("Hello, Python!")
print("My setup works")
Compare each line of the target with the lines of the script.
A script runs from top to bottom, so the output lines appear in the same order as the print lines.
+ Practice
Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.
Questions
Check yourself
In your own words, what is a program?
Show the answer
A precise list of instructions that a computer follows in order, exactly as written.
Check yourself
Why do we need programming languages instead of giving instructions to the computer in English?
Show the answer
English is vague and full of assumptions. A computer has no common sense, so it needs instructions with exactly one possible meaning. Programming languages are designed to be unambiguous, and they can be translated into the machine code a processor actually runs.
Check yourself
What do the letters in REPL stand for?
Show the answer
Read, Evaluate, Print, Loop.
Check yourself
You type 50 * 2 in the shell and see 100. You put the same line in a file and run it, and nothing appears. Why?
Show the answer
The shell automatically shows the value of whatever you type. A script only shows things you explicitly print. The multiplication still happens in the script; the result just isn't displayed.
Check yourself
What file extension do Python scripts use?
Show the answer
.py
Check yourself
On a Mac, which command starts Python: python or python3?
Show the answer
python3.
Check yourself
What does the >>> symbol mean?
Show the answer
It is the shell's prompt: Python is waiting for you to type something.
Check yourself
Name three areas where Python is widely used.
Show the answer
Any three of: AI and machine learning, data science, web development, automation, science and research, education.
Hands-on tasks
Check yourself
Shell calculator. Use the shell to find: the number of seconds in a day; the number of hours in a year (use 365 days); and what 100 divided by 3 gives.
Notice the last digit of 100 / 3: it ends in 6, not 3. Computers store decimal numbers in binary and can't store 33.333… exactly. This is normal and explained in → Chapter 4.
Check yourself
Your first file. Create about_me.py that prints your name on one line and your city on the next. Run it from the terminal and from VS Code.
Show the answer
— about_me.py (use your own name and city):
print("Alex")print("Tokyo")
Output
Alex
Tokyo
Check yourself
Spot the difference. Create quiet.py containing just the line 7 * 8. Run it. Then change it so the answer appears.
Show the answer
— quiet.py with only 7 * 8 prints nothing. Wrap it in print:
print(7*8)
Output
56
Check yourself
Explore help. In the shell, type help(len). What do you think len does? (You'll meet it properly in → Chapter 7.)
Show the answer
— len gives the length of something: the number of characters in a piece of text, or the number of items in a collection.
>>> len("Python")
6
More practice
Write code
Shell calculator as a script. Write a script that prints three lines, in this order: the number of seconds in a day, the number of hours in a year of 365 days, and what 100 divided by 3 gives. Let Python do every calculation.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
86400
8760
33.333333333333336
Output
A day has 24 hours, an hour has 60 minutes and a minute has 60 seconds. Multiply with *.
In a script, every calculation needs its own print( ). Division is written with /.
print(24*60*60)print(365*24)print(100/3)
The shell would show these values by itself. A script needs one print for each value.
Write code
Name and city. Write a script that prints exactly two lines: Maya on the first line and Lima on the second line.
The program prints the lines below. Your program must print exactly these lines.
Example run
Maya
Lima
Output
Each print shows one line.
Text goes inside quotes: print("Maya"). Write a second line of the same kind for the city.
print("Maya")print("Lima")
Two print lines give two lines of output, in the order in which they are written.
Fix the bug
This script should print the label first and the number below it. Now the two lines come out in the wrong order. Fix it.
The program prints the lines below. Your program must print exactly these lines.
Example run
Minutes in one day
1440
Output
Python runs the lines from top to bottom.
Swap the two lines.
print("Minutes in one day")print(24*60)
The output follows the order of the lines in the file. To change the order of the output, change the order of the lines.
Predict the output
This script is run from the terminal. What does it print?
print("Seconds in one hour")60*60print(60*60)print(9/2)
One line of this script has no print. What does a script show for that line?
9 / 2 is not a whole number. The result has a decimal point, like 10 / 4 in section 0.5.
It prints
Seconds in one hour
3600
4.5
The line without print shows nothing in a script. The other three lines each show one line of output.
Chapter project: Water for a week
Project
Write your first small report. Maya drinks 8 glasses of water every day. One glass holds 250 millilitres. Create a file called water.py and write a script that prints five lines, in this order:
the text Water plan
the number of glasses Maya drinks in a week of 7 days
the number of millilitres she drinks in one day
the number of millilitres she drinks in a week
the number of litres she drinks in a week (1000 millilitres make one litre)
Let Python do every calculation: write the calculation inside print, not the result. Use only what this chapter showed: print with text in quotes, and print with a calculation that uses * and /.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Water plan
56
2000
14000
14.0
Output
A script shows only what you print, so the report needs five print lines, one below the other.
Glasses in a week: glasses per day times 7. Millilitres in a day: glasses per day times 250.
For the week in millilitres, multiply three numbers in one line. For litres, write the same calculation and put / 1000 at the end.
The script uses the three ideas of section 0.5: a file runs from top to bottom, it shows only what you print, and Python works out a calculation before it shows the result.