107 lessons

Python Tutorial for Beginners

Learn Python programming step by step, from your first print() to classes, testing and real projects, then choose an optional track in web development, data science, algorithms or machine learning.

Browse all 107 lessons by stage

Lessons
107
Code examples
249
Exercises
289
Quiz questions
289

Python course at a glance

Who it's for

Complete beginners, people who know another language, and anyone using Python for automation, data, web back ends or machine learning.

Prerequisites

None for the core course. The data science and machine learning tracks use school-level maths, explained as you go.

What you need

Python 3.12 or newer, a code editor such as VS Code and a terminal. Lessons and exercises also work here in the browser.

How long it takes

Two to four months for the core at five hours a week, then four to eight weeks per specialist track.

Python roadmap: beginner to advanced

Work through the core stages in order, because each one builds on the last, then choose the optional tracks that match your goals. Every lesson has worked examples, exercises and a quiz.

1

Beginner

Your first program, variables, numbers, strings, formatting, decisions, loops and lists: everything you need to write short, useful scripts.

  1. 1IntroductionWhat Python is, how to install it and how to write and run your first program.
  2. 2Syntax and StatementsHow Python reads your code: statements and expressions, colons and indentation, long lines, and syntax errors.
  3. 3CommentsWrite # comments, comment out code, document functions with docstrings and keep notes accurate as code changes.
  4. 4The print() FunctionDisplay values with print(), control separators and line endings with sep and end, and send output to files or other streams.
  5. 5Variables & Data TypesStore values in variables and work with strings, integers, floats and booleans.
  6. 6Naming and Multiple AssignmentChoose valid, readable names, assign several variables at once, unpack and swap values, and know when two names share one object.
Show all 19 lessonsShow fewer
  1. 7Numbers & MathDo calculations in Python with int and float, the arithmetic operators, rounding, and the math and random modules.
  2. 8Type CastingConvert values between types with int(), float(), str() and bool(), and know which conversions fail, truncate or surprise.
  3. 9The None ValueRepresent missing values with None, test for it with is None, and use it safely as a default and a return value.
  4. 10StringsWork with text in Python: indexing, slicing, string methods, searching and formatting output.
  5. 11String FormattingMake output look professional with f-string format specifiers for decimals, thousands separators, percentages, padding and aligned tables.
  6. 12User Input with input()Read keyboard input with input(), convert it safely, re-ask until it is valid and handle the end of input.
  7. 13Boolean Values and ExpressionsUse True and False, build conditions with comparisons, understand truthiness and see how and, or and not really evaluate.
  8. 14Operators and PrecedenceUse every kind of Python operator correctly and predict the order an expression is evaluated in.
  9. 15if / elif / elseMake decisions in your programs with comparisons, if, elif, else and logical operators.
  10. 16The match StatementUse match and case to branch on the value and shape of data, with guards, captures and a wildcard fallback.
  11. 17The pass StatementUse pass to keep an empty block valid, tell it apart from continue and break, and mark unfinished work clearly.
  12. 18Loops (for & while)Repeat code with for loops, while loops and range(), and control them with break and continue.
  13. 19ListsKeep many values in one variable, then read, change, add, remove and loop through them.
2

Intermediate

Dictionaries, sets, functions, comprehensions, errors, files, modules and dates: organise data and reuse code like a real programmer.

  1. 20DictionariesStore labelled data as key-value pairs, then read, update, loop through and nest dictionaries.
  2. 21Tuples & SetsUse tuples for fixed groups of values and sets for unique items, and learn when to choose each collection.
  3. 22range() in DepthMaster range(start, stop, step): boundaries, negative steps, empty ranges, slicing and why a range uses almost no memory.
  4. 23Arrays in PythonCompare lists, array.array and NumPy arrays, use type codes, and choose the right structure for your data.
  5. 24Advanced Collection MethodsUse the key methods of lists, tuples, sets and dictionaries, and know which ones change the collection and which return new values.
  6. 25Copying and Joining CollectionsTell aliasing, shallow copies and deep copies apart, and combine lists and dictionaries without unwanted side effects.
Show all 14 lessonsShow fewer
  1. 26FunctionsPackage code into reusable functions with def, parameters, default values and return.
  2. 27Arguments & ScopeWrite flexible functions with *args and **kwargs, unpack arguments, understand local and global scope, and avoid the mutable default trap.
  3. 28RecursionWrite recursive functions with a reachable base case, trace the call stack and decide when recursion or a loop fits better.
  4. 29Comprehensions & LambdaBuild new lists, dictionaries and sets in one readable line, and use small lambda functions with sorted, map and filter.
  5. 30Errors & ExceptionsCatch and handle exceptions with try, except, else and finally, and raise your own errors with clear messages.
  6. 31Files (Text, CSV, JSON)Read and write text files safely with open() and with, and work with CSV and JSON data.
  7. 32Modules, pip & venvReuse code with import, explore the standard library, write your own modules and install packages with pip in a virtual environment.
  8. 33Dates & TimesWork with dates and times using the datetime module: today's date, formatting with strftime, reading dates with strptime, timedelta arithmetic and time zones.
3

Advanced

Classes, dataclasses, generators, decorators, regex, testing and APIs: the skills that turn scripts into dependable programs.

  1. 34Classes & ObjectsModel real things with classes: attributes, the __init__ method, instance methods, self, class attributes and __str__.
  2. 35InheritanceBuild new classes from existing ones with inheritance, override methods, call super() and use polymorphism.
  3. 36Python Magic MethodsMake your classes work with print(), ==, <, len() and + by defining the right special methods.
  4. 37Class Methods and PropertiesChoose between instance, class and static methods, write alternative constructors and validate attributes with @property.
  5. 38Polymorphism and Inner ClassesWrite code that works with any object offering the right methods, prefer composition where it fits, and use nested classes properly.
  6. 39Type Hints & DataclassesMake code clearer and catch bugs earlier with type hints, then write data-holding classes in a few lines with @dataclass.
Show all 13 lessonsShow fewer
  1. 40Iterators & GeneratorsUnderstand how for loops really work, write generator functions with yield, use generator expressions and process large data one item at a time.
  2. 41Iterators vs. IterablesDistinguish iterables from iterators, use iter() and next() directly, handle exhaustion and build a custom iterator.
  3. 42Context ManagersUnderstand the with statement, write context managers as classes or with @contextmanager, and guarantee clean-up even after errors.
  4. 43DecoratorsAdd behaviour to functions without changing their code, using decorators, wrapper functions, functools.wraps and decorators that take arguments.
  5. 44Regular ExpressionsFind and change patterns in text with the re module: character classes, quantifiers, groups, findall, sub and validating input.
  6. 45TestingCheck your code automatically with unit tests: assert, pytest, testing for exceptions, fixtures, parametrised tests and unittest.
  7. 46Web APIs & requestsFetch and send data over the internet with the requests library: GET and POST, JSON responses, query parameters, status codes, headers, API keys and error handling.
4

Files and Standard Library

Extend the foundation with focused file, JSON, CSV, configuration, packaging and reference lessons. Read the existing files and modules lessons first.

  1. 47Read, Write, Create and Delete FilesCreate, read, write, append and delete files safely, choosing the right open() mode and encoding.
  2. 48JSON HandlingConvert between JSON and Python with the json module, write readable files and validate what you parse.
  3. 49CSV Handling in DepthRead and write CSV files correctly with csv.reader, DictReader and DictWriter, including quoting, encodings and type conversion.
  4. 50File and Directory OperationsBuild paths, create folders, list and search files, and move or delete them safely with pathlib and shutil.
  5. 51Built-in Functions ReferenceUse Python's most important built-in functions for inspecting values, summarising data, transforming sequences and building collections.
  6. 52String and Collection Methods ReferenceLook up the most-used methods of str, list, dict, tuple and set, with their return values and mutation behaviour.
Show all 11 lessonsShow fewer
  1. 53Exception Types ReferenceRecognise Python's common built-in exceptions, understand what causes each and catch the right one in the right place.
  2. 54Python Keywords and GlossaryKnow Python's reserved and soft keywords, and use core programming vocabulary precisely.
  3. 55Standard Library EssentialsUse the most useful standard library modules for system access, paths, counting and grouping, and quick statistics.
  4. 56Environment Variables and ConfigurationRead settings from environment variables, convert and validate them at startup, and keep secrets out of code and logs.
  5. 57pip and Virtual EnvironmentsIsolate each project's packages with venv, install with python -m pip, and record dependencies so others can reproduce your setup.
5

Professional Development

Build dependable projects with debugging, logging, pytest, fixtures, style, type checking, dependencies and Git.

  1. 58Debugging Python ProgramsFind and fix bugs systematically: reproduce them, read tracebacks, inspect state with breakpoint() and pdb, and confirm the cause before changing code.
  2. 59LoggingReplace print statements with the logging module: choose levels, name loggers, format output, record exceptions and protect private data.
  3. 60Unit Testing and pytestDesign focused unit tests, make sure pytest discovers them, cover boundaries with parametrize and check exceptions precisely.
  4. 61Mocking and Test FixturesGive tests fresh, controlled dependencies with fixtures, and replace slow or external services with mocks patched in the right place.
  5. 62Code Style and PEP 8Write Python that looks like Python: PEP 8 naming, layout and imports, and the tools that apply them automatically.
  6. 63Type Checking and Type HintingRun a static type checker, narrow optional values, describe collections and structural interfaces, and read type errors.
Show all 9 lessonsShow fewer
  1. 64Virtual Environments and DependenciesDeclare dependencies in pyproject.toml, choose sensible version ranges, lock exact versions and keep development tools separate.
  2. 65Git and Python ProjectsSet up a Python project in Git with the right ignore rules, a clear folder layout, focused commits and a tested branch workflow.
  3. 66Interview Questions and AnswersAnswer common Python interview questions with explanations and small code demonstrations, and approach coding problems methodically.
8

DSA Track

Optional specialization after functions: complexity, search, sorting, stacks, queues, linked lists, trees and graphs.

  1. 81Time and Space ComplexityDescribe how running time and memory grow with input size, recognise common complexity classes and pick data structures accordingly.
  2. 82Linear and Binary SearchImplement linear and binary search, keep binary search's interval correct, and use the bisect module for sorted data.
  3. 83Sorting AlgorithmsSort by the right key, rely on stability for ties, understand insertion and merge sort, and use Python's built-in sorting in real code.
  4. 84Stacks and QueuesImplement stacks with lists and queues with deque, handle empty structures and choose queue.Queue for work shared between threads.
  5. 85Linked ListsBuild a singly linked list from nodes, traverse it, insert and delete safely, and understand when linked lists help and when they don't.
  6. 86Hash TablesUnderstand the hash table behind dict and set: hashing, collisions, why keys must be hashable and what O(1) average really means.
Show all 9 lessonsShow fewer
  1. 87Trees and Binary Search TreesModel hierarchies as trees, implement a binary search tree with insert and search, traverse it three ways and see why balance matters.
  2. 88Graphs and Graph TraversalRepresent graphs with adjacency lists and explore them with breadth-first and depth-first search, handling cycles and disconnected vertices.
  3. 89Recursive Problem SolvingDecompose problems into choices and smaller subproblems, explore options with backtracking, speed up repeats with memoization and estimate growth.
9

Machine Learning Track

Separate advanced route after data science: distributions, regression, classification, held out data, evaluation and clustering.

  1. 90Introduction to Machine LearningFrame a prediction problem, choose features and a target, compare a model against a simple baseline and evaluate it on data it hasn't seen.
  2. 91Mean, Median, Mode and DeviationUse mean, median, mode and standard deviation to describe ML features, build baselines and standardise inputs without leaking test data.
  3. 92Data Distribution and PercentilesDescribe the shape of numeric data with percentiles and quartiles, choose a percentile method deliberately, investigate outliers and watch for drift.
  4. 93Linear and Multiple RegressionFit simple and multiple linear regression models, read their coefficients and residuals, evaluate them on held-out data and know their limits.
  5. 94Logistic RegressionClassify outcomes with logistic regression, read predicted probabilities, choose a decision threshold and evaluate with metrics for both classes.
  6. 95Decision Trees and K-Nearest NeighborsTrain decision trees and k-nearest neighbours, tune depth and neighbour count on validation data, scale features for KNN and compare the two models.
Show all 9 lessonsShow fewer
  1. 96Training and Testing DatasetsDivide data into training, validation and test sets, pick a split strategy that matches how the data was produced, and keep preprocessing leak-free.
  2. 97Cross-Validation and EvaluationEstimate model performance reliably with k-fold cross-validation, the right splitter for your data, meaningful metrics and leak-free pipelines.
  3. 98Clustering and K-MeansGroup unlabelled data with k-means, scale features first, compare cluster counts and describe clusters in their original units.
10

Practice and Projects

Return throughout your studies for extra examples, graded practice problems, chapter quizzes, projects and a study plan.

  1. 99Python Examples LibraryA library of short, explained Python programs covering everyday tasks, with guidance on tracing, varying and combining examples.
  2. 100Python Coding ChallengesSolve classic Python coding challenges by stating the contract, writing tests first, building a working solution and explaining its invariant and cost.
  3. 101Python Practice ProblemsWork through focused Python practice problems with step-by-step reasoning, and use prediction, delayed solutions and transfer to make practice stick.
  4. 102Python Exercises by DifficultyChoose Python exercises at the right level, from short beginner tasks to design-focused advanced work, and use feedback to move up.
  5. 103Python Quizzes by ChapterCheck your Python knowledge chapter by chapter, choose the right quiz settings, analyse mistakes and turn results into a revision plan.
  6. 104Beginner Python ProjectsBuild small, complete Python projects from variables, conditions, loops and functions, delivering one working behaviour at a time.
Show all 9 lessonsShow fewer
  1. 105Intermediate Python ProjectsBuild multi-file Python projects that separate parsing, logic and output, store data safely, test with temporary files and run from a clean checkout.
  2. 106Advanced Python ProjectsPlan advanced Python projects around clear interfaces, reliable behaviour, measured performance and complete delivery, not just more code.
  3. 107Study Plan and Learning RoadmapFollow a realistic Python study plan through the core course, professional skills and one specialist track, with projects as evidence of progress.

What is Python?

Python is a programming language known for code that reads almost like English. It's used to automate boring tasks, analyse data, build websites and APIs, train machine learning models and teach programming in schools and universities around the world.

Python is a great first language because you can do useful things with very little code. There are no curly braces or semicolons to remember. Instead, Python uses indentation, the spaces at the start of a line, to show which lines belong together. That one rule makes Python programs tidy by default.

How the course is organised

The course has a shared core and optional specialist tracks:

  • Beginner: your first program, variables, numbers, strings and formatting, input, decisions with if, loops and lists.
  • Intermediate: dictionaries, tuples and sets, functions and their arguments, comprehensions, error handling, files, modules and dates.
  • Advanced: classes and inheritance, magic methods, type hints and dataclasses, generators, decorators, context managers, regular expressions, testing and web APIs.
  • Files and standard library: JSON, CSV, configuration, pip and virtual environments, and reference lessons for built-in functions and keywords.
  • Professional development: debugging, logging, pytest, mocking, PEP 8 style, type checking, dependency management and Git.

After the core, choose the track that matches your goal. The database and web track covers SQL from Python, MySQL, MongoDB, HTTP, authentication and Flask. The data science track covers NumPy, pandas, data cleaning, statistics and Matplotlib. The data structures and algorithms track covers complexity, searching, sorting, stacks, queues, linked lists, trees and graphs. Machine learning builds on data science with regression, classification, evaluation and clustering.

How to follow this course

Read the core stages in order, because each lesson builds on the ones before it. Every lesson explains the idea with examples and their output, shows common mistakes, and ends with exercises, a quiz and frequently asked questions. Type the examples yourself and change them: predicting what a small change will do is the fastest way to learn.

Check your progress with the Python exercises, the course quiz and the chapter quizzes as you finish each stage. Build a beginner project once functions make sense, an intermediate project after files and testing, and an advanced project after a specialist track. The Python study roadmap suggests a weekly plan and shows how long each stage usually takes.

Learning and career routes

For automation, combine files, CSV, configuration, logging and testing. For backend work, add databases, HTTP and Flask, then build a small booking service. For data work, combine pandas, cleaning, statistics and charts. The learning paths connect these routes to portfolio projects, and SQL is the natural companion for both backend and data roles.

Keep the Python cheat sheet and the keywords and glossary lesson open while you practise. Completing lessons builds knowledge; finished projects, explained design choices and tests are what show employers and teachers that you can use it.

What you will learn

10 practical skills, built one lesson at a time

  • Install Python and run programs from a file or the interactive shell
  • Calculate with numbers and format output neatly with f-strings
  • Make decisions with if, elif and else, and repeat work with loops
  • Choose between lists, dictionaries, tuples and sets for your data
  • Write reusable functions with defaults, args and *kwargs
  • Handle errors, and read and write text, CSV and JSON files
  • Work with dates and times using datetime
  • Model real things with classes, inheritance and dataclasses
  • Use generators, decorators and regular expressions
  • Test your code with pytest and fetch data from web APIs
107 lessons249 examples289 exercises

Practise Python your way

Learning sticks when you use it. Pick a mode.

Python FAQ

Is Python good for complete beginners?

Yes. Python's short, readable syntax lets you focus on how to think like a programmer instead of fighting punctuation. Many universities use it as the first language in their computer science courses.

What can I build with Python?

Small scripts that rename files or tidy spreadsheets, data reports and charts, web back ends with frameworks like Django and Flask, games, bots and machine learning projects. It's one of the most widely used languages in the world.

Do I need to install anything to learn Python?

To run code on your own computer you install Python from python.org, which takes a few minutes. The first lesson shows you how, and how to check it worked. You can read every lesson and do the exercises here without installing anything.

How long does it take to learn Python?

With about five hours a week, most beginners finish the beginner stage in three to four weeks and the core stages in two to four months; a specialist track adds another four to eight weeks. Becoming fluent comes from building small projects of your own, such as a quiz game, a budget tracker or a script that tidies your downloads folder.

Should I learn Python or JavaScript first?

If you want to build websites, start with HTML, then CSS and JavaScript. If you're more interested in data, automation or general programming, start with Python. The core ideas, such as variables, loops and functions, transfer between them.

Is this Python course free?

Yes. Every lesson, exercise, quiz and cheat sheet is free to use, with no account or sign-up needed.

Which Python version does the course use?

The lessons use Python 3.12 or newer, and almost everything also works on Python 3.10 and 3.11. Python 2 is no longer supported and isn't covered. The introduction shows how to check which version you have.

Do I need to finish every track?

No. Complete the core stages, then choose one track that matches your goal: web and databases, data science, algorithms, or machine learning after data science. The study roadmap helps you decide.

Can I get a job with Python after this course?

The course gives you the knowledge employers expect for junior roles, but a job also needs evidence: two or three finished projects in a public repository, with tests and a README. The interview questions lesson helps you prepare for technical interviews.

More tutorials