FREE • INTERACTIVE • BEGINNER-FRIENDLY

Learn Python

Master Python programming with our comprehensive, interactive tutorial. From basics to advanced concepts — learn by doing with 50+ live examples and instant feedback.

Lessons
15
Examples
50+
Duration
3 Hours
Cost
FREE
1

What is Python?

5 min read

Python is a high-level, interpreted programming language known for its simplicity and readability. Created by Guido van Rossum and first released in 1991, Python emphasizes code readability and allows programmers to express concepts in fewer lines of code than languages like C++ or Java.

Python is one of the most popular programming languages in the world, used by millions of developers for web development, data science, artificial intelligence, automation, and more. Its syntax is designed to be intuitive and mirrors natural language, making it an excellent choice for beginners.

🐍 Why Python is Popular

  • Easy to learn: Simple syntax that reads like English
  • Versatile: Used for web dev, data science, AI, automation, and more
  • Large community: Millions of developers and extensive documentation
  • Rich ecosystem: Thousands of libraries and frameworks available
  • Cross-platform: Runs on Windows, macOS, Linux, and more
hello.py
Valid Python ✓
# Your first Python program
print("Hello, World!")
name = "Python"
print(f"Welcome to {name}!")
2

Python Syntax Basics

8 min read

Python syntax is clean and readable. Understanding these fundamental rules will help you write Python code effectively.

Python Features

  • Indentation-based blocks (no curly braces)
  • Dynamic typing (no type declarations)
  • Comments start with #
  • Case-sensitive (name ≠ Name)
  • Variables don't need declaration
  • Multiple assignment: a, b = 1, 2

📝 Code Structure

  • Use 4 spaces for indentation (standard)
  • Colon : starts code blocks
  • No semicolons needed (optional)
  • Line continuation with \ or parentheses
  • String quotes: single or double (both work)

Wrong Indentation

if x > 0:
print("Positive")  # IndentationError!
    print("Still positive")

Correct Indentation

if x > 0:
    print("Positive")  # Correct!
    print("Still positive")

Try It Yourself

Edit the Python code and see the results

Click "Run Code" to see results

Try these examples:

3

Variables & Data Types

10 min read

Python is dynamically typed, meaning you don't need to declare variable types. Python automatically determines the type based on the value assigned.

Basic Data Types

🔢

Integer

age = 30
count = -5
big_number = 1000000

Whole numbers, positive or negative. No size limit in Python 3.

📊

Float

price = 19.99
pi = 3.14159
temperature = -5.5

Decimal numbers. Use for calculations requiring precision.

📝

String

name = "Python"
message = 'Hello, World!'
multiline = """This is
a multiline
string"""

Text data. Can use single, double, or triple quotes. Triple quotes for multiline strings.

✓✗

Boolean

is_active = True
is_complete = False
has_permission = True

True or False (capitalized). Used for conditional logic.

📋

List

fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]

Ordered, mutable collection. Can contain any data type, including mixed types.

📖

Dictionary

person = {
    "name": "John",
    "age": 30,
    "city": "NYC"
}

Key-value pairs. Keys must be immutable (strings, numbers, tuples).

🔒

Tuple

coordinates = (10, 20)
colors = ("red", "green", "blue")
single = (42,)  # Note the comma

Ordered, immutable collection. Faster than lists, used for fixed data.

None

result = None
value = None

Represents absence of value. Similar to null in other languages.

4

Operators & Expressions

8 min read

Python supports various operators for performing operations on variables and values.

Arithmetic Operators

OperatorDescriptionExample
+Addition5 + 3 = 8
-Subtraction10 - 4 = 6
*Multiplication3 * 4 = 12
/Division (float)10 / 3 = 3.333...
//Floor division10 // 3 = 3
%Modulus (remainder)10 % 3 = 1
**Exponentiation2 ** 3 = 8

Comparison Operators

x = 5
y = 10

print(x == y)  # False (equal)
print(x != y)  # True (not equal)
print(x < y)   # True (less than)
print(x > y)   # False (greater than)
print(x <= y)  # True (less than or equal)
print(x >= y)  # False (greater than or equal)

Logical Operators

a = True
b = False

print(a and b)  # False
print(a or b)   # True
print(not a)    # False
5

Control Flow

12 min read

Control flow statements allow you to control the execution order of your code. Python supports if/else, loops, and more.

If/Else Statements

age = 20

if age >= 18:
    print("You are an adult")
elif age >= 13:
    print("You are a teenager")
else:
    print("You are a child")

For Loops

# Iterate over a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

# Iterate with index
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

# Range function
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

While Loops

count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1

# Break and continue
while True:
    user_input = input("Enter 'quit' to exit: ")
    if user_input == 'quit':
        break
    if user_input == 'skip':
        continue
    print(f"You entered: {user_input}")
6

Functions

10 min read

Functions are reusable blocks of code that perform a specific task. They help organize code and avoid repetition.

Defining Functions

# Simple function
def greet(name):
    return f"Hello, {name}!"

# Function with default parameters
def greet_with_title(name, title="Mr."):
    return f"Hello, {title} {name}!"

# Function with multiple return values
def get_name_and_age():
    return "John", 30

name, age = get_name_and_age()

Lambda Functions

# Lambda (anonymous) function
square = lambda x: x ** 2
print(square(5))  # 25

# Used with map, filter, etc.
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
# [1, 4, 9, 16, 25]
7

Lists & Dictionaries

12 min read

Lists and dictionaries are Python's most commonly used data structures for storing collections of data.

Lists

# Create a list
fruits = ["apple", "banana", "orange"]

# Access elements
print(fruits[0])      # "apple"
print(fruits[-1])     # "orange" (last item)

# Modify list
fruits.append("grape")  # Add item
fruits.remove("banana") # Remove item
fruits.insert(1, "mango")  # Insert at index

# List methods
fruits.sort()         # Sort alphabetically
fruits.reverse()      # Reverse order
length = len(fruits)  # Get length

Dictionaries

# Create a dictionary
person = {
    "name": "John",
    "age": 30,
    "city": "NYC"
}

# Access values
print(person["name"])        # "John"
print(person.get("age"))    # 30
print(person.get("email", "N/A"))  # "N/A" (default)

# Modify dictionary
person["email"] = "john@example.com"  # Add/update
person.pop("age")  # Remove key
person.clear()     # Clear all items

# Dictionary methods
keys = person.keys()    # Get all keys
values = person.values()  # Get all values
items = person.items()   # Get key-value pairs
8

Object-Oriented Programming

15 min read

Python supports object-oriented programming (OOP) with classes and objects. OOP helps organize code into reusable, modular components.

Classes and Objects

# Define a class
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def introduce(self):
        return f"I'm {self.name}, {self.age} years old"
    
    def have_birthday(self):
        self.age += 1

# Create objects (instances)
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

print(person1.introduce())  # "I'm Alice, 25 years old"
person1.have_birthday()
print(person1.age)  # 26

Inheritance

# Base class
class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        return "Some sound"

# Derived class
class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

dog = Dog("Buddy")
print(dog.speak())  # "Woof!"
9

File Handling

10 min read

Python makes it easy to read from and write to files. The with statement ensures files are properly closed.

Reading Files

# Read entire file
with open('data.txt', 'r') as file:
    content = file.read()
    print(content)

# Read line by line
with open('data.txt', 'r') as file:
    for line in file:
        print(line.strip())  # strip() removes newline

# Read all lines into list
with open('data.txt', 'r') as file:
    lines = file.readlines()

Writing Files

# Write to file (overwrites)
with open('output.txt', 'w') as file:
    file.write("Hello, World!")

# Append to file
with open('output.txt', 'a') as file:
    file.write("\nNew line")

# Write multiple lines
lines = ["Line 1", "Line 2", "Line 3"]
with open('output.txt', 'w') as file:
    file.writelines(lines)
10

Error Handling

10 min read

Python uses try-except blocks to handle errors gracefully. This prevents your program from crashing when something goes wrong.

Try-Except Blocks

# Basic error handling
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

# Multiple exceptions
try:
    number = int(input("Enter a number: "))
    result = 100 / number
except ValueError:
    print("Invalid input! Please enter a number.")
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"An error occurred: {e}")

Finally Block

# Finally always executes
try:
    file = open('data.txt', 'r')
    content = file.read()
except FileNotFoundError:
    print("File not found!")
finally:
    file.close()  # Always closes, even if error occurs

# Better: use 'with' statement (automatic cleanup)
try:
    with open('data.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("File not found!")
11

Modules & Packages

12 min read

Modules are Python files containing functions, classes, and variables. Packages are collections of modules. They help organize and reuse code.

Importing Modules

# Import entire module
import math
print(math.pi)  # 3.14159...

# Import specific function
from math import sqrt, pow
print(sqrt(16))  # 4.0

# Import with alias
import datetime as dt
now = dt.datetime.now()

# Import all (not recommended)
from math import *

Common Built-in Modules

math

Mathematical functions

import math; math.sqrt(16)
datetime

Date and time operations

from datetime import datetime; datetime.now()
os

Operating system interface

import os; os.getcwd()
json

JSON encoding/decoding

import json; json.loads(data)
random

Random number generation

import random; random.randint(1, 10)
re

Regular expressions

import re; re.search(pattern, text)
12

Common Mistakes

10 min read

Even experienced Python developers make these mistakes. Learn to avoid them early.

1

Indentation Errors

Python uses indentation to define code blocks. Use 4 spaces consistently (not tabs).

HIGH

Wrong

if x > 0:
print("Positive")  # IndentationError!

Correct

if x > 0:
    print("Positive")  # Correct indentation
2

Mutable Default Arguments

Mutable default arguments are shared across function calls. Use None as default instead.

HIGH

Wrong

def add_item(item, my_list=[]):
    my_list.append(item)
    return my_list

Correct

def add_item(item, my_list=None):
    if my_list is None:
        my_list = []
    my_list.append(item)
    return my_list
3

Modifying List While Iterating

Modifying a list while iterating can cause unexpected behavior. Use list comprehension or iterate over a copy.

HIGH

Wrong

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:
        numbers.remove(num)  # Dangerous!

Correct

numbers = [1, 2, 3, 4, 5]
numbers = [num for num in numbers if num % 2 != 0]  # List comprehension
4

Using == for None

Use "is" or "is not" for None comparisons, not == or !=. This checks identity, not equality.

MEDIUM

Wrong

if value == None:  # Not recommended
    print("No value")

Correct

if value is None:  # Correct
    print("No value")
5

Forgetting Return Statement

Functions without a return statement return None. Always use return for values you want to use.

MEDIUM

Wrong

def calculate_sum(a, b):
    a + b  # Missing return!

Correct

def calculate_sum(a, b):
    return a + b  # Correct
13

Best Practices

12 min read

Follow these Python best practices to write clean, maintainable, and Pythonic code.

1

📋Follow PEP 8 Style Guide

PEP 8 is Python's official style guide. Following it makes your code more readable and professional.

✓ Good naming

user_name = "John" def calculate_total(): pass

✗ Bad naming

userName = "John" def CalculateTotal(): pass
2

Use List Comprehensions

List comprehensions are more Pythonic and often faster than loops.

✗ Loop approach

squares = []
for x in range(10):
    squares.append(x ** 2)

✓ List comprehension

squares = [x ** 2 for x in range(10)]
3

💬Use f-strings for Formatting

f-strings (Python 3.6+) are the most readable and efficient way to format strings.

✗ Old style

name = "John" message = "Hello, %s" % name

✓ f-string

name = "John" message = f"Hello, {name}"
4

🔒Use Context Managers (with statement)

Always use 'with' for file operations to ensure proper cleanup.

✗ Manual cleanup

file = open('data.txt')
content = file.read()
file.close()  # Easy to forget!

✓ Context manager

with open('data.txt') as file:
    content = file.read()
# Automatically closed
5

📚Write Docstrings

Document your functions and classes with docstrings for better code documentation.

def calculate_area(length, width):
    """
    Calculate the area of a rectangle.
    
    Args:
        length (float): The length of the rectangle
        width (float): The width of the rectangle
    
    Returns:
        float: The area of the rectangle
    """
    return length * width
💻

Practice Coding

Interactive exercises to test your skills

Put your Python knowledge to the test! Complete these exercises to reinforce what you've learned. Each exercise has a solution you can check when you're ready.

Exercise 1: Hello World Program

Beginner

Write a Python program that prints "Hello, World!" to the console.

Exercise 2: Variables and Operations

Beginner

Create two variables: name (string) and age (integer). Then print a message combining them using an f-string.

Exercise 3: Create a Function

Intermediate

Write a function called greet that takes a name parameter and returns a greeting message. Then call it with "Alice".

Exercise 4: List Operations

Intermediate

Create a list of numbers [1, 2, 3, 4, 5]. Use a list comprehension to create a new list with each number squared.

Exercise 5: Create a Class

Advanced

Create a Person class with __init__ method that takes name and age. Add a method introduce() that returns a string with the person's name and age.

Ready to Practice?

Now that you understand Python, explore our developer tools and continue your learning journey.