Quick Python Tutorial: Learn the Basics Fast
Learn Python basics quickly with one runnable path through syntax, collections, control flow, functions, errors, files, and an expense script.
Quick Python means learning enough Python 3 to read, change, and write a small working script. This tutorial progressively builds an expense summary, revising the same script to add input, validation, collections, loops, and functions.
The short version: Learn Python quickly by running small examples in order, then combine variables, collections, control flow, functions, and error handling in one complete command-line program.
What “Quick Python” Means
A quick Python tutorial gives you working literacy, not mastery. By the end, you should be able to recognize common syntax, follow the flow of a short program, change its behavior, and write a small script without copying every line from somewhere else.
That scope matters. Python includes far more than one tutorial can teach well. Classes, decorators, asynchronous programming, frameworks, and specialist libraries belong later. They make more sense after variables, collections, conditions, loops, and functions feel familiar.
“Quick Python” can also refer to packages, specialized quick starts, or books with similar names. This page teaches the Python language itself. It is not documentation for a package called QuickPython, a guide to a specialist Python tool, or a substitute for a full programming curriculum.
If you already know another language, this lesson can act as a syntax refresh. If programming is new, work through each example and change one detail before moving on. The longer Python learning roadmap explains what to study after this first pass.
Run Your First Python Program
First, open a terminal and check whether a Python 3 interpreter is available:
python --version
Depending on the installation, the command may instead be:
python3 --version
or:
py --version
Use whichever command reports Python 3.10 or newer. In the examples below, replace PYTHON with that command.
The interactive interpreter, also called a REPL, runs one statement at a time. Start it by entering your Python command without a filename:
PYTHON
At the >>> prompt, try:
print("Hello, Python")
2 + 3
The interpreter displays:
Hello, Python
5
This is useful for experiments. The Python REPL guide covers multiline input, history, and productive ways to test an idea before placing it in a script.
A script is a text file containing Python statements. In the example below, a nonempty string is truthy, so if name runs its indented block. The f prefix creates an f-string, and {name} inserts the variable’s value. Create a file named hello.py:
name = "Mina"
if name:
print(f"Hello, {name}")
Run it from the directory containing the file:
PYTHON hello.py
The result is:
Hello, Mina
Python uses indentation to define a block. The indented print belongs to the if statement. Keep indentation consistent, normally with four spaces. Removing the indentation changes the structure, and inconsistent indentation can stop the script from running.
Comments begin with # and continue to the end of the physical line unless the character appears inside a string:
# This is a comment.
message = "A # inside a string is text."
Indentation is part of Python syntax. It tells Python which statements belong inside a condition, loop, or function.
Values, Variables, and Collections
A value is a piece of data, such as 42, 3.5, or "lunch". A variable is a name that refers to a value. A type describes what kind of value it is and which operations it supports.
expense_name = "Train ticket" # str
amount = 18.50 # float
quantity = 2 # int
reimbursable = True # bool
Python has several collection types for keeping related values together:
| Type | Example | Ordered | Can its contents change? | Typical use |
|---|---|---|---|---|
list | ["food", "travel"] | Yes | Yes | A sequence that grows or changes |
tuple | (51.5, -0.1) | Yes | No—its slots are fixed, although stored objects may be mutable | A fixed group of values |
set | {"food", "travel"} | No positional indexing | Yes | Unique values |
dict | {"name": "Lunch", "amount": 12.5} | Yes—in insertion order | Yes | Named fields and lookup tables |
A mutable object can be changed after creation. Lists, sets, and dictionaries are mutable. Strings are immutable. A tuple’s slots cannot be added, removed, or reassigned, although an object stored in a tuple may itself be mutable.
categories = ["food", "travel"]
categories.append("supplies")
expense = {
"name": "Notebook",
"category": "supplies",
"amount": 6.75,
}
expense["amount"] = 7.25
print(categories)
print(expense["name"])
['food', 'travel', 'supplies']
Notebook
Indexing selects one item by position. Python starts counting positions at zero. Slicing selects a range and excludes the stop position:
names = ["Lunch", "Train", "Notebook", "Coffee"]
print(names[0])
print(names[1:3])
Lunch
['Train', 'Notebook']
The same excluded endpoint appears in range(), which you will use with loops.
Strings support indexing and slicing, but they cannot be changed at a position:
label = "travel"
short_label = label[:3]
print(short_label)
tra
Numbers have separate division operators. / returns a floating-point result, // performs floor division, and % returns the remainder:
print(7 / 2)
print(7 // 2)
print(7 % 2)
3.5
3
1
Common Python collection mistakes
- Indexing starts at
0, so the first list item isitems[0]. - A slice such as
items[1:3]includes positions1and2, not position3. - Assigning one list variable to another does not automatically make a separate copy.
- Sets do not provide list-style positional indexing.
- Dictionary keys and list indexes solve different problems. Use a key such as
expense["amount"]for a named field.
The common Python mistakes guide covers these traps and the errors they tend to produce.
Make Decisions, Repeat Work, and Use Functions
Control flow is the order in which a program chooses and runs statements. Conditions choose a branch, loops repeat work, and functions package operations under a name.
Use if, elif, and else to select one branch:
amount = 48.0
if amount <= 0:
print("Amount must be positive.")
elif amount >= 40:
print("Large expense")
else:
print("Regular expense")
Large expense
A for loop takes items from an iterable, which is an object Python can visit one item at a time. Lists, strings, dictionaries, and ranges are common iterables.
expense_names = ["Lunch", "Train", "Notebook"]
for name in expense_names:
print(name)
Lunch
Train
Notebook
range(3) produces 0, 1, and 2. Its stop value is excluded:
for number in range(3):
print(number)
0
1
2
A while loop continues while its condition is true. break exits the nearest loop. input() returns text, and .strip() removes whitespace from both ends of that text. The final expense program uses these features so that a blank expense name can finish data entry:
while True:
name = input("Expense name, or press Enter to finish: ").strip()
if name == "":
break
A function is a named block of reusable code. A parameter is a name in the function definition. An argument is the value supplied during a call. A return value is the result sent back to the caller.
This small function shows the basic shape:
def add_amount(total, amount):
return total + amount
Here, total and amount are parameters. When the program calls add_amount(10, 5), 10 and 5 are arguments. The return value is 15. The expense project below adds functions only after building its records and input loop.
An f-string begins with f or F and places expressions inside braces. Format a number with two decimal places like this:
amount = 12.5
print(f"Amount: ${amount:.2f}")
Amount: $12.50
input() returns a string. Convert numeric input with float() or int() before doing arithmetic, and handle conversion failures instead of assuming the user typed a number. This introductory project uses float as a teaching simplification; real monetary software should use decimal values or integer minor units to avoid binary floating-point rounding errors.
Common Python control-flow mistakes
- The stop value of
range()is excluded. - Ordinary statements following
returnin the same suite are unreachable, although cleanup in an enclosingfinallyblock still runs before the function returns. breakexits a loop; it does not end the whole program unless no later statements remain.- An f-string needs the
fprefix. Without it, braces remain ordinary text. - A local variable inside a function is different from an unrelated variable outside it. The Python scope guide explains when names are local or global.
Build a Small Expense Summary
Build expenses.py in revisions, running it after each step. Start with one dictionary and a mutable list:
expenses = []
expense = {"name": "Lunch", "category": "food", "amount": 12.50}
expenses.append(expense)
print(expenses)
Next, replace the fixed record with an input loop. A try block contains conversion that may fail; the matching except ValueError block handles invalid numeric text. continue skips the rest of the current loop iteration. math.isfinite() rejects nan and infinities, which float() accepts but which must not enter the totals:
import math
expenses = []
while True:
name = input("Expense name, or press Enter to finish: ").strip()
if name == "":
break
category = input("Category: ").strip()
if category == "":
print("Category cannot be empty.")
continue
try:
amount = float(input("Amount: ").strip())
except ValueError:
print("Amount must be a number.")
continue
if not math.isfinite(amount) or amount <= 0:
print("Amount must be a finite number greater than zero.")
continue
expenses.append({"name": name, "category": category, "amount": amount})
Then move collection into collect_expenses() and add calculate_totals(). The expression totals.get(category, 0.0) retrieves an existing total or supplies 0.0 when the key is absent:
def calculate_totals(expenses):
totals = {}
for expense in expenses:
category = expense["category"]
amount = expense["amount"]
totals[category] = totals.get(category, 0.0) + amount
return totals
The finished revision adds the summary. if not expenses detects an empty list. totals.items() produces key-value pairs for dictionary iteration, while totals.values() produces the values that sum() adds. The if __name__ == "__main__" guard calls main() when this file is run directly, but not when it is imported.
The features connect to the finished script like this:
flowchart LR
A["input(): text"] --> B[".strip() and float(): cleanup and conversion"]
B --> C["try/except, conditions, math.isfinite(): validation"]
C --> D["dict: one expense record"]
D --> E["mutable list: all records"]
E --> F["loops and functions: process records"]
F --> G["dict.get(): category totals"]
G --> H["sum(values): grand total"]
Save the finished revision below as expenses.py.
import math
def collect_expenses():
expenses = []
while True:
name = input("Expense name, or press Enter to finish: ").strip()
if name == "":
break
category = input("Category: ").strip()
if category == "":
print("Category cannot be empty.")
continue
amount_text = input("Amount: ").strip()
try:
amount = float(amount_text)
except ValueError:
print("Amount must be a number.")
continue
if not math.isfinite(amount) or amount <= 0:
print("Amount must be a finite number greater than zero.")
continue
expense = {
"name": name,
"category": category,
"amount": amount,
}
expenses.append(expense)
return expenses
def calculate_totals(expenses):
totals = {}
for expense in expenses:
category = expense["category"]
amount = expense["amount"]
totals[category] = totals.get(category, 0.0) + amount
return totals
def print_summary(expenses, totals):
if not expenses:
print("No expenses entered.")
return
print("\nExpenses:")
for expense in expenses:
print(
f"- {expense['name']} "
f"({expense['category']}): ${expense['amount']:.2f}"
)
print("\nCategory totals:")
for category, total in totals.items():
print(f"- {category}: ${total:.2f}")
grand_total = sum(totals.values())
print(f"\nGrand total: ${grand_total:.2f}")
def main():
expenses = collect_expenses()
totals = calculate_totals(expenses)
print_summary(expenses, totals)
if __name__ == "__main__":
main()
Run it with:
PYTHON expenses.py
A session can look like this:
Expense name, or press Enter to finish: Lunch
Category: food
Amount: 12.50
Expense name, or press Enter to finish: Train
Category: travel
Amount: 18
Expense name, or press Enter to finish: Coffee
Category: food
Amount: 3.25
Expense name, or press Enter to finish:
Expenses:
- Lunch (food): $12.50
- Train (travel): $18.00
- Coffee (food): $3.25
Category totals:
- food: $15.75
- travel: $18.00
Grand total: $33.75
Try the invalid cases too. Enter letters, nan, or inf for the amount, leave the category blank, or enter 0. The program should explain the problem, skip that record, and continue accepting expenses.
This project now uses the core pieces from the tutorial in one place:
- Strings from terminal input
- A float converted from input text
- Dictionaries for named expense fields
- A mutable list for collected records
- Conditions for validation
whileandforloops- Functions, parameters, arguments, and return values
- F-strings for readable output
- A targeted
ValueErrorhandler
Handle Errors, Files, and Packages
An exception is a signal that interrupts normal control flow, usually because an error or exceptional condition occurred. The expense program handles ValueError, the specific exception raised when float() cannot convert the supplied text. Avoid a bare except, because it can hide errors the program does not know how to recover from.
A module is a unit Python can load through the import system, commonly—but not always—implemented as a .py file. You can move reusable functions into another module and import them:
from expense_tools import calculate_totals
An import package is a special kind of module that can contain submodules. A separately installable distribution package may provide zero, one, or several import packages, sometimes under different names. Python also includes a standard library, so many useful modules are available without installing an outside dependency.
Files need their own error handling. This standalone example reads a text file and reports a missing file:
try:
with open("expense-notes.txt", encoding="utf-8") as file:
notes = file.read()
print(notes)
except FileNotFoundError:
print("No expense notes file was found.")
Using with closes the file after the block finishes, including when an exception occurs. When writing files, choose the mode deliberately because opening a file in write mode can replace its existing contents.
A virtual environment is an isolated environment for a project’s Python packages. It lets separate projects keep different package versions without one project’s upgrade changing the other project’s environment. Create one with the standard venv module:
PYTHON -m venv .venv
Activation commands vary by shell and operating system, so use the instructions for the environment where the project runs. You do not need an outside package for this expense program.
Your Next Python Step
Complete beginners should reinforce this lesson with small variations. Add a date field, reject excessively short names, or save the formatted summary to a text file. Each change makes you reuse syntax in a real context.
Experienced programmers refreshing Python can move to modules, testing, type hints, and a project in the domain where they plan to use the language. The official Python tutorial is written for programmers who are new to Python and already understand basic programming. The Python language reference is useful when exact language behavior matters.
Where the books fit
For a compact continuation, Python in Three Days fits a short deadline and keeps the path focused. Python in One Month gives a complete beginner more repetition, while Python in Three Months suits someone building toward job-ready depth. Keep the expense script nearby and extend it as each new Python feature earns a place.
Frequently asked questions
What is the quickest way to learn basic Python?
Learn enough syntax to build one small program, then modify it. Start with values, variables, collections, conditions, loops, functions, input, and error handling instead of trying to memorize the whole language.
Can I learn Python in one day?
Experienced programmers may complete this introductory pass faster than complete beginners. A complete beginner can still run programs and write small scripts, but fluency and job readiness require repeated practice.
Should I use python, python3, or py to run Python?
The command depends on how Python was installed and configured. Try python first, then python3 on systems that use that name or py where the Python launcher is available.
Why does Python indentation matter?
Python uses indentation to group statements into blocks. Lines inside a condition, loop, or function must be indented consistently or the program can fail or behave differently than intended.
What should I learn after Python basics?
Complete beginners should reinforce the basics with several small scripts. Experienced programmers can move to modules, testing, type hints, and a project in the domain where they plan to use Python.