Complete Python Tutorial | In-Depth English Guide for Beginners
Python Foundations · Beginner Course
Complete Python Programming Guide
From your first print() to building real programs — this guide takes absolute beginners through every core concept with clear explanations, copyable code, and practical context for data science, web development, and automation.
14 topics
Zero experience
Copyable code
Real-world tips
01 Introduction
Why Learn Python?
Python is one of the most popular programming languages in the world — not because it is trendy, but because it is readable, versatile, and powerful. A single language can take you from automating boring spreadsheet tasks to training machine learning models, building websites, or analyzing millions of data points.
Web development — Django and Flask power sites from startups to Instagram-scale backends.
Data science & AI — NumPy, pandas, PyTorch, and TensorFlow are all Python-first.
Education — Clean syntax lets you focus on logic, not semicolons and braces.
Your learning path in this guide — each section unlocks the next
What makes Python special
Python uses indentation instead of curly braces to define blocks. It is dynamically typed — you don't declare variable types. And it has a massive standard library plus over 500,000 third-party packages on PyPI. You write less boilerplate and ship ideas faster.
02 Getting started
Setup & Your First Program
Before writing code, install Python from python.org (version 3.11 or newer is recommended). During installation on Windows, check "Add Python to PATH". On macOS/Linux, Python 3 is often pre-installed — verify with python3 --version.
Three ways to run Python
Method
When to use
Interactive shell (REPL)
Quick experiments — type python in terminal
Script file (.py)
Real programs — save and run with python myfile.py
IDE / editor
VS Code, PyCharm — syntax highlighting, debugging, extensions
# hello.py — your first Python program print("Hello, World!") print("Python version:", __import__("sys").version.split()[0]) # Running in terminal: # python hello.py
REPL quick test
Open a terminal, type python, then try: 2 + 2 → 4. Type exit() to leave. The REPL is perfect for testing one-liners before putting them in a file.
03 Core concepts
Variables & Data Types
A variable is a name attached to a value in memory. Python infers the type automatically — you never write int age = 30 like in C or Java.
name = "Alice Johnson" # str — text age = 30 # int — whole number salary = 5200.75 # float — decimal is_employed = True # bool — True or False print("Name:", name) print("Age:", age) print(type(name)) # <class 'str'> print(type(age)) # <class 'int'> # Multiple assignment in one line x, y, z = 10, 20.5, "Python" print(x, y, z) # Type conversion score_str = "95" score_int = int(score_str) # "95" → 95 price = float("19.99") # "19.99" → 19.99
Naming rules
Use snake_case: user_name, not userName or UserName.
Names are case-sensitive: count and Count are different variables.
Cannot start with a digit or use reserved words like class, for, return.
Choose descriptive names — total_price beats tp.
Deep dive
Python variables are references to objects, not boxes that hold values. When you write a = [1, 2, 3] and b = a, both names point to the same list — changing b affects a. For independent copies of mutable objects, use copy.deepcopy() or slicing.
04 Core concepts
Operators & String Manipulation
Operators let you compute, compare, and combine values. Strings are sequences of characters — one of the most-used types in real programs.
# Arithmetic a, b = 17, 5 print(a + b) # 22 print(a // b) # 3 — floor division print(a % b) # 2 — remainder (modulo) print(a ** b) # 1419857 — power # Comparisons → True or False print(10 > 5) # True print(10 == 10) # True (equality) print(10 != 5) # True (not equal) # String operations greeting = "Hello" name = "World" message = greeting + ", " + name + "!" # concatenation print(message) print(message.upper()) # HELLO, WORLD! print(message.lower()) # hello, world! print(len(message)) # 13 characters print(message[0:5]) # Hello — slicing # f-strings (Python 3.6+) — preferred formatting age = 28 print(f"{name} is {age} years old.") print(f"Next year: {age + 1}")
Worked example
A product costs $24.99 with 8% tax. Total = 24.99 * 1.08 = $26.99. In code: total = round(24.99 * 1.08, 2) — always use round() for currency to avoid floating-point surprises like 26.989199999999998.
05 Control flow
Conditional Statements
Conditionals let your program branch — execute different code based on whether a condition is True or False.
score = 87 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F" print(f"Score: {score} → Grade: {grade}") # Logical operators: and, or, not temperature = 28 is_sunny = True if temperature > 25 and is_sunny: print("Great day for the beach!") elif temperature > 25 and not is_sunny: print("Warm but cloudy.") else: print("Maybe stay indoors.") # Ternary (one-line conditional) status = "adult" if age >= 18 else "minor"
Key insight
Indentation is syntax in Python — 4 spaces per level (never tabs mixed with spaces). Comparison operators: ==, !=, >, <, >=, <=. Truthy values: non-zero numbers, non-empty strings/lists, True. Falsy: 0, "", [], None, False.
06 Control flow
Loops — for and while
Loops repeat code. for iterates over sequences; while repeats until a condition becomes false.
# for loop with range(start, stop) — stop is exclusive for number in range(1, 6): print(number) # 1, 2, 3, 4, 5 # Iterate over a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(f"I like {fruit}") # while loop — always ensure the condition eventually becomes False counter = 0 while counter < 4: print(f"Counter: {counter}") counter += 1 # break (exit loop) and continue (skip iteration) for i in range(10): if i == 3: continue # skip printing 3 if i == 7: break # stop at 7 print(i) # enumerate — get index + value for index, fruit in enumerate(fruits): print(f"{index}: {fruit}")
Common pattern
Sum a list without built-in sum(): initialize total = 0, loop with for n in numbers: total += n. This pattern — accumulator + loop — appears everywhere from statistics to game scores.
07 Organization
Functions — Reusable Code Blocks
Functions package logic into named, callable units. They reduce duplication and make programs easier to test and read.
def greet(name): """Return a personalized greeting.""" # docstring return f"Hello, {name}! Welcome aboard." print(greet("Sarah")) def calculate_area(length, width=5): """width defaults to 5 if not provided.""" return length * width print(calculate_area(10)) # 50 print(calculate_area(10, 8)) # 80 # *args — variable positional arguments def sum_all(*args): return sum(args) print(sum_all(1, 2, 3, 4, 5)) # 15 # **kwargs — variable keyword arguments def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_info(name="John", age=25, city="New York") # Lambda — small anonymous function square = lambda x: x ** 2 print(square(7)) # 49
Best practices
One function, one job. Use verb names: calculate_tax(), load_users(). Always document with a docstring. Return early on invalid input instead of nesting deeply. Pure functions (no side effects) are easier to test.
08 Data structures
Lists & Tuples
Lists are ordered, mutable collections in square brackets []. Tuples are ordered and immutable — defined with parentheses ().
numbers = [1, 2, 3, 4, 5] mixed = ["text", 42, 3.14, True, [1, 2]] numbers.append(6) # add to end numbers.insert(0, 0) # insert at index 0 numbers.remove(3) # remove first 3 last = numbers.pop() # remove and return last numbers.sort(reverse=True) # [5, 4, 2, 1, 0] print("List:", numbers) print("Slice [:3]:", numbers[:3]) print("Length:", len(numbers)) # List comprehension — concise creation squares = [x**2 for x in range(1, 6)] evens = [x for x in range(20) if x % 2 == 0] print("Squares:", squares) print("Evens:", evens) # Tuple — immutable, often used for coordinates, DB rows point = (10, 20) x, y = point # unpacking print(f"Point: ({x}, {y})")
When to use which
Use a list when you need to add, remove, or change items. Use a tuple when the collection should not change — dictionary keys, function return of multiple values, or protecting data from accidental modification.
09 Data structures
Dictionaries & Sets
Dictionaries map unique keys to values — like a real dictionary maps words to definitions. Sets hold unique, unordered items — perfect for removing duplicates.
student = { "name": "Omar", "age": 23, "major": "Computer Science", "courses": ["Algorithms", "Database", "AI"], "graduated": False } print(student["name"]) print(student.get("GPA", "Not available")) # safe access student["GPA"] = 3.8 student.update({"age": 24, "graduated": True}) for key, value in student.items(): print(f"{key}: {value}") # Dictionary comprehension squares_dict = {x: x**2 for x in range(1, 6)} print(squares_dict) # Sets — unique elements, fast membership tests tags = {"python", "tutorial", "beginner", "python"} print(tags) # {'tutorial', 'beginner', 'python'} print("python" in tags) # True — O(1) lookup a = {1, 2, 3, 4} b = {3, 4, 5, 6} print(a | b) # union: {1,2,3,4,5,6} print(a & b) # intersection: {3, 4}
Real-world use
JSON APIs return dictionaries. Configuration files map settings to values. Sets deduplicate email lists before sending campaigns. In data science, pandas DataFrames are built on dictionaries of columns.
10 I/O
File Handling
Python reads and writes text, CSV, and JSON files with built-in tools. Always use with open(...) — it closes the file automatically, even if an error occurs.
# Write text file with open("sample.txt", "w", encoding="utf-8") as file: file.write("Line 1: Python is awesome\n") file.write("Line 2: Learning is fun\n") # Read entire file with open("sample.txt", "r", encoding="utf-8") as file: content = file.read() print(content) # Read line by line (memory-efficient for large files) with open("sample.txt", "r", encoding="utf-8") as file: for line_num, line in enumerate(file, start=1): print(f"Line {line_num}: {line.strip()}") # Append mode with open("sample.txt", "a", encoding="utf-8") as file: file.write("Line 3: Added later.\n") # JSON — structured data import json data = {"name": "Alice", "scores": [95, 87, 92]} with open("data.json", "w") as f: json.dump(data, f, indent=2) with open("data.json", "r") as f: loaded = json.load(f) print(loaded["name"])
File modes
Mode
Meaning
'r'
Read (default). File must exist.
'w'
Write — creates or overwrites.
'a'
Append — adds to end.
'r+'
Read and write.
'b'
Binary mode (images, PDFs) — combine with above.
11 Advanced basics
Object-Oriented Programming
OOP models real-world entities as objects with attributes (data) and methods (behavior). A class is the blueprint; an instance is the built object.
Encapsulation — bundle data + methods; hide internals with _private convention.
Inheritance — child classes reuse and extend parent behavior via super().
Polymorphism — same method name, different behavior per class.
Abstraction — expose only what users need; hide complexity.
12 Robustness
Error & Exception Handling
Programs encounter bad input, missing files, and network failures. try-except catches errors gracefully instead of crashing.
try: number = int(input("Enter a number: ")) result = 10 / number print(f"10 / {number} = {result}") except ValueError: print("Invalid input! Please enter an integer.") except ZeroDivisionError: print("Cannot divide by zero!") except Exception as e: print(f"Unexpected error: {e}") else: print("Division succeeded.") # runs only if no exception finally: print("Done.") # always runs # Raising your own exceptions def withdraw(balance, amount): if amount > balance: raise ValueError("Insufficient funds") return balance - amount
Defensive programming
Catch specific exceptions (ValueError, FileNotFoundError), not bare except:. Log errors in production. Validate user input at the boundary — don't let bad data propagate deep into your logic.
13 Ecosystem
Modules, pip & Virtual Environments
Python's power comes from its ecosystem. The standard library covers HTTP, dates, math, and more. Third-party packages install via pip. Virtual environments isolate project dependencies.
# Import entire module import math print(math.sqrt(144)) # 12.0 print(math.pi) # Import specific names from datetime import datetime now = datetime.now() print(now.strftime("%Y-%m-%d %H:%M")) # Create your own module: save helpers.py, then: # from helpers import my_function # Terminal commands: # pip install requests # install a package # pip list # see installed packages # python -m venv myenv # create virtual environment # myenv\Scripts\activate # Windows activate # source myenv/bin/activate # macOS/Linux activate
Package
Purpose
requests
HTTP API calls
pandas
Data analysis & tables
flask / django
Web applications
pytest
Automated testing
14 Application
Mini Project — Task Manager CLI
Combine everything: lists, functions, file I/O, and loops. This command-line task manager saves tasks to a JSON file.
import json from pathlib import Path FILE = Path("tasks.json") def load_tasks(): if FILE.exists(): return json.loads(FILE.read_text(encoding="utf-8")) return [] def save_tasks(tasks): FILE.write_text(json.dumps(tasks, indent=2), encoding="utf-8") def add_task(tasks, description): tasks.append({"id": len(tasks) + 1, "text": description, "done": False}) save_tasks(tasks) print(f"Added: {description}") def list_tasks(tasks): if not tasks: print("No tasks yet.") return for t in tasks: mark = "✓" if t["done"] else " " print(f"[{mark}] {t['id']}. {t['text']}") def main(): tasks = load_tasks() while True: cmd = input("\n(add/list/quit): ").strip().lower() if cmd == "add": add_task(tasks, input("Task: ")) elif cmd == "list": list_tasks(tasks) elif cmd == "quit": print("Goodbye!") break if __name__ == "__main__": main()
Next steps
Extend the project: add done <id> to mark complete, delete <id> to remove, or wrap it in a Flask web UI. Then explore automate the boring stuff, build a REST API, or dive into data science with pandas.
Congratulations
You now have a solid Python foundation — variables, control flow, data structures, OOP, files, errors, and the package ecosystem. Practice daily: solve problems on Exercism or LeetCode (easy), read others' code on GitHub, and build one small project per week. Consistency beats intensity.