Learn Python fundamentals including syntax, data structures, functions, and object-oriented programming for Django development.
Learn Python fundamentals including syntax, data structures, functions, and object-oriented programming for Django development.
Learn the basics of Python syntax, variables, string formatting, arithmetic operations, and user input for Django development.
Content by: Meet Sherasiya
Python Django Developer
Python is a high-level, interpreted programming language known for its simplicity and readability. It's widely used in web development, data science, AI, and many other fields.
# This is a comment
print("Hello, World!") # Simple output
# Variables
name = "John"
age = 25
height = 1.75
is_student = True
# String formatting
print(f"My name is {name} and I am {age} years old")
# Basic arithmetic
x = 10
y = 3
print(f"Addition: {x + y}")
print(f"Subtraction: {x - y}")
print(f"Multiplication: {x * y}")
print(f"Division: {x / y}")
print(f"Floor division: {x // y}")
print(f"Modulus: {x % y}")
print(f"Exponent: {x ** y}")
# Input from user
user_name = input("What's your name? ")
print(f"Hello, {user_name}!")# Create a simple calculator
def calculator():
print("Simple Calculator")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice = input("Enter choice (1-4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
result = num1 + num2
print(f"{num1} + {num2} = {result}")
elif choice == '2':
result = num1 - num2
print(f"{num1} - {num2} = {result}")
elif choice == '3':
result = num1 * num2
print(f"{num1} * {num2} = {result}")
elif choice == '4':
if num2 != 0:
result = num1 / num2
print(f"{num1} / {num2} = {result}")
else:
print("Error: Division by zero")
else:
print("Invalid choice")
# Run the calculator
calculator()Test your understanding of this topic:
Explore Python's built-in data structures including lists, tuples, dictionaries, and sets for efficient data organization.
Content by: Krish Dadhaniya
Python Django Developer
Python provides several built-in data structures that are essential for organizing and manipulating data efficiently.
# Lists - ordered, mutable
fruits = ["apple", "banana", "orange"]
print(fruits[0]) # apple
print(fruits[-1]) # orange
# List operations
fruits.append("grape")
fruits.insert(1, "mango")
fruits.remove("banana")
fruits.pop() # removes last item
# List comprehension
squares = [x ** 2 for x in range(10)]
even_numbers = [x for x in range(20) if x % 2 == 0]
# Nested lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Tuples - ordered, immutable
coordinates = (10, 20)
person = ("John", 25, "Developer")
# Dictionaries - key-value pairs
person_info = {
"name": "John",
"age": 25,
"city": "New York",
"skills": ["Python", "Django", "React"]
}
# Accessing dictionary values
print(person_info["name"])
print(person_info.get("age", "Not found"))
# Adding/updating items
person_info["email"] = "john@example.com"
person_info["age"] = 26
# Sets - unordered, unique elements
unique_numbers = {1, 2, 3, 4, 5}
unique_numbers.add(6)
unique_numbers.remove(1)
# Set operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union = set1 | set2
intersection = set1 & set2
difference = set1 - set2# Student Grade Manager using data structures
class GradeManager:
def __init__(self):
self.students = {} # Dictionary to store student data
def add_student(self, name, grades):
"""Add a student with their grades"""
if name not in self.students:
self.students[name] = grades
print(f"Added student: {name}")
else:
print(f"Student {name} already exists")
def get_average(self, name):
"""Calculate average grade for a student"""
if name in self.students:
grades = self.students[name]
return sum(grades) / len(grades)
return None
def get_top_student(self):
"""Find student with highest average"""
if not self.students:
return None
top_student = None
top_average = -1
for name, grades in self.students.items():
avg = sum(grades) / len(grades)
if avg > top_average:
top_average = avg
top_student = name
return top_student, top_average
def display_all_students(self):
"""Display all students and their averages"""
print("\nStudent Grades Summary:")
print("-" * 30)
for name, grades in self.students.items():
avg = sum(grades) / len(grades)
print(f"{name}: {grades} (Avg: {avg:.2f})")
# Usage example
manager = GradeManager()
manager.add_student("Alice", [85, 90, 88, 92])
manager.add_student("Bob", [78, 85, 80, 88])
manager.add_student("Charlie", [92, 95, 89, 91])
manager.display_all_students()
print(f"\nTop student: {manager.get_top_student()}")Test your understanding of this topic:
Master Python functions, control flow structures, and error handling for writing reusable and robust code.
Content by: Manali Trivedi
Python Django Developer
Functions are reusable blocks of code that perform specific tasks. They help organize code and make it more maintainable.
# Basic 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", 25
# Lambda functions (anonymous functions)
square = lambda x: x ** 2
add = lambda x, y: x + y
# Control flow
def check_number(num):
if num > 0:
return "Positive"
elif num < 0:
return "Negative"
else:
return "Zero"
# Loops
# For loop
for i in range(5):
print(i)
# For loop with enumerate
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# While loop
count = 0
while count < 5:
print(count)
count += 1
# List comprehension with condition
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
# Error handling
def divide_numbers(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
return "Error: Division by zero"
except TypeError:
return "Error: Invalid input types"
finally:
print("Division operation completed")
# Example usage
print(greet("Alice"))
print(greet_with_title("Bob", "Dr."))
name, age = get_name_and_age()
print(f"{name} is {age} years old")
print(square(5))
print(add(3, 4))# Password validation function
def validate_password(password):
"""
Validate password strength
Returns: (is_valid, message)
"""
if len(password) < 8:
return False, "Password must be at least 8 characters long"
if not any(c.isupper() for c in password):
return False, "Password must contain at least one uppercase letter"
if not any(c.islower() for c in password):
return False, "Password must contain at least one lowercase letter"
if not any(c.isdigit() for c in password):
return False, "Password must contain at least one number"
if not any(c in "!@#$%^&*()_+-=[]{}|;:,.<>?" for c in password):
return False, "Password must contain at least one special character"
return True, "Password is strong!"
def test_passwords():
"""Test various passwords"""
test_cases = [
"weak",
"WeakPassword",
"WeakPassword123",
"StrongPassword123!",
"12345678",
"abcdefgh"
]
print("Password Validation Results:")
print("-" * 40)
for password in test_cases:
is_valid, message = validate_password(password)
status = "✓ VALID" if is_valid else "✗ INVALID"
print(f"{status}: {password}")
print(f" {message}\n")
# Run the password validator
test_passwords()Test your understanding of this topic:
Learn object-oriented programming concepts in Python, including classes, inheritance, encapsulation, and polymorphism.
Content by: Aditya Bhatt
Python Django Developer
Object-Oriented Programming (OOP) is a programming paradigm that uses objects to design applications and computer programs.
# Basic class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name}"
def get_age(self):
return self.age
def have_birthday(self):
self.age += 1
return f"Happy birthday! You are now {self.age} years old"
# Creating objects
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
print(person1.greet())
print(person2.get_age())
print(person1.have_birthday())
# Inheritance
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def study(self):
return f"{self.name} is studying"
def get_info(self):
return f"Student {self.name} (ID: {self.student_id}) is {self.age} years old"
# Encapsulation
class BankAccount:
def __init__(self, account_number, balance=0):
self._account_number = account_number # Protected
self.__balance = balance # Private
def deposit(self, amount):
if amount > 0:
self.__balance += amount
return f"Deposited ${amount}. New balance: ${self.__balance}"
return "Invalid amount"
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
return f"Withdrew ${amount}. New balance: ${self.__balance}"
return "Insufficient funds"
def get_balance(self):
return self.__balance
# Polymorphism
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Woof!"
class Cat(Animal):
def make_sound(self):
return "Meow!"
# Using polymorphism
animals = [Dog(), Cat()]
for animal in animals:
print(animal.make_sound())
# Example usage
student = Student("Charlie", 20, "S12345")
print(student.study())
print(student.get_info())
account = BankAccount("123456789", 1000)
print(account.deposit(500))
print(account.withdraw(200))
print(f"Balance: ${account.get_balance()}")# Library Management System using OOP
class Book:
def __init__(self, title, author, isbn, available=True):
self.title = title
self.author = author
self.isbn = isbn
self.available = available
def __str__(self):
status = "Available" if self.available else "Borrowed"
return f"'{self.title}' by {self.author} - {status}"
class Library:
def __init__(self):
self.books = []
self.borrowed_books = {}
def add_book(self, book):
self.books.append(book)
print(f"Added book: {book.title}")
def borrow_book(self, isbn, borrower):
for book in self.books:
if book.isbn == isbn and book.available:
book.available = False
self.borrowed_books[isbn] = borrower
print(f"'{book.title}' borrowed by {borrower}")
return True
print(f"Book with ISBN {isbn} not available")
return False
def return_book(self, isbn):
if isbn in self.borrowed_books:
for book in self.books:
if book.isbn == isbn:
book.available = True
borrower = self.borrowed_books.pop(isbn)
print(f"'{book.title}' returned by {borrower}")
return True
print(f"Book with ISBN {isbn} not found in borrowed books")
return False
def search_book(self, title):
results = []
for book in self.books:
if title.lower() in book.title.lower():
results.append(book)
return results
def display_books(self):
print("\nLibrary Catalog:")
print("-" * 50)
for book in self.books:
print(book)
# Usage example
library = Library()
# Add books
library.add_book(Book("Python Programming", "John Smith", "123456"))
library.add_book(Book("Django Web Development", "Jane Doe", "123457"))
library.add_book(Book("Data Science with Python", "Bob Johnson", "123458"))
# Display all books
library.display_books()
# Borrow and return books
library.borrow_book("123456", "Alice")
library.borrow_book("123457", "Bob")
library.return_book("123456")
# Search for books
python_books = library.search_book("Python")
print("\nPython books found:")
for book in python_books:
print(f" - {book.title}")Test your understanding of this topic:
Learn to work with files, handle exceptions, and organize code using modules and packages for Django development.
Content by: Manali Trivedi
Python Django Developer
Python provides built-in functions and methods for reading, writing, and manipulating files. Understanding file handling is crucial for web development.
# Writing to a file
def write_to_file(filename, content):
try:
with open(filename, 'w') as file:
file.write(content)
print(f"Successfully wrote to {filename}")
except IOError as e:
print(f"Error writing to file: {e}")
# Reading from a file
def read_from_file(filename):
try:
with open(filename, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
print(f"File {filename} not found")
return None
except IOError as e:
print(f"Error reading file: {e}")
return None
# Appending to a file
def append_to_file(filename, content):
try:
with open(filename, 'a') as file:
file.write("\n" + content)
print(f"Successfully appended to {filename}")
except IOError as e:
print(f"Error appending to file: {e}")
# Working with CSV files
import csv
def write_csv(filename, data):
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
print(f"CSV file {filename} created successfully")
def read_csv(filename):
data = []
with open(filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
data.append(row)
return data
# Example usage
sample_data = [
['Name', 'Age', 'City'],
['John', '25', 'New York'],
['Alice', '30', 'London'],
['Bob', '35', 'Paris']
]
write_csv('people.csv', sample_data)
csv_content = read_csv('people.csv')
print("CSV content:", csv_content)# Log File Analyzer
import re
from datetime import datetime
class LogAnalyzer:
def __init__(self):
self.log_entries = []
def parse_log_line(self, line):
"""Parse a log line and extract information"""
# Example log format: [2024-01-15 10:30:45] INFO: User login successful
pattern = r'\[(.*?)\] (\w+): (.+)'
match = re.match(pattern, line.strip())
if match:
timestamp_str, level, message = match.groups()
try:
timestamp = datetime.strptime(timestamp_str, '%Y-%m-%d %H:%M:%S')
return {
'timestamp': timestamp,
'level': level,
'message': message
}
except ValueError:
return None
return None
def load_log_file(self, filename):
"""Load and parse log file"""
try:
with open(filename, 'r') as file:
for line in file:
entry = self.parse_log_line(line)
if entry:
self.log_entries.append(entry)
print(f"Loaded {len(self.log_entries)} log entries")
except FileNotFoundError:
print(f"Log file {filename} not found")
def get_entries_by_level(self, level):
"""Get all entries of a specific log level"""
return [entry for entry in self.log_entries if entry['level'] == level.upper()]
def get_entries_by_time_range(self, start_time, end_time):
"""Get entries within a time range"""
return [entry for entry in self.log_entries
if start_time <= entry['timestamp'] <= end_time]
def generate_summary(self):
"""Generate summary statistics"""
if not self.log_entries:
return "No log entries to analyze"
levels = {}
for entry in self.log_entries:
level = entry['level']
levels[level] = levels.get(level, 0) + 1
summary = "Log Analysis Summary:\n"
summary += "-" * 30 + "\n"
summary += f"Total entries: {len(self.log_entries)}\n"
summary += f"Time range: {self.log_entries[0]['timestamp']} to {self.log_entries[-1]['timestamp']}\n"
summary += "\nEntries by level:\n"
for level, count in levels.items():
summary += f" {level}: {count}\n"
return summary
# Create sample log file
sample_logs = [
"[2024-01-15 10:30:45] INFO: User login successful",
"[2024-01-15 10:31:12] INFO: Database connection established",
"[2024-01-15 10:31:45] WARNING: High memory usage detected",
"[2024-01-15 10:32:00] ERROR: Database connection failed",
"[2024-01-15 10:32:15] INFO: Retrying database connection",
"[2024-01-15 10:32:30] INFO: Database connection restored"
]
with open('sample.log', 'w') as f:
for log in sample_logs:
f.write(log + "\n")
# Analyze the log file
analyzer = LogAnalyzer()
analyzer.load_log_file('sample.log')
# Generate summary
print(analyzer.generate_summary())
# Get specific entries
error_entries = analyzer.get_entries_by_level('ERROR')
print(f"\nError entries: {len(error_entries)}")
for entry in error_entries:
print(f" {entry['timestamp']}: {entry['message']}")Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Continue to Module 2