Free Interactive Python Course

Python Tutorial — Learn Python Step by Step

Key takeaway: Master Python programming from scratch — variables, loops, functions, OOP, file handling, and libraries — with clear human-readable explanations and runnable code examples.

50+ Structured Lessons
Runnable Code Examples
100% Free No Registration
Updated October 2026

Python Global Keyword

The global keyword allows a function to modify a variable defined at the module level. Without it, assignment inside a function creates a new local variable instead.

Why global Is Needed

# Without global — this FAILS
counter = 0

def increment():
    counter += 1  # UnboundLocalError!
    # Python sees assignment and assumes counter is local
    # but local counter was never assigned before this line

# With global — this WORKS
counter = 0

def increment():
    global counter  # tell Python: use the module-level counter
    counter += 1

increment()
increment()
increment()
print(counter)  # 3

Reading vs Modifying Globals

# You can READ globals without the global keyword
APP_NAME = "MyApp"
VERSION = "2.1.0"

def show_info():
    # Reading is fine — no global keyword needed
    print(f"{APP_NAME} v{VERSION}")

show_info()  # MyApp v2.1.0

# You only need global when you want to REASSIGN
def update_version(new_version):
    global VERSION
    VERSION = new_version

update_version("3.0.0")
print(VERSION)  # 3.0.0

# Note: mutating mutable globals (lists, dicts) works without global
settings = {"debug": False}

def enable_debug():
    settings["debug"] = True  # mutating, not reassigning — no global needed

enable_debug()
print(settings)  # {"debug": True}

Practical Examples

# Example 1: Simple counter
request_count = 0

def handle_request():
    global request_count
    request_count += 1
    print(f"Handling request #{request_count}")

handle_request()  # Handling request #1
handle_request()  # Handling request #2

# Example 2: Toggle/configuration flag
_verbose = False

def set_verbose(enabled):
    global _verbose
    _verbose = enabled

def log(message):
    if _verbose:
        print(f"[LOG] {message}")

set_verbose(True)
log("Server started")  # [LOG] Server started

# Example 3: Caching with a global dict
_cache = {}

def get_data(key):
    global _cache  # not strictly needed for mutation, but makes intent clear
    if key not in _cache:
        _cache[key] = expensive_lookup(key)
    return _cache[key]

global vs nonlocal

# global: refers to module-level variable
# nonlocal: refers to enclosing function variable

x = "global"

def outer():
    x = "outer"

    def inner_global():
        global x
        x = "changed by inner_global"

    def inner_nonlocal():
        nonlocal x
        x = "changed by inner_nonlocal"

    inner_nonlocal()
    print(x)  # "changed by inner_nonlocal" (outer x changed)

outer()
print(x)  # "global" (module x unchanged by nonlocal)

# Now with global:
def outer2():
    x = "outer"

    def inner():
        global x
        x = "changed globally"

    inner()
    print(x)  # "outer" (outer2 local x unchanged)

outer2()
print(x)  # "changed globally" (module x was changed)

When to Avoid global

# PREFER function parameters and return values over global
# BAD — hidden dependency
total = 0
def add_to_total(n):
    global total
    total += n

# GOOD — explicit, testable, no side effects
def add(current_total, n):
    return current_total + n

result = add(0, 5)
result = add(result, 10)
print(result)  # 15

# BETTER for stateful logic — use a class
class Accumulator:
    def __init__(self):
        self.total = 0

    def add(self, n):
        self.total += n
        return self.total

acc = Accumulator()
print(acc.add(5))   # 5
print(acc.add(10))  # 15
  • global is only needed to reassign a module-level variable inside a function.
  • You can read globals and mutate mutable globals (lists, dicts) without global.
  • Use nonlocal for enclosing function scope; global for module scope.
  • Minimize use of global — prefer parameters, return values, or classes for cleaner code.
  • Global state makes code harder to test, debug, and reason about in larger projects.

Python Programming Tutorial — Learn Python in a practical, step-by-step way. According to the official Python documentation, Python emphasizes code readability and simplicity, making it ideal for beginners.

Related tools: Python Online Compiler | Python Examples | JavaScript Tutorial | Java Tutorial

Python Career & Learning Guide

Python is the world's most popular programming language for beginners, data science, AI/ML, web development, and automation. This tutorial teaches Python step-by-step with clear explanations and runnable code examples in our free Python Compiler.

Why Learn Python in 2026?

  • #1 Most Popular Language: Ranked first on TIOBE, Stack Overflow, and GitHub.
  • AI and Data Science: The primary language for machine learning (TensorFlow, PyTorch, scikit-learn) and data analysis (Pandas, NumPy).
  • Web Development: Django and Flask power scalable backends at companies like Instagram and Spotify.
  • Automation & Scripting: Automate files, emails, web scraping, and data processing in minutes.

Python vs Other Languages

FeaturePythonJavaJavaScriptC++
SyntaxVery clean, readableVerboseModerateComplex
TypingDynamic, strongStatic, strongDynamic, weakStatic, strong
Best ForAI/ML, Data, WebEnterprise, AndroidWeb Frontend/BackendSystems, Games
Learning Time2–4 weeks basics4–6 weeks basics3–4 weeks basics8–12 weeks basics

Frequently Asked Questions

Do I need prior programming experience to learn Python?

No! Python is specifically designed to be beginner-friendly. This tutorial starts from zero and builds up gradually.

Which Python version should I use?

Python 3.10+ is recommended. All examples in this tutorial use Python 3 syntax.

Is this Python tutorial completely free?

Yes, 100% free with no registration or sign-up required. Access all lessons and code examples anytime.