Complete Python Programming Tutorial

Master Python - a powerful, versatile programming language used for web development, data science, AI, and more

Introduction to Python

Python is an interpreted, high-level, general-purpose programming language created by Guido van Rossum and first released in 1991. Python's design philosophy emphasizes code readability with its notable use of significant whitespace.

Simple Python Program
print("Hello, World!")

Why Learn Python?

  • Easy to Learn - Simple syntax similar to English
  • Versatile - Web development, data science, AI, automation, etc.
  • Large Community - Extensive documentation and support
  • Rich Ecosystem - Vast collection of libraries and frameworks
  • Cross-Platform - Runs on Windows, Linux, macOS
  • High Demand - One of the most sought-after skills in tech

Key Features of Python

  • Interpreted language
  • Dynamically typed
  • Object-oriented and procedural
  • Extensive standard library
  • Supports multiple programming paradigms
  • Automatic memory management

Environment Setup

To start programming in Python, you need to install Python and optionally set up a development environment.

1. Installing Python

  1. Download Python from python.org
  2. Run the installer (check "Add Python to PATH")
  3. Verify installation: python --version in terminal

2. Development Environments

Option Description
IDLE Python's built-in IDE
PyCharm Professional Python IDE by JetBrains
VS Code Lightweight editor with Python extension
Jupyter Notebook Interactive computing environment
Online Editors Replit, Google Colab, PythonAnywhere

3. Running Python Code

  • Interactive Mode: Run python in terminal
  • Script Mode: Save as .py file and run with python filename.py
Testing Python Installation
# Create hello.py
print("Python is working!")

# Run in terminal:
# python hello.py

Basic Syntax

Python syntax is clean and easy to read with significant whitespace (indentation) for code blocks.

Python Program Structure
# This is a comment
def main():  # Function definition
    # Indented block
    print("Hello")

if __name__ == "__main__":
    main()  # Function call

Key Components

Component Description Example
Comments Explanatory notes # Single-line comment
Variables Store data values x = 5
Functions Reusable code blocks def greet(): ...
Indentation Defines code blocks if x > 0:
  print("Positive")
Print Output Display to console print("Hello")

First Python Program

# Simple calculator
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

print(f"Sum: {num1 + num2}")
print(f"Product: {num1 * num2}")
Enter first number: 5 Enter second number: 3 Sum: 8.0 Product: 15.0

Data Types

Python has several built-in data types:

Basic Data Types

Data Type Description Example
int Integer numbers x = 5
float Decimal numbers y = 3.14
str Text (strings) name = "Alice"
bool Boolean (True/False) is_active = True
list Ordered, mutable sequence colors = ["red", "green"]
tuple Ordered, immutable sequence point = (10, 20)
dict Key-value pairs person = {"name": "John"}
set Unordered, unique elements unique = {1, 2, 3}

Type Conversion

x = 5       # int
y = float(x) # 5.0
z = str(x)   # "5"
Data Type Example
# Checking data types
print(type(10))          # <class 'int'>
print(type(3.14))        # <class 'float'>
print(type("Hello"))    # <class 'str'>
print(type([1, 2, 3]))   # <class 'list'>
print(type({"a": 1}))   # <class 'dict'>

Variables

Variables are containers for storing data values. In Python, variables are created when you assign a value to them.

Variable Declaration

variable_name = value
Variable Examples
# Different variable types
name = "Alice"       # String
age = 25            # Integer
height = 5.9        # Float
is_student = True    # Boolean

Rules for Naming Variables

  • Must start with a letter or underscore
  • Can contain letters, numbers, and underscores
  • Case-sensitive (age and Age are different)
  • Cannot use Python keywords (e.g., if, while)
  • Use descriptive names (e.g., user_age instead of ua)

Multiple Assignment

# Assign multiple values
x, y, z = "Orange", "Banana", "Cherry"

# Assign same value
a = b = c = "Apple"

Operators

Python has various operators for different operations:

Arithmetic Operators

Operator Description Example
+ Addition 5 + 3 → 8
- Subtraction 5 - 3 → 2
* Multiplication 5 * 3 → 15
/ Division 5 / 3 → 1.666...
% Modulus 5 % 3 → 2
** Exponentiation 5 ** 3 → 125
// Floor division 5 // 3 → 1

Comparison Operators

Operator Description Example
== Equal 5 == 3 → False
!= Not equal 5 != 3 → True
> Greater than 5 > 3 → True
< Less than 5 < 3 → False
>= Greater than or equal 5 >= 3 → True
<= Less than or equal 5 <= 3 → False

Logical Operators

Operator Description Example
and Returns True if both statements are true x > 3 and x < 10
or Returns True if one of the statements is true x > 3 or x < 10
not Reverse the result not(x > 3)

Operator Example

# Operator examples
a = 10
b = 20

print(f"a + b = {a + b}")
print(f"a < b: {a < b}")
print(f"a == 10 and b == 20: {a == 10 and b == 20}")
a + b = 30 a < b: True a == 10 and b == 20: True

Conditional Statements

Conditional statements are used to perform different actions based on different conditions.

if Statement

if condition:
    # code to execute if condition is True

if-else Statement

if condition:
    # code if True
else:
    # code if False

if-elif-else Statement

if condition1:
    # code if condition1 True
elif condition2:
    # code if condition2 True
else:
    # code if all False

Ternary Operator

value_if_true if condition else value_if_false
Conditional Example
# Grade calculator
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

print(f"Grade: {grade}")  # B

# Ternary example
result = "Pass" if score >= 60 else "Fail"

Loops

Loops are used to execute a block of code repeatedly.

while Loop

while condition:
    # code to execute

for Loop

for item in sequence:
    # code to execute

Loop Control Statements

  • break - Terminates the loop
  • continue - Skips current iteration
  • pass - Placeholder for empty block

Loop Examples

# while loop
i = 1
while i <= 5:
    print(i)
    i += 1

# for loop with range
for num in range(1, 6):
    if num == 3:
        continue
    print(num)

# for loop with list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
1 2 3 4 5 1 2 4 5 apple banana cherry

Functions

Functions are blocks of reusable code that perform a specific task.

Function Definition

def function_name(parameters):
    """docstring"""
    # function body
    return value

Function Call

function_name(arguments)
Function Example
# Function definition
def greet(name):
    """This function greets the person passed in"""
    return f"Hello, {name}!"

# Function call
message = greet("Alice")
print(message)  # Hello, Alice!

Default Arguments

def greet(name="Guest"):
    print(f"Hello, {name}!")

Variable-Length Arguments

def sum_all(*numbers):
    total = 0
    for num in numbers:
        total += num
    return total

Lambda Functions

square = lambda x: x * x
print(square(5))  # 25

Lists

Lists are ordered, mutable collections of items (can contain mixed types).

List Creation

my_list = [1, 2, 3]
empty_list = []
mixed_list = [1, "Hello", 3.4]

List Operations

Operation Description Example
Indexing Access item by index my_list[0] → 1
Slicing Get sublist my_list[1:3] → [2, 3]
Append Add item to end my_list.append(4)
Insert Insert at position my_list.insert(1, 5)
Remove Remove item my_list.remove(2)
Pop Remove and return item my_list.pop() → 3
Length Number of items len(my_list) → 3
List Example
# List operations
fruits = ["apple", "banana", "cherry"]

# Access elements
print(fruits[1])  # banana

# Change element
fruits[0] = "orange"

# Add elements
fruits.append("grape")

# Remove element
fruits.remove("banana")

# Loop through list
for fruit in fruits:
    print(fruit)

List Comprehensions

squares = [x**2 for x in range(10)]
even_numbers = [x for x in range(20) if x % 2 == 0]

Tuples

Tuples are ordered, immutable collections of items (can contain mixed types).

Tuple Creation

my_tuple = (1, 2, 3)
empty_tuple = ()
single_item = (5,)  # Note the comma

Tuple Operations

Operation Description Example
Indexing Access item by index my_tuple[0] → 1
Slicing Get subtuple my_tuple[1:3] → (2, 3)
Count Count occurrences my_tuple.count(2) → 1
Index Find index of item my_tuple.index(3) → 2
Length Number of items len(my_tuple) → 3
Tuple Example
# Tuple operations
colors = ("red", "green", "blue")

# Access elements
print(colors[1])  # green

# Unpacking
r, g, b = colors
print(g)  # green

# Immutable - this will error
# colors[0] = "yellow"

Dictionaries

Dictionaries are unordered collections of key-value pairs.

Dictionary Creation

my_dict = {"name": "John", "age": 30}
empty_dict = {}
with_dict = dict(name="John", age=30)

Dictionary Operations

Operation Description Example
Access Get value by key my_dict["name"] → "John"
Add/Update Add or change item my_dict["city"] = "NY"
Remove Remove item del my_dict["age"]
Keys Get all keys my_dict.keys()
Values Get all values my_dict.values()
Items Get key-value pairs my_dict.items()
Length Number of items len(my_dict) → 2
Dictionary Example
# Dictionary operations
person = {
    "name": "Alice",
    "age": 25,
    "city": "London"
}

# Access value
print(person["name"])  # Alice

# Add new key-value
person["email"] = "alice@example.com"

# Loop through dictionary
for key, value in person.items():
    print(f"{key}: {value}")

Dictionary Comprehensions

squares = {x: x**2 for x in range(6)}
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}

Sets

Sets are unordered collections of unique elements.

Set Creation

my_set = {1, 2, 3}
empty_set = set()  # Not {}
from_list = set([1, 2, 3])

Set Operations

Operation Description Example
Add Add element my_set.add(4)
Remove Remove element my_set.remove(2)
Union Combines sets set1 | set2
Intersection Common elements set1 & set2
Difference Elements in set1 not in set2 set1 - set2
Symmetric Difference Elements in either set but not both set1 ^ set2
Set Example
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

# Union
print(a | b)  # {1, 2, 3, 4, 5, 6}

# Intersection
print(a & b)  # {3, 4}

# Difference
print(a - b)  # {1, 2}

# Symmetric difference
print(a ^ b)  # {1, 2, 5, 6}

Strings

Strings in Python are sequences of Unicode characters.

String Creation

s1 = 'Single quotes'
s2 = "Double quotes"
s3 = """Multi-line
string"""

String Operations

Operation Description Example
Concatenation Combine strings "Hello" + "World" → "HelloWorld"
Repetition Repeat string "Hi" * 3 → "HiHiHi"
Indexing Get character "Hello"[1] → 'e'
Slicing Get substring "Hello"[1:4] → 'ell'
Length Number of characters len("Hello") → 5
Formatting Insert values f"Hello {name}"

Common String Methods

s = " Hello World! "

s.strip()      # "Hello World!"
s.lower()      # " hello world! "
s.upper()      # " HELLO WORLD! "
s.replace("H", "J")  # " Jello World! "
s.split()      # ['Hello', 'World!']
s.find("World") # 6
String Example
# String formatting
name = "Alice"
age = 25

# f-strings (Python 3.6+)
print(f"My name is {name} and I'm {age} years old.")

# String methods
text = " Python is awesome! "
print(text.strip())
print(text.lower())
print(text.replace("awesome", "great"))

File Handling

Python provides functions for creating, reading, updating, and deleting files.

File Modes

Mode Description
'r' Read (default)
'w' Write (creates new or truncates)
'a' Append
'x' Create (fails if exists)
'b' Binary mode
't' Text mode (default)
'+' Updating (read/write)

File Operations

# Open and read
with open("file.txt", "r") as file:
    content = file.read()

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

# Read line by line
with open("file.txt") as file:
    for line in file:
        print(line.strip())
File Handling Example
# Write to file
with open("example.txt", "w") as file:
    file.write("Line 1\n")
    file.write("Line 2\n")

# Read from file
with open("example.txt", "r") as file:
    print("File content:")
    print(file.read())

Exception Handling

Exceptions are errors that occur during program execution. Python provides ways to handle them gracefully.

Try-Except Block

try:
    # Code that might raise an exception
except ExceptionType:
    # Code to handle the exception
else:
    # Code to run if no exception
finally:
    # Code that always runs

Common Exception Types

  • Exception - Base class for all exceptions
  • ValueError - Invalid value
  • TypeError - Invalid operation
  • IndexError - Invalid sequence index
  • KeyError - Dictionary key not found
  • FileNotFoundError - File doesn't exist
  • ZeroDivisionError - Division by zero
Exception Handling Example
try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print(f"Result: {result}")
except ValueError:
    print("Please enter a valid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"An error occurred: {e}")
else:
    print("Division successful")
finally:
    print("Execution complete")

Raising Exceptions

def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

Object-Oriented Programming

Python supports object-oriented programming with classes and objects.

Class Definition

class ClassName:
    # Class attribute
    class_attr = value

    # Constructor
    def __init__(self, param1, param2):
        # Instance attributes
        self.param1 = param1
        self.param2 = param2

    # Instance method
    def method(self):
        # method body
        return self.param1

Creating Objects

obj = ClassName(arg1, arg2)
OOP Example
class Dog:
    # Class attribute
    species = "Canis familiaris"

    # Initializer / Instance attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Instance method
    def description(self):
        return f"{self.name} is {self.age} years old"

    # Another instance method
    def speak(self, sound):
        return f"{self.name} says {sound}"

# Create objects
buddy = Dog("Buddy", 9)
miles = Dog("Miles", 4)

print(buddy.description())
print(miles.speak("Woof Woof"))

Inheritance

class ChildClass(ParentClass):
    def __init__(self, param1, param2):
        super().__init__(param1)  # Call parent constructor
        self.param2 = param2

Special Methods

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    # String representation
    def __str__(self):
        return f"{self.title} by {self.author}"

    # Length of book title
    def __len__(self):
        return len(self.title)

Modules & Packages

Modules are Python files containing reusable code. Packages are collections of modules.

Creating and Using Modules

# mymodule.py
def greet(name):
    return f"Hello, {name}!"

PI = 3.14159

# main.py
import mymodule

print(mymodule.greet("Alice"))
print(mymodule.PI)

Importing Specific Items

from math import sqrt, pi
from mymodule import greet

Creating Packages

mypackage/
    __init__.py
    module1.py
    module2.py
    subpackage/
        __init__.py
        module3.py

Common Standard Library Modules

  • math - Mathematical functions
  • random - Random number generation
  • datetime - Date and time operations
  • os - Operating system interfaces
  • sys - System-specific parameters
  • json - JSON encoding/decoding
  • re - Regular expressions

Date & Time

Python provides the datetime module for working with dates and times.

Date and Time Objects

from datetime import datetime, date, time, timedelta

# Current date and time
now = datetime.now()

# Specific date
d = date(2023, 12, 25)

# Specific time
t = time(14, 30)

# Timedelta (duration)
delta = timedelta(days=7)

Formatting Dates

# Format as string
now.strftime("%Y-%m-%d %H:%M:%S")  # '2023-10-15 14:30:45'

# Parse from string
dt = datetime.strptime("2023-10-15", "%Y-%m-%d")
Date Example
from datetime import datetime, timedelta

# Current date and time
now = datetime.now()
print(f"Current datetime: {now}")

# Formatting
formatted = now.strftime("%A, %B %d, %Y")
print(f"Formatted: {formatted}")

# Date arithmetic
one_week = timedelta(weeks=1)
next_week = now + one_week
print(f"Next week: {next_week}")

JSON Handling

Python's json module allows encoding and decoding JSON data.

JSON Operations

import json

# Convert Python object to JSON string
json_str = json.dumps(python_obj)

# Convert JSON string to Python object
python_obj = json.loads(json_str)

# Write JSON to file
with open("data.json", "w") as f:
    json.dump(python_obj, f)

# Read JSON from file
with open("data.json") as f:
    data = json.load(f)
JSON Example
import json

# Python dictionary
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York",
    "hobbies": ["reading", "hiking"]
}

# Convert to JSON
json_data = json.dumps(person, indent=4)
print("JSON String:")
print(json_data)

# Convert back to Python
python_obj = json.loads(json_data)
print("\nPython Object:")
print(python_obj["name"])

Error Handling

  • Use specific exceptions rather than bare except clauses
  • Include meaningful error messages
  • Use context managers (with statements) for resource management
  • Create custom exception classes when needed

Testing

  • Write unit tests using unittest or pytest
  • Test edge cases and invalid inputs
  • Use mocking for external dependencies
  • Automate testing with CI/CD pipelines
Testing Example
# test_calculator.py
import unittest
from calculator import add

class TestCalculator(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(1, 2), 3)
        self.assertEqual(add(-1, 1), 0)
        self.assertRaises(TypeError, add, 'a', 5)

if __name__ == '__main__':
    unittest.main()

Documentation

  • Write docstrings following Google or NumPy style
  • Use type hints to indicate expected types
  • Include examples in your documentation
  • Generate API documentation with Sphinx
Documentation Example
def calculate_area(length: float, width: float) -> float:
    """Calculate the area of a rectangle.

    Args:
        length: The length of the rectangle in meters
        width: The width of the rectangle in meters

    Returns:
        The area in square meters

    Examples:
        >>> calculate_area(5, 3)
        15.0
    """
    return length * width

Conclusion

Congratulations on completing this comprehensive Python programming guide! You've learned the fundamentals of Python including:

  • Python syntax and basic programming concepts
  • Data structures like lists, tuples, dictionaries, and sets
  • Control flow with conditionals and loops
  • Functions and modular programming
  • Object-oriented programming principles
  • File handling and exception management
  • Working with dates, times, and JSON data
  • Python best practices and coding standards

Next Steps

To continue your Python journey:

  1. Practice regularly - Solve coding challenges on platforms like LeetCode or HackerRank
  2. Build projects - Apply your knowledge to real-world applications
  3. Explore specialized areas:
    • Web Development (Django, Flask)
    • Data Science (NumPy, Pandas, Matplotlib)
    • Machine Learning (scikit-learn, TensorFlow)
    • Automation and Scripting
  4. Contribute to open source - Collaborate on Python projects
  5. Stay updated - Follow Python Enhancement Proposals (PEPs)