W3docs

Python HOME

A complete beginner's guide to Python: what it is, why it matters, how to install it, and your first working programs with clear examples.

Python is a high-level, general-purpose programming language renowned for its readable syntax and broad applicability — from web servers and data pipelines to machine-learning models and automation scripts. This tutorial covers everything you need to go from zero to writing real Python programs.

What Is Python?

Python was created by Guido van Rossum and first released in 1991. It is:

  • Interpreted — code runs line by line; no separate compile step needed.
  • Dynamically typed — variable types are inferred at runtime, not declared up front.
  • Multi-paradigm — supports procedural, object-oriented, and functional styles.
  • Cross-platform — the same script runs on Windows, macOS, and Linux without changes.

Python consistently ranks as one of the most widely used programming languages in annual developer surveys, partly because its syntax resembles plain English, making programs easier to read and maintain than in many other languages.

Why Learn Python?

Python is a good first language because the gap between "what you think" and "what you type" is small. Consider printing a message:

print("Hello, World!")

That is the entire program — no imports, no class boilerplate, no semicolons.

Beyond simplicity, Python is genuinely used in production:

DomainCommon libraries
Web developmentDjango, Flask, FastAPI
Data analysisPandas, NumPy
Machine learningscikit-learn, TensorFlow, PyTorch
Automation / scriptingstandard library (os, pathlib, subprocess)
Scientific computingSciPy, Matplotlib

Learning Python opens doors across all of these areas with a single language.

Installing Python

Python is available at python.org. Download the installer for your operating system and follow the prompts. Enable the "Add Python to PATH" option on Windows so you can run Python from any terminal.

Verify the installation:

python3 --version
# Python 3.12.x  (version number will vary)

On Windows the command may be python instead of python3.

Your First Python Program

Open any plain-text editor (or an IDE like VS Code), create a file named hello.py, and add:

print("Hello, World!")

Run it from your terminal:

python3 hello.py
# Hello, World!

The Interactive Shell (REPL)

Python also ships with an interactive shell — the REPL (Read-Eval-Print Loop). Type python3 in your terminal and you get a prompt (>>>) where you can execute code immediately:

>>> 2 + 2
4
>>> name = "Alice"
>>> print(f"Hello, {name}!")
Hello, Alice!

The REPL is useful for quick experiments; scripts (.py files) are better for anything you want to save or repeat.

Python Syntax Basics

Python uses indentation (spaces or tabs, consistently) to define code blocks instead of curly braces {}. This is one of its most distinctive features.

age = 20

if age >= 18:
    print("Adult")      # indented → inside the if block
else:
    print("Minor")      # indented → inside the else block

print("Done")           # not indented → outside the if/else

Getting indentation wrong raises an IndentationError, so editors that show whitespace are helpful when starting out.

See Python Syntax for a full reference.

Variables and Data Types

A variable is a name that holds a value. In Python you create one by assigning to it — no declaration keyword needed:

x = 10          # integer
pi = 3.14159    # float
greeting = "Hi" # string
active = True   # boolean
nothing = None  # absence of a value

Python's core built-in types include:

TypeExampleDescription
int42Whole numbers
float3.14Decimal numbers
str"hello"Text
boolTrue / FalseLogic
list[1, 2, 3]Ordered, mutable sequence
tuple(1, 2, 3)Ordered, immutable sequence
dict{"a": 1}Key-value pairs
set{1, 2, 3}Unordered, unique values

You can check a value's type with type():

print(type(42))       # <class 'int'>
print(type("hello"))  # <class 'str'>
print(type([1, 2]))   # <class 'list'>

See Data Types and Variables for details.

Control Flow

if / elif / else

score = 75

if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "F"

print(grade)  # B

for Loops

for iterates over any sequence — a list, a string, a range, or any iterable:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)
# apple
# banana
# cherry

for i in range(3):   # range(3) produces 0, 1, 2
    print(i)
# 0
# 1
# 2

while Loops

count = 0
while count < 3:
    print(count)
    count += 1
# 0
# 1
# 2

See if / else and for loops for full coverage.

Functions

A function bundles reusable logic under a name. Define it with def, call it by name:

def add(a, b):
    return a + b

result = add(3, 5)
print(result)  # 8

Functions can have default parameter values so callers can omit optional arguments:

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Alice"))            # Hello, Alice!
print(greet("Bob", "Hi"))        # Hi, Bob!

See Python Functions for parameters, return values, and scope.

Working with Strings

Strings support a rich set of operations:

s = "python programming"

print(s.upper())          # PYTHON PROGRAMMING
print(s.title())          # Python Programming
print(s.replace("python", "great"))  # great programming
print(len(s))             # 18
print(s[0:6])             # python  (slicing)

f-strings (formatted string literals, Python 3.6+) are the modern way to embed expressions in text:

language = "Python"
version = 3.12
print(f"Learning {language} {version}")  # Learning Python 3.12

See Python Strings and Format Strings for more.

Lists — the Workhorse Collection

A list holds an ordered, changeable sequence of items:

colors = ["red", "green", "blue"]

colors.append("yellow")   # add to end
print(colors)             # ['red', 'green', 'blue', 'yellow']

colors.remove("green")
print(colors)             # ['red', 'blue', 'yellow']

print(colors[1])          # blue  (zero-indexed)
print(len(colors))        # 3

See Python Lists for slicing, sorting, and list comprehensions.

Modules and the Standard Library

A module is a Python file you import to reuse its code. Python ships with a large standard library — modules for math, file I/O, dates, networking, and more — so many tasks need no third-party packages at all.

import math
import random

print(math.sqrt(16))          # 4.0
print(math.pi)                # 3.141592653589793
print(random.randint(1, 6))   # random integer between 1 and 6

Install third-party packages with pip:

pip install requests

Then import them the same way:

import requests

response = requests.get("https://httpbin.org/get")
print(response.status_code)  # 200

Error Handling

Python signals problems by raising exceptions. Use try / except to handle them gracefully instead of crashing:

try:
    number = int("abc")   # this raises ValueError
except ValueError:
    print("That is not a valid number.")

# That is not a valid number.

A bare except catches everything — avoid it. Always name the specific exception type so unexpected errors still surface.

See Python try / except for else, finally, and custom exceptions.

Next Steps

This page introduced the fundamentals. The rest of this tutorial goes deeper on each topic:

Practice

Practice
Which of the following are characteristics of Python?
Which of the following are characteristics of Python?
Was this page helpful?