Python for beginners
You install Python from python.org, make a file ending in py, and run it with one command in a terminal. By the end of this lesson you will have written a real program that measures the length of a text, and you will know how to read a Python error from the bottom up.
- Lesson 4 of 14
- Beginner
- Free, no signup
From the install to the first program that is any use
Five steps, and none of them needs more than a few minutes.
-
1
Install it from python.org
On macOS and most Linux systems it is already there and this step is unnecessary.
-
2
Confirm it with one command
python3 --version should print a number. On Windows, py --version.
-
3
Create a py file
Call it hello.py and make sure the extension really is py, not py.txt.
-
4
Take input and give output
input always gives a string; to calculate you must convert it.
-
5
Write one genuinely useful program
Something you need yourself, not a textbook exercise. That is the one that keeps you going.
These five steps run on your own machine and need no hosting or domain. Running Python on a web host built for PHP pages is a separate and later question.
Last checked: Facts and tool names in this lesson are re-checked against their sources on this date.
Where do you get Python, and how do you know it installed?
From the python.org downloads page and nowhere else. On macOS and most Linux systems Python is already there and you need to install nothing; on Windows you install it.
After the install one job is left, and it is where most beginners get stuck: make sure the terminal can see Python. Open a terminal and type this:
python3 --versionIf a version number is printed, you are done. On the very server where this lesson is being written, the answer to that command is Python 3.12.3.
And now the trap no tutorial mentions: on many systems there is no command called python at all. On this server python answers "command not found" while python3 works. So when a tutorial shows you python file.py and nothing happens, the mistake is not yours; add the 3.
Windows has a third story. Python own documentation says that when several versions are involved, the recommended command is py. So on Windows try py --version first, and then use that same py for the rest of the commands in this lesson.
py --versionIf none of those three commands answers, the problem is not the install; it is that the operating system does not yet know where Python is. The fix differs per system, and the official Windows guide has the Windows version of it.
The first script: from an empty file to output in the terminal
Make a text file and call it hello.py. Any text editor works and today is not the day to shop for tools. Write one line in it:
print("Hello")Now open a terminal in that folder and run it:
python3 hello.pyThe word Hello is printed. That is all. If nothing was printed, check three things in this order: you are in the folder the file is in, the file name really ends in py and not in py.txt, and the command you typed is the one that answered in the previous section.
There is also one rule that separates Python from other languages, and it is better to meet it now: in Python the space at the start of a line means something. There are no braces and no semicolons; you show that something belongs to a block by indenting it, and the whole language is built on that convention.
if 5 > 3:
print("bigger")Those four spaces before print are not decoration, they are syntax. Take them away and Python raises IndentationError. Our advice is to set your editor to insert four spaces for tab, and then never think about it again.
Four things that work and four that stop everything
Nearly every day one "why does it not run" is in the right hand column.
If these are right, it runs
- The version command prints a number
- The file really is saved with a py extension
- The terminal is in the folder the file is in
- The indents are all spaces and not mixed with tabs
If these are true, nothing happens
- You typed python and on this system it does not exist at all
- The editor saved the file as hello.py.txt
- The file is in one folder and the terminal in another
- You copied the code off a web page and invisible spaces came with it
This list only guarantees that the program runs, not that it is correct. Code that runs can still give the wrong answer.
Input and output: a program that talks to the user
A program that only prints is a note. input turns it into something that gets an answer back:
name = input("Your name: ")
print("Hello,", name)Three things live in those two lines. input prints the message you give it and waits, it returns whatever the user typed, and you keep that answer in the variable name so you can use it later.
Now the most important point in this section, and if you do not know it, it becomes the first real error of your programming life: input always returns a string. Python own documentation says exactly that; even when the user types 17, what reaches you is the text "17" and not the number 17.
age = input("Age: ")
print(type(age))The output of those two lines is <class 'str'>. Which means that if you want to add one to it, Python raises an error and you have to convert it first:
age = input("Age: ")
print(int(age) + 1)Why is it like this? Because Python does not guess. If it turned strings into numbers by itself, a program taking a postcode or a card number would lose its leading zeros. The conversion is yours because only you know what that string is supposed to mean. This matters enough that the next lesson in this track is entirely about data types, and the order of the lessons is on the track page.
Your first real program: count the length of a text
Now we write something we genuinely use ourselves. The meta description of every page on this site has to be between 140 and 160 characters; that is our own house rule and it is written in this site content guide. Counting that by eye is hard work, and six lines of Python make it a ten second job.
text = input("Meta description: ")
n = len(text)
if n < 140:
print(f"{n} characters. Too short, {140 - n} to go.")
elif n > 160:
print(f"{n} characters. Too long by {n - 160}.")
else:
print(f"{n} characters. Good.")We ran this three times before shipping this lesson and its real output was: for a 90 character text, 90 characters. Too short, 50 to go.; for 150 characters, 150 characters. Good.; and for 200 characters, 200 characters. Too long by 40.
There are four new things in those six lines. len gives the length of a string. if, elif and else build a three way branch and exactly one of them runs. The f before the quote means you may put braces inside the string and Python works out what is in them; it is called an f-string and it is the easiest way to build text. And arithmetic works inside those braces too, as in {140 - n}.
One exercise worth doing right now: change the condition so that it counts words rather than characters. Hint: len(text.split()). If you changed that yourself and it worked, you are no longer somebody who has taken a tutorial; you are somebody who has written a program.
Got an error? Read the traceback from the bottom
The skill that separates a beginner from somebody who really writes programs is not writing code without errors; it is reading errors. When a program falls over, Python prints a traceback, and that frightening block of text is in fact the most precise friend you have.
Make this file, call it shop.py, and run it:
def price(n):
return n * 1.09
print(price("100"))And this is exactly what gets printed. The real run, not what ought to be printed:
Traceback (most recent call last):
File "shop.py", line 4, in <module>
print(price("100"))
^^^^^^^^^^^^
File "shop.py", line 2, in price
return n * 1.09
~~^~~~~~
TypeError: can't multiply sequence by non-int of type 'float'Now the rule: read it from the bottom. The last line says what happened; here a data type was wrong. The line above it says where it happened: line 2, inside the function price. And above that, who called that place: line 4. So the error appeared on line 2 but its cause is on line 4, where we sent a string instead of a number.
That order holds for every traceback, which is why the habit of reading upwards is worth building today. Read the last sentence first, then look at the lowest line that belongs to your own file, and only then look at the rest.
The first three errors of anybody life are these: SyntaxError means you wrote the sentence wrongly and it is usually a missing bracket or colon; NameError means you called a name that does not exist and most of the time it is a typo; and TypeError is the one above, meaning the type of the data does not fit what you are doing with it.
What comes next: a plan that does not waste your time
The most important thing you need after this lesson is not another tutorial; it is a small program you actually need. But there are four things whose order matters, and the figure below shows that order.
First, the standard library. Python installs with a warehouse of ready code, and most everyday jobs already have a function. Before writing any loop, search the official Python tutorial once to see whether the job is already done.
Then installing outside libraries with pip, and with it the virtual environment. These two lines keep your project separate from the rest of the system:
python3 -m venv .venv
source .venv/bin/activateOn Windows the second line differs and the venv documentation has the correct form. Why bother? Because without it every project you build drops its libraries in the same shared place, and six months later two projects want two different versions of one library while your system has only one.
And finally, when your program passes a hundred lines, move to writing functions and then to classes. Not sooner. Learning classes before you have a pain that classes cure is the mistake that talks a lot of people out of programming.
Five rungs after the first program, in this order
Order matters more than speed here; rung four before rung three only makes confusion.
-
1
Search the standard library
Before writing any loop, check whether that job is already done for you.
-
2
One program you need yourself
A textbook exercise gets abandoned; something that solves a pain of yours does not.
-
3
pip and the virtual environment
The first time two projects want two versions of one library, you will see why.
-
4
Writing functions
When you copy the same piece of code a third time, it is time.
-
5
Classes, only once you have the pain
Learning classes before having a problem they solve is the most common reason people quit.
This ladder is an order, not a timetable. Somebody with two hours a week may stay on the second rung for months, and that is normal.
The fast path, with AI
The fast path for a beginner is not "get the code". Any model writes a six line script, and that is exactly what keeps a person standing still. The real speed is elsewhere: in the loop after the writing. What a professional does is hand the model the code so that it attacks it, finds the inputs that knock the program over, and tries them before a user does. A fast cheap model is enough here; our current pick is in <a class="text-link" href="/en/ai/">the AI section</a>.
- First write the smallest version yourself and run it, even if it is ugly. Code that has run once is a fact; code that has only been read is a guess.
- Hand over your real code with one real input and one real output and ask for the shortest fix list, not a rewrite. A rewrite swaps your code for the model code and leaves you where you were.
- Ask for five inputs that knock the program over, then run those five yourself. That is where the learning happens, not while reading a correct answer.
- Finally ask which standard library function replaces your hand rolled part, and check that function name in the official documentation rather than in the model answer.
Copy-ready recipe
This is my Python code. I wrote it myself and it runs:
{your complete code}
With this input: {one real input}
It printed this: {the real output of that run}
Do four things and do not rewrite:
1. The shortest fix list for this code. For each item: which line, what change,
why. Keep my structure and my names.
2. Five inputs that knock this program over or make it answer wrongly, each with
one sentence saying what happens. Include an empty value, a negative number, a
very long text and non English letters.
3. If any part of this code already exists in the Python standard library, give
the exact function and module name. The name only, no code.
4. One small exercise that moves this program one step forward, and do not write
its answer.
Ask me questions if anything in my code is unclear.
Before you trust the output: The model has no terminal. It cannot see your Python version, your operating system or where your files are, so every sentence about "this should work" is yours to run. The second point matters more: it will occasionally state the name of a library or function that does not exist, with full confidence. The rule is simple, search any suggested <code>import</code> in the official Python documentation before installing it; if it is not there, it does not exist.
AI in this kind of work
Our position on learning with a model is plain: use it as a teacher that asks you questions, not as one that hands over answers. In practice the difference is one sentence you add to the prompt: "explain first, then ask me three questions and wait for my answers." Two of the three tools below have a separate mode built for exactly that.
Tools that actually help
- Claude It has a learning mode that asks questions like a tutor instead of answering, built for exactly the "explain, then quiz me" pattern. Iran is not on Anthropic supported countries list, which we read on Anthropic own page.
- Gemini Its guided learning mode also asks questions rather than answering, and turns your own source into a study guide, flashcards and quizzes. It understands Persian well. Google own page says the Gemini web app runs in over 230 countries and territories, and Iran is not on that list.
- ChatGPT The most common choice and acceptable for basic Python questions. We do not have a page for it in our AI section yet, so we make no claim here about its access or pricing.
Where it backfires
There is one use that works directly against you and it should be said plainly: copy the exercise, take the answer, move on. The answer is right, the page fills up, and nothing happens inside your head. Programming skill is built in exactly the minutes when you are stuck, and the model takes precisely those minutes away from you. If you are doing exercises for a university course, it is also cheating on top of being useless. The second risk is of another kind: the model gives an entirely convincing answer about your error and may explain the wrong layer, syntax when the problem is at run time. That is why this lesson taught the traceback first and only then reached for a model; somebody who reads the traceback can tell whether the answer has anything to do with their problem. And the third risk is access: Iran is on neither of Anthropic two supported countries lists and is not on Google list of countries for Gemini; we read both on the vendor own pages and we do not suggest routes around them.
Sources: Python docs: built-in functions, input Anthropic: supported countries Google: where Gemini Apps are available
Where this advice stops
This lesson takes you as far as a single file script on your own machine and stops there. Deployment, packaging, concurrency and the data libraries are none of them here. There is also a practical limit that many people meet late: a Python script does not run on a web host built for PHP pages; for something that runs continuously you need a server you control. And one honest note about learning itself: reading this page is not learning. The only real measure is that you changed the code and it still worked.
From our own work
Python is the doorkeeper of our own work, and this very lesson went past it. Two Python scripts, one of 281 lines and one of 89, cut every lesson file into its four languages and hunt for forbidden characters in each piece. Today those same two scripts rejected one character in the sibling lesson of this session: a hamza inside a word that looked perfectly fine to the eye. A person did not see it and six lines of Python saw it in under a second. The Python that did it is 3.12.3 and can be checked on this server with python3 --version; on the same server the command python does not exist at all, which is the trap in section one of this lesson.
Real follow-up questions
Should you learn Python 2 or 3?
Version 3, without hesitation. Python 2 has been out of support for years and the python.org downloads page offers only 3. If you meet a tutorial with print "hello" and no brackets, that text was written for version 2 and the rest of it is probably stale as well.
Which editor do you need to start?
The one already on your computer. Any plain text editor saves a py file and on day one that is enough, as long as it does not turn the extension into txt. The editor starts to matter when your project has several files; on that day you will know what you want.
Can you learn Python without English?
Yes, but you have to learn one thing: reading error messages. Error text is English and is not translated, yet it is the same few dozen sentences repeating, and after two weeks you know them by heart. Speaking and writing English is not needed; recognising TypeError and NameError is.