Python for absolute beginners: a hands-on first tutorial
Never written a line of code in your life? Good — this is written for you. We start from “what even is Python” and finish with a small program you build yourself, one patient step at a time.
If you can use a spreadsheet, send an email, and follow a recipe, you can learn to program. Python is the friendliest place to start, because it was designed to read almost like plain English: its official summary describes it as a language whose “elegant syntax” and “dynamic typing” make it “ideal for scripting and rapid application development.”1 This tutorial assumes you know nothing about coding. Every new idea is introduced with a tiny, runnable example, and every language feature links to the official Python documentation2 so you can always dig deeper.
You don't need to memorise anything. Read a section, type the example yourself (typing beats copy-pasting when you're learning), watch what happens, then move on. Let's begin.
01What Python is, in one minute
Python is a programming language — a way of writing precise instructions that a computer will carry out. You write plain text in a file (or type it live), and a program called the Python interpreter reads your instructions from top to bottom and does what they say.1
People reach for Python for an enormous range of things: analysing data, building websites, automating boring tasks, scientific research, and the artificial-intelligence tools you've been hearing about. You do not need to know any of that yet. For now, think of Python as a very literal, very fast assistant that does exactly what you tell it — no more, no less.
02Get Python running (pick one of three ways)
Before writing code, you need somewhere to run it. Here are three options, from zero-setup to proper installation. Any one of them works for this whole tutorial.
Option A — Run it online (nothing to install)
The fastest start is a browser-based Python. Search for an “online Python interpreter,” or use the official interactive shell available from the Python website. You type code, press a button, and see the result — no downloads. This is perfect for your first hour.
Option B — Install Python on your computer (recommended)
Go to the official downloads page at python.org/downloads, download the latest version for your system, and run the installer.3 As of mid-2026 the current version is Python 3.14 — any Python 3 will do for this guide.
- Windows: during installation, tick the box that says “Add Python to PATH” before clicking Install. This one checkbox saves a lot of confusion later.
- macOS: download the macOS installer and run it, or install via the official package. A modern Mac may already have a Python, but installing the latest from python.org keeps things predictable.
- Linux: Python 3 is very likely already installed; open a terminal and type
python3 --versionto check.
Python comes with a simple built-in editor called IDLE. After installing, open IDLE from your applications — it gives you a place to type code live and a place to save programs, which is all we need.
Option C — A code editor (for when you're ready)
Later you may want a fuller editor like VS Code. Don't worry about this yet; IDLE or an online interpreter is completely fine for learning the basics.
03Your first program: print()
Every programming journey traditionally starts by making the computer say hello. Open IDLE's editor (or your online interpreter), type exactly this, and run it:
print("Hello, world!")Run it and you'll see:
Hello, world!Small as it is, a lot just happened. print is a function — a ready-made command that does a job for you; this one displays text on the screen.5 The round brackets () are how you “call” (use) a function, and whatever you put inside them is what you're giving it to work with. The text in quotes, "Hello, world!", is called a string — programmer-speak for a piece of text.
The interactive shell (your Python playground)
Python also has an interactive mode, often called the REPL — you type one line, press Enter, and it answers immediately.4 In IDLE this is the window with the >>> prompt. It's the best place to experiment:
>>> print("Hi!")
Hi!
>>> 2 + 2
42 + 2 and press Enter. The shell prints 4 without you asking it to print — a convenience that only happens in interactive mode. Inside a saved program, you'd write print(2 + 2).04Variables: giving names to things
A variable is a name that points to a value, so you can reuse it. You create one with a single equals sign, =, which means “store the thing on the right under the name on the left.”
name = "Ada"
age = 36
print(name)
print(age)Ada
36Now name stands for "Ada" everywhere you use it. You can change what a variable points to at any time — just assign again. Because Python figures out the type of value on its own (text, whole number, and so on), you never have to declare it in advance; this is what “dynamic typing” means.1
Naming rules and good habits
- Names can use letters, numbers, and underscores, but can't start with a number:
score,player_2, andtotal_priceare fine;2playeris not. - Names are case-sensitive:
Ageandageare two different variables. - Choose descriptive names.
total_pricetells the next reader (often future-you) far more thantp. Python's official style guide, PEP 8, recommends lowercase words joined by underscores for ordinary names.6
05Working with text (strings)
A string is text wrapped in quotes — single '...' or double "...", Python treats them the same.7 You can join strings together with + and repeat them with *:
first = "Grace"
last = "Hopper"
full = first + " " + last # join with a space between
print(full)
print("ha" * 3) # repeat the text three timesGrace Hopper
hahahaf-strings: the modern way to build text
Gluing strings with + gets clumsy fast. Python's formatted string literals — “f-strings” — let you drop variables straight into text by putting an f before the opening quote and wrapping each variable in curly braces.9 This is the style you'll use most:
name = "Ada"
age = 36
print(f"{name} is {age} years old.")Ada is 36 years old.Handy string tricks
Strings come with built-in methods — actions you run by writing a dot after the string.8 A few you'll use constantly:
msg = " Hello There "
print(msg.upper()) # ALL CAPS
print(msg.lower()) # all lowercase
print(msg.strip()) # remove surrounding spaces
print(len(msg)) # how many characters (including spaces) HELLO THERE
hello there
Hello There
15len() is a built-in function that measures length; the others are methods that belong to the string. Don't worry about the exact distinction yet — just notice the two shapes: len(thing) versus thing.action().
06Numbers and simple math
Python handles two everyday kinds of number: integers (whole numbers like 7) and floats (numbers with a decimal point like 3.14).7 The math symbols are what you'd expect, with a couple of useful extras:
print(10 + 3) # 13 addition
print(10 - 3) # 7 subtraction
print(10 * 3) # 30 multiplication
print(10 / 3) # 3.333... division (always gives a float)
print(10 // 3) # 3 floor division (drops the remainder)
print(10 % 3) # 1 modulo (the remainder)
print(10 ** 3) # 1000 exponent (10 to the power of 3)The remainder operator % looks obscure but is quietly one of the most useful tools you'll meet — for example, number % 2 is 0 for every even number, which is how you test “is this even?”
Text and numbers don't mix (until you convert them)
This trips up every beginner, so let's meet it head-on. The number 5 and the text "5" are different things. You convert between them with int(), float(), and str():
count = "5" # this is TEXT, not a number
print(int(count) + 1) # convert to a real number first -> 6
print("Total: " + str(42)) # convert 42 to text to join it -> Total: 42Why does this matter? Because everything a user types is text — which is exactly the next topic.
07Talking to the user: input()
The input() function pauses your program, shows a prompt, and waits for the person to type something and press Enter. Whatever they type comes back as a string.10
name = input("What is your name? ")
print(f"Nice to meet you, {name}!")What is your name? Sam
Nice to meet you, Sam!Because input() always returns text, you must convert it when you want a number. This is the single most common beginner bug — and now you already know the fix from section 6:
age_text = input("How old are you? ")
age = int(age_text) # turn "36" into 36
print(f"Next year you'll be {age + 1}.")08Making decisions: if / elif / else
Real programs make choices. An if statement runs a block of code only when a condition is true.11 Conditions use comparison operators: == (equal — note the double equals), != (not equal), and <, >, <=, >=.
age = 20
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")You are an adult.Python checks each condition top to bottom and runs the first one that's true, then skips the rest. elif (short for “else if”) handles extra cases; else catches everything left over and is optional.
Indentation is not decoration — it's the structure
Notice the lines under each if are pushed to the right. In most languages that spacing is cosmetic; in Python it is the actual grammar. The indented lines are “inside” the if; when the indentation stops, the block ends. The convention, from PEP 8, is four spaces per level.6
IndentationError. Pick four spaces and let your editor (IDLE, VS Code) handle it — pressing Tab in them inserts spaces for you.You can combine conditions with and, or, and not:
temperature = 22
if temperature > 15 and temperature < 28:
print("Pleasant weather.")09Doing things repeatedly: loops
Computers shine at repetition. A loop runs the same block of code many times.11 Python has two.
The for loop — do something for each item
A for loop walks through a collection of things one at a time:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}.")I like apple.
I like banana.
I like cherry.To repeat something a set number of times, pair for with the built-in range(), which produces a sequence of numbers. range(5) gives 0, 1, 2, 3, 4 — five numbers, starting at zero (counting from zero is a programming habit worth getting used to early):
for i in range(5):
print(f"Line number {i}")Line number 0
Line number 1
Line number 2
Line number 3
Line number 4The while loop — keep going until a condition changes
A while loop repeats as long as its condition stays true. It's the right tool when you don't know in advance how many times you'll loop:
count = 3
while count > 0:
print(count)
count = count - 1 # shrink toward the stopping point
print("Lift off!")3
2
1
Lift off!while loop whose condition never becomes false runs forever (an “infinite loop”). Always make sure something inside the loop moves you toward the exit — here, count shrinks each pass. If you ever get stuck in one, press Ctrl + C to stop it.10Collections: lists and dictionaries
So far each variable held one value. Real data comes in groups, and Python has excellent built-in ways to hold them.12
Lists — an ordered collection
A list holds items in order, inside square brackets. You can read, change, add, and remove items:
scores = [10, 25, 7]
print(scores[0]) # first item -> 10 (counting starts at 0)
print(scores[-1]) # last item -> 7
scores.append(99) # add to the end
print(scores) # -> [10, 25, 7, 99]
print(len(scores)) # how many items -> 4Lists and for loops are natural partners — a loop over a list lets you do something with every item, no matter how long the list is.
Dictionaries — labelled data
A dictionary stores pairs: a key (a label) and its value. Instead of remembering that position 2 holds the email, you just ask for the "email":12
person = {
"name": "Ada",
"age": 36,
"city": "London",
}
print(person["name"]) # -> Ada
person["age"] = 37 # change a value
person["email"] = "[email protected]" # add a new pair
print(person)Lists and dictionaries are the two containers you'll reach for most often. Python also has tuples (like lists, but unchangeable) and sets (collections with no duplicates) — worth knowing they exist, but lists and dictionaries will carry you a long way.12
11Functions: naming a set of steps
When you find yourself writing the same few lines again and again, wrap them in a function — a named, reusable block of steps.11 You've already been using functions (print, len, input); now you'll write your own with the def keyword.
def greet(name):
print(f"Hello, {name}!")
greet("Ada")
greet("Sam")Hello, Ada!
Hello, Sam!The word in brackets, name, is a parameter — a placeholder for whatever value you hand in when you call the function. Define the recipe once; use it as many times as you like.
Getting a result back with return
Functions can also compute a value and hand it back to you with return, so you can store or reuse the result:
def add(a, b):
return a + b
total = add(4, 5)
print(total) # -> 9The difference is worth pausing on: print shows a value on screen; return gives a value back to the code that called the function, to do more work with. Most functions you write will return something.
12When things go wrong: errors and try
Errors are normal — every programmer, at every level, sees them constantly. Python is unusually polite about them: when something breaks, it stops and prints a message (a “traceback”) telling you what went wrong and on which line.13 Read the last line first; it names the problem.
For example, asking int() to convert something that isn't a number fails:
int("hello") # ValueError: invalid literal for int() with base 10: 'hello'When you expect an error might happen — say, a user typing letters where you wanted a number — you can catch it with try and except, so your program responds gracefully instead of crashing:13
answer = input("Enter a number: ")
try:
number = int(answer)
print(f"Doubled, that's {number * 2}.")
except ValueError:
print("That wasn't a number — please try again.")Python tries the indented block; if a ValueError happens anywhere inside it, control jumps to the except block instead of crashing. Don't reach for this everywhere — but for user input, it's exactly right.
13Standing on giants: the standard library and pip
Python is famous for being “batteries included”: a large standard library ships with it, so many common jobs are already solved.14 You reach these tools with import. Here's the random module picking a number — which you'll use in the project next:
import random
roll = random.randint(1, 6) # a random whole number from 1 to 6
print(f"You rolled a {roll}.")When the standard library doesn't have what you need, the community has published hundreds of thousands of free packages on the Python Package Index (PyPI). You install them with a companion tool called pip, run from your system's terminal (not inside Python):15
pip install requestsYou don't need any of these extra packages for this tutorial — but knowing they exist explains how Python programs can do so much with so little of your own code.
14Build something: a number-guessing game
Time to combine everything — variables, input, conversion, a loop, an if, and the random module — into one small, complete program. Type it into a file, save it as guess.py, and run it.
import random
secret = random.randint(1, 20) # the number to guess
guesses = 0
print("I'm thinking of a number between 1 and 20.")
while True: # loop until we break out
answer = input("Your guess: ")
try:
guess = int(answer)
except ValueError:
print("Please type a whole number.")
continue # skip the rest, ask again
guesses = guesses + 1
if guess < secret:
print("Too low.")
elif guess > secret:
print("Too high.")
else:
print(f"Correct! You got it in {guesses} guesses.")
break # leave the loop — game overRead it slowly and you'll recognise every piece:
import randomandrandintpick the secret number (section 13).while True:loops forever until abreakstops it (section 9).try/exceptshrug off non-number input;continuejumps back to ask again (sections 9 and 12).if/elif/elsecompares the guess and gives a hint (section 8).- An f-string reports the winning count (section 5).
That's a genuine, interactive program — and you now understand every line of it. Change the range, add a guess limit, congratulate the player by name: tinkering with a working program is the fastest way to learn.
15Where to go next
You've covered the true fundamentals: running code, variables, text, numbers, input, decisions, loops, collections, functions, and errors. That's most of what any Python program is built from — everything else is more of the same, plus libraries.
- Practise more than you read. Programming is a skill like an instrument; understanding a chord isn't the same as playing one. Retype the examples, break them on purpose, and fix them.
- Work the official tutorial next. The Python Software Foundation's own tutorial is excellent, free, and goes one careful step past this guide.2 For a non-programmer's starting map, the Python Wiki's beginners' guide is a friendly hub.17
- Build tiny things you actually want. A tip calculator, a to-do list in the terminal, a script that renames your holiday photos. Motivation from a real goal beats any exercise sheet.
- Keep it readable. Python's own guiding philosophy, the “Zen of Python,” puts it plainly: readability counts.16 Write code your future self can understand.
Everyone who writes Python fluently was once exactly where you are now, staring at their first print("Hello, world!"). The distance from here to there is just practice — and you've already taken the first steps.