Prerequisites
- Basic understanding of programming concepts 📝
- Python installation (3.8+) 🐍
- VS Code or preferred IDE 💻
What you'll learn
- Understand the concept fundamentals 🎯
- Apply the concept in real projects 🏗️
- Debug common issues 🐛
- Write clean, Pythonic code ✨
🎯 Introduction
Welcome to this exciting tutorial on Python scripts vs modules! 🎉 In this guide, we’ll explore the fundamental differences between Python scripts and modules, and why understanding this distinction is crucial for organizing your code effectively.
You’ll discover how knowing when to write a script versus a module can transform your Python development experience. Whether you’re building automation tools 🤖, creating reusable libraries 📚, or developing applications 🌐, understanding this concept is essential for writing professional, maintainable code.
By the end of this tutorial, you’ll feel confident deciding when to use scripts and when to create modules in your own projects! Let’s dive in! 🏊♂️
📚 Understanding Scripts vs Modules
🤔 What’s the Difference?
Think of a Python script as a complete recipe 🍳 that you follow from start to finish, while a module is like a cookbook 📖 full of recipes that you can reference whenever needed.
In Python terms:
- Script: A
.py
file designed to be run directly 🏃♂️ - Module: A
.py
file designed to be imported and used by other files 📦
This means you can:
- ✨ Run scripts to perform specific tasks
- 🚀 Import modules to reuse code
- 🛡️ Build larger applications by combining both
💡 Why Does This Matter?
Here’s why understanding the difference is important:
- Code Organization 📁: Keep your projects clean and structured
- Reusability ♻️: Write once, use many times
- Maintainability 🔧: Easier to update and debug
- Professional Development 💼: Follow industry best practices
Real-world example: Imagine building a weather app 🌤️. Your main application would be a script, while functions for fetching weather data would be in a module!
🔧 Basic Syntax and Usage
📝 Creating a Simple Script
Let’s start with a basic Python script:
# weather_app.py - A Python script 🏃♂️
# This runs when executed directly
print("🌤️ Welcome to Weather App!")
def get_temperature(city):
# Simulated temperature data
temps = {"New York": 72, "London": 59, "Tokyo": 68}
return temps.get(city, "Unknown")
# Script execution starts here
city = input("Enter city name: ")
temp = get_temperature(city)
print(f"🌡️ Temperature in {city}: {temp}°F")
print("Thanks for using Weather App! 👋")
💡 Explanation: This script runs from top to bottom when executed with python weather_app.py
.
🎯 Creating a Module
Now let’s create a reusable module:
# weather_utils.py - A Python module 📦
"""Weather utility functions for reuse"""
# Module-level constants
DEFAULT_UNIT = "fahrenheit"
API_KEY = "your-api-key" # 🔐 In real apps, use env variables!
def celsius_to_fahrenheit(celsius):
"""Convert Celsius to Fahrenheit 🌡️"""
return (celsius * 9/5) + 32
def get_weather_emoji(condition):
"""Return emoji for weather condition 🎨"""
weather_emojis = {
"sunny": "☀️",
"cloudy": "☁️",
"rainy": "🌧️",
"snowy": "❄️",
"stormy": "⛈️"
}
return weather_emojis.get(condition.lower(), "🌈")
def format_temperature(temp, unit="F"):
"""Format temperature with unit 📊"""
return f"{temp}°{unit}"
# This only runs if file is executed directly
if __name__ == "__main__":
print("🧪 Testing weather_utils module...")
print(f"32°C = {celsius_to_fahrenheit(32)}°F")
print(f"Sunny weather: {get_weather_emoji('sunny')}")
💡 Practical Examples
🛒 Example 1: E-commerce System
Let’s build a practical example showing scripts vs modules:
# product_module.py - Reusable module 📦
class Product:
"""Product class for our store 🛍️"""
def __init__(self, name, price, emoji):
self.name = name
self.price = price
self.emoji = emoji
def display(self):
return f"{self.emoji} {self.name} - ${self.price:.2f}"
def calculate_discount(price, percent):
"""Calculate discount amount 💰"""
return price * (percent / 100)
def apply_tax(price, tax_rate=0.08):
"""Apply tax to price 🧾"""
return price * (1 + tax_rate)
# Module test code
if __name__ == "__main__":
# This only runs when module is executed directly
print("🧪 Testing product module...")
laptop = Product("Laptop", 999.99, "💻")
print(laptop.display())
# shopping_app.py - Main script 🏃♂️
import product_module # Import our module!
def main():
"""Main shopping application 🛒"""
print("🛍️ Welcome to Python Shop!")
# Create products using imported module
products = [
product_module.Product("Python Book", 29.99, "📘"),
product_module.Product("Coffee Mug", 12.99, "☕"),
product_module.Product("Keyboard", 79.99, "⌨️")
]
# Display products
print("\n📋 Available Products:")
for i, product in enumerate(products, 1):
print(f"{i}. {product.display()}")
# Shopping logic
cart = []
while True:
choice = input("\nEnter product number (or 'done'): ")
if choice.lower() == 'done':
break
try:
index = int(choice) - 1
if 0 <= index < len(products):
cart.append(products[index])
print(f"✅ Added {products[index].emoji} to cart!")
except (ValueError, IndexError):
print("❌ Invalid choice!")
# Calculate total
if cart:
subtotal = sum(item.price for item in cart)
tax = product_module.apply_tax(subtotal) - subtotal
total = subtotal + tax
print("\n🧾 Your Order:")
for item in cart:
print(f" {item.display()}")
print(f"\nSubtotal: ${subtotal:.2f}")
print(f"Tax: ${tax:.2f}")
print(f"Total: ${total:.2f} 💳")
if __name__ == "__main__":
main()
🎯 Try it yourself: Add a coupon system using a new module!
🎮 Example 2: Game Development
Let’s create a game system:
# game_entities.py - Game entities module 🎮
import random
class Player:
"""Player character class 🦸♂️"""
def __init__(self, name):
self.name = name
self.health = 100
self.score = 0
self.level = 1
self.emoji = "🦸♂️"
def take_damage(self, amount):
"""Player takes damage 💥"""
self.health = max(0, self.health - amount)
return self.health > 0
def heal(self, amount):
"""Heal the player ❤️"""
self.health = min(100, self.health + amount)
def add_score(self, points):
"""Add to player score 🎯"""
self.score += points
# Level up every 100 points
new_level = (self.score // 100) + 1
if new_level > self.level:
self.level = new_level
return True # Leveled up!
return False
class Enemy:
"""Enemy class 👾"""
enemy_types = {
"goblin": {"health": 30, "damage": 10, "emoji": "👺", "points": 20},
"dragon": {"health": 100, "damage": 25, "emoji": "🐉", "points": 100},
"zombie": {"health": 50, "damage": 15, "emoji": "🧟", "points": 40}
}
def __init__(self, enemy_type):
stats = self.enemy_types.get(enemy_type, self.enemy_types["goblin"])
self.type = enemy_type
self.health = stats["health"]
self.damage = stats["damage"]
self.emoji = stats["emoji"]
self.points = stats["points"]
def attack(self):
"""Enemy attacks with random variance 🎲"""
return random.randint(self.damage - 5, self.damage + 5)
# adventure_game.py - Main game script 🎮
import game_entities
import random
import time
def display_status(player):
"""Display player status bar 📊"""
health_bar = "❤️" * (player.health // 10)
print(f"\n{player.emoji} {player.name} | {health_bar} {player.health}/100 | ⭐ Score: {player.score} | 📈 Level: {player.level}")
def battle(player, enemy):
"""Battle sequence ⚔️"""
print(f"\n⚔️ A wild {enemy.emoji} {enemy.type} appears!")
while enemy.health > 0 and player.health > 0:
print(f"\n{enemy.emoji} Health: {enemy.health}")
action = input("Choose: [a]ttack, [h]eal, [r]un: ").lower()
if action == 'a':
damage = random.randint(15, 30)
enemy.health -= damage
print(f"💥 You deal {damage} damage!")
if enemy.health > 0:
enemy_damage = enemy.attack()
player.take_damage(enemy_damage)
print(f"😱 {enemy.emoji} deals {enemy_damage} damage!")
elif action == 'h':
heal_amount = random.randint(10, 25)
player.heal(heal_amount)
print(f"✨ You heal for {heal_amount} HP!")
enemy_damage = enemy.attack()
player.take_damage(enemy_damage)
print(f"😱 {enemy.emoji} deals {enemy_damage} damage!")
elif action == 'r':
if random.random() < 0.5:
print("🏃 You escaped!")
return False
else:
print("❌ Can't escape!")
enemy_damage = enemy.attack()
player.take_damage(enemy_damage)
if enemy.health <= 0:
print(f"\n🎉 Victory! You defeated the {enemy.type}!")
if player.add_score(enemy.points):
print(f"📈 LEVEL UP! You're now level {player.level}!")
return True
return False
def main():
"""Main game loop 🎮"""
print("🏰 Welcome to Python Adventure!")
name = input("Enter your hero's name: ")
player = game_entities.Player(name)
print(f"\n📖 Greetings {player.name}! Your adventure begins...")
enemies_defeated = 0
while player.health > 0:
display_status(player)
# Random encounter
if random.random() < 0.7: # 70% chance of enemy
enemy_type = random.choice(["goblin", "zombie", "dragon"])
enemy = game_entities.Enemy(enemy_type)
if battle(player, enemy):
enemies_defeated += 1
else:
# Find treasure
treasure = random.choice(["🍎 Apple (+20 HP)", "🧪 Potion (+50 HP)", "💎 Gem (+50 points)"])
print(f"\n📦 You found: {treasure}")
if "Apple" in treasure:
player.heal(20)
elif "Potion" in treasure:
player.heal(50)
elif "Gem" in treasure:
player.add_score(50)
if player.health <= 0:
print(f"\n💀 Game Over! You defeated {enemies_defeated} enemies.")
print(f"🏆 Final Score: {player.score}")
break
if input("\nContinue? (y/n): ").lower() != 'y':
print(f"\n👋 Thanks for playing! Final score: {player.score}")
break
if __name__ == "__main__":
main()
🚀 Advanced Concepts
🧙♂️ The __name__
Magic Variable
Understanding if __name__ == "__main__":
is crucial:
# advanced_module.py
print(f"🔍 Module name is: {__name__}")
def useful_function():
"""A function others might import 🛠️"""
return "I'm useful!"
# This section only runs when file is executed directly
if __name__ == "__main__":
print("🏃♂️ Running as a script!")
print(f"Result: {useful_function()}")
else:
print("📦 Being imported as a module!")
# test_import.py
import advanced_module # This will show different output!
print(f"✨ Using imported function: {advanced_module.useful_function()}")
🏗️ Package Structure
For larger projects, organize modules into packages:
# Project structure 📁
my_project/
__init__.py # Makes directory a package
main.py # Main script 🏃♂️
utils/
__init__.py
math_utils.py # Math module 🔢
string_utils.py # String module 📝
models/
__init__.py
user.py # User model 👤
product.py # Product model 📦
⚠️ Common Pitfalls and Solutions
😱 Pitfall 1: Circular Imports
# ❌ Wrong way - circular import!
# file1.py
import file2
def func1():
return file2.func2()
# file2.py
import file1 # 💥 Circular import!
def func2():
return file1.func1()
# ✅ Correct way - restructure your code!
# utils.py
def shared_function():
return "Shared functionality 🤝"
# file1.py
from utils import shared_function
def func1():
return shared_function()
# file2.py
from utils import shared_function
def func2():
return shared_function()
🤯 Pitfall 2: Module Naming Conflicts
# ❌ Dangerous - naming conflict!
# math.py (Don't name your module same as built-in!)
def add(a, b):
return a + b
# other_file.py
import math # 💥 Which math? Yours or Python's?
# ✅ Safe - use unique names!
# my_math_utils.py
def add(a, b):
return a + b
# other_file.py
import my_math_utils # ✅ Clear and safe!
import math # ✅ Built-in math still available
🛠️ Best Practices
- 🎯 Clear Purpose: Scripts do one thing well, modules provide reusable tools
- 📝 Good Names: Use descriptive names (
user_authentication.py
notauth.py
) - 🛡️ Guard Main Code: Always use
if __name__ == "__main__":
- 📁 Organize Well: Group related modules into packages
- ✨ Document Everything: Add docstrings to modules and functions
🧪 Hands-On Exercise
🎯 Challenge: Build a Library Management System
Create a modular library system with:
📋 Requirements:
- ✅ Book module with Book class and utilities
- 📚 Library module for managing collections
- 👤 Member module for library members
- 🏃♂️ Main script to run the system
- 🎨 Each component should use appropriate emojis!
🚀 Bonus Points:
- Add due date tracking
- Implement late fee calculation
- Create a search feature
💡 Solution
🔍 Click to see solution
# book_module.py - Book management module 📚
from datetime import datetime, timedelta
class Book:
"""Book class for library 📖"""
def __init__(self, isbn, title, author, genre):
self.isbn = isbn
self.title = title
self.author = author
self.genre = genre
self.available = True
self.borrowed_by = None
self.due_date = None
self.emoji = self._get_genre_emoji()
def _get_genre_emoji(self):
"""Get emoji based on genre 🎨"""
genre_emojis = {
"fiction": "📖",
"science": "🔬",
"history": "📜",
"technology": "💻",
"children": "🧸",
"mystery": "🔍"
}
return genre_emojis.get(self.genre.lower(), "📚")
def checkout(self, member_id, days=14):
"""Check out book to member 📤"""
if self.available:
self.available = False
self.borrowed_by = member_id
self.due_date = datetime.now() + timedelta(days=days)
return True
return False
def return_book(self):
"""Return book to library 📥"""
self.available = True
self.borrowed_by = None
self.due_date = None
def __str__(self):
status = "✅ Available" if self.available else "❌ Borrowed"
return f"{self.emoji} '{self.title}' by {self.author} - {status}"
# member_module.py - Member management 👤
class Member:
"""Library member class 🎫"""
def __init__(self, member_id, name, email):
self.member_id = member_id
self.name = name
self.email = email
self.books_borrowed = []
self.emoji = "👤"
def borrow_book(self, book_isbn):
"""Add book to borrowed list 📚"""
self.books_borrowed.append(book_isbn)
def return_book(self, book_isbn):
"""Remove book from borrowed list 📤"""
if book_isbn in self.books_borrowed:
self.books_borrowed.remove(book_isbn)
def __str__(self):
return f"{self.emoji} {self.name} (ID: {self.member_id}) - {len(self.books_borrowed)} books"
# library_system.py - Main library script 🏛️
import book_module
import member_module
from datetime import datetime
class Library:
"""Main library system 🏛️"""
def __init__(self, name):
self.name = name
self.books = {}
self.members = {}
self.emoji = "🏛️"
def add_book(self, book):
"""Add book to library 📚"""
self.books[book.isbn] = book
print(f"✅ Added: {book}")
def add_member(self, member):
"""Register new member 👤"""
self.members[member.member_id] = member
print(f"✅ Registered: {member}")
def checkout_book(self, isbn, member_id):
"""Check out book to member 📤"""
if isbn in self.books and member_id in self.members:
book = self.books[isbn]
member = self.members[member_id]
if book.checkout(member_id):
member.borrow_book(isbn)
print(f"✅ {member.name} borrowed '{book.title}'")
print(f"📅 Due date: {book.due_date.strftime('%Y-%m-%d')}")
return True
else:
print(f"❌ '{book.title}' is not available")
return False
def return_book(self, isbn, member_id):
"""Return book from member 📥"""
if isbn in self.books and member_id in self.members:
book = self.books[isbn]
member = self.members[member_id]
book.return_book()
member.return_book(isbn)
print(f"✅ {member.name} returned '{book.title}'")
return True
return False
def search_books(self, query):
"""Search books by title or author 🔍"""
results = []
query_lower = query.lower()
for book in self.books.values():
if (query_lower in book.title.lower() or
query_lower in book.author.lower()):
results.append(book)
return results
def main():
"""Main library application 🏛️"""
print("🏛️ Welcome to Python Library System!")
library = Library("City Central Library")
# Add sample books
sample_books = [
book_module.Book("001", "Python Magic", "Guido van Rossum", "technology"),
book_module.Book("002", "The Coding Mystery", "Ada Lovelace", "mystery"),
book_module.Book("003", "Data Science Fun", "Alan Turing", "science")
]
for book in sample_books:
library.add_book(book)
# Add sample member
member = member_module.Member("M001", "Alice Developer", "[email protected]")
library.add_member(member)
# Interactive menu
while True:
print("\n📋 Menu:")
print("1. 📚 View all books")
print("2. 🔍 Search books")
print("3. 📤 Borrow book")
print("4. 📥 Return book")
print("5. 🚪 Exit")
choice = input("\nChoose option: ")
if choice == "1":
print("\n📚 Library Collection:")
for book in library.books.values():
print(f" {book}")
elif choice == "2":
query = input("🔍 Search for: ")
results = library.search_books(query)
if results:
print("\n🔍 Search Results:")
for book in results:
print(f" {book}")
else:
print("❌ No books found")
elif choice == "3":
isbn = input("Enter ISBN: ")
library.checkout_book(isbn, "M001")
elif choice == "4":
isbn = input("Enter ISBN: ")
library.return_book(isbn, "M001")
elif choice == "5":
print("👋 Thanks for visiting!")
break
if __name__ == "__main__":
main()
🎓 Key Takeaways
You’ve learned so much! Here’s what you can now do:
- ✅ Distinguish between scripts and modules with confidence 💪
- ✅ Create reusable modules for your projects 📦
- ✅ Organize code professionally using best practices 🎯
- ✅ Avoid common import issues like a pro 🛡️
- ✅ Build modular applications with Python! 🚀
Remember: Good code organization is the foundation of maintainable software! 🏗️
🤝 Next Steps
Congratulations! 🎉 You’ve mastered the difference between Python scripts and modules!
Here’s what to do next:
- 💻 Practice creating your own modules
- 🏗️ Refactor an existing script into modules
- 📚 Learn about Python packages and
__init__.py
- 🌟 Share your modular projects with others!
Remember: Every Python expert started by understanding these fundamentals. Keep coding, keep learning, and most importantly, have fun! 🚀
Happy coding! 🎉🚀✨