CodeCraft Innovation

CodeCraft Innovation Software development expertise, coding education, ethical hacking focus, and IT advice services.

The belief that complex systems require armies of designers and programmers is wrong. A system that is not understood in its entirety, or at least to a significant degree of detail by a single individual, should probably not be built.

03/05/2025

*Roadmap to learn HTML & CSS Roadmap in 1 month*

*Week 1: HTML Basics*

What is HTML and how the web works

Basic page structure: , , ,

Headings ( to ), Paragraphs, Links, Images

Lists (, , ), Tables

Forms: , , , buttons

Semantic HTML: , , , , ,

> Mini Project: Create a simple personal profile page using only HTML.

*Week 2: CSS Basics*

What is CSS? Inline vs Internal vs External

CSS Syntax: Selectors, Properties, Values

Colors, Units (px, %, em, rem), Fonts

Box Model (margin, border, padding, content)

display: block, inline, inline-block

position: static, relative, absolute, fixed

> Mini Project: Style your HTML profile page with colors, fonts, and spacing.

*Week 3: Layout with CSS*

Flexbox (justify-content, align-items, flex-wrap)

Grid (grid-template-columns, grid-gap, etc.)

Float & Clear (basic understanding)

z-index, overflow

> Mini Project: Build a responsive 3-column layout using Flexbox or Grid.

*Week 4: Responsive Design*

Media Queries

Mobile-first design

Units: vh, vw, em, rem for responsiveness

Using responsive images and typography

> Mini Project: Build a responsive landing page (like a product page or blog homepage)

React with ❤️ if you want similar roadmap for Javascript

*ENJOY LEARNING* 👍👍

03/05/2025

Now, let's move to the next important topic in the Python Learning Series:

*Generators & Iterators*

*1. What are Iterators?*

An iterator is an object that allows you to iterate over a sequence of values. It implements two special methods:

__iter__() → Returns the iterator object itself

__next__() → Returns the next value; raises StopIteration when exhausted

*Example:*

my_list = [1, 2, 3]
iterator = iter(my_list)

print(next(iterator)) # 1
print(next(iterator)) # 2
print(next(iterator)) # 3

*2. What are Generators?*

A generator is a simpler way to create iterators using functions and the yield keyword.

*Key Differences:*

- Uses yield instead of return

- Maintains state between calls

- More memory-efficient for large data

*Example:*

def countdown(n):
while n > 0:
yield n
n -= 1

for i in countdown(3):
print(i)

*Output:*

3
2
1

*3. Generator Expressions*

squares = (x*x for x in range(5))

for num in squares:
print(num)

This is similar to a list comprehension but returns a generator instead of a list.

*4. Why Use Generators?*

- Efficient for reading large files or processing streams

- Lazy evaluation: doesn't store the whole sequence in memory

- Great for pipelines, streaming APIs, etc.

*If you need to create an iterable class, override __iter__() and __next__().*
*If you need quick iteration over a large sequence — use yield.*

*React with ❤️ once you're ready for the next quiz on decorators*

03/05/2025

Now, let's move to the next important topic in the Python Learning Series:

*Decorators*

A decorator is a function that adds extra functionality to another function without modifying its actual code.

Think of it like wrapping a gift — the gift (function) stays the same, but you add some nice packaging (extra features).

*How Does It Work?*

In Python, functions are first-class objects — they can be passed around just like variables. This makes decorators possible.

*Syntax Example:*

def greet(func):
def wrapper():
print("Hello!")
func()
print("Have a nice day!")
return wrapper


def say_name():
print("I am learning Python.")

say_name()

*Output:*

Hello!
I am learning Python.
Have a nice day!

Here, is the decorator that wraps say_name().

*Without Using @ Symbol:*

def greet(func):
def wrapper():
print("Hello!")
func()
print("Have a nice day!")
return wrapper

def say_name():
print("I am learning Python.")

say_name = greet(say_name)
say_name()

Works the same way!

*Where Are Decorators Used?*

- Logging

- Access control

- Timing functions

- Modifying behavior for frameworks (like Flask, Django)

*React with ❤️ once you're ready for the next quiz on decorators*

02/05/2025

*Now, let's move to the next topic in the Python Learning Series*

*Inheritance and Polymorphism*

*What is Inheritance?*

Inheritance is an important concept in Object-Oriented Programming (OOP). It allows one class to inherit the properties and methods of another class. This helps us create a hierarchy of classes, where a base class (or parent class) is extended by one or more derived classes (child classes).

In simple terms, inheritance lets you reuse code by creating new classes based on existing ones.

*Real-World Example:*

Imagine you have a parent class called Animal and two child classes: Dog and Cat. The Dog and Cat classes inherit properties from the Animal class (like a name and age), and they can also add their specific behaviors (like bark for Dog and meow for Cat).

class Animal:
def __init__(self, name, age):
self.name = name
self.age = age

def speak(self):
return "Animal sound"

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

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

# Creating objects
dog = Dog("Buddy", 3)
cat = Cat("Whiskers", 2)

print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow!

*In the above example:*

The Animal class is the parent (or base) class.

Dog and Cat are child classes that inherit from Animal.

Both the Dog and Cat classes override the speak() method from Animal to provide specific behavior for each.

*What is Polymorphism?*

Polymorphism is another key concept in OOP that allows one method to behave differently based on the object it is acting upon. In simple terms, polymorphism means that you can call the same method on different objects, but each object may respond in its own way.

*Real-World Example:* In the case of our Animal classes, both Dog and Cat have a speak() method. Although the method name is the same, the implementation is different for each class (a dog barks and a cat meows).

# The same method name, but different behavior
def animal_sound(animal):
print(animal.speak())

# Calling polymorphism
animal_sound(dog) # Output: Woof!
animal_sound(cat) # Output: Meow!

*In the above example:*

The animal_sound() function calls the speak() method.

Depending on whether the object passed is a Dog or a Cat, it behaves differently.

This is an example of method overriding (a form of polymorphism).

*Types of Polymorphism in Python:*

*1. Method Overloading:* Python doesn’t support method overloading directly (i.e., defining multiple methods with the same name but different parameters), but you can achieve this by using default parameters or variable-length arguments.

class Example:
def greet(self, name="Guest"):
return f"Hello, {name}!"

obj = Example()
print(obj.greet()) # Output: Hello, Guest!
print(obj.greet("Alice")) # Output: Hello, Alice!

*2. Method Overriding:* As demonstrated earlier, method overriding occurs when a child class provides its own version of a method that is already defined in the parent class.

*How Inheritance and Polymorphism Work Together:*

Inheritance and polymorphism often work hand-in-hand in OOP. Inheritance allows a child class to inherit methods from a parent class, while polymorphism allows the child class to modify (or override) those methods.

class Animal:
def sound(self):
return "Some generic sound"

class Dog(Animal):
def sound(self):
return "Woof!"

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

# Create objects
animals = [Dog(), Cat()]

# Demonstrating polymorphism
for animal in animals:
print(animal.sound())

*Output:*

Woof!
Meow!

Here, even though both Dog and Cat are calling the same method (sound()), they respond differently. This is polymorphism in action, where the same method behaves differently based on the object.

*Key Takeaways:*

Inheritance allows a class to inherit attributes and methods from another class. This helps in code reuse and creating class hierarchies.

Polymorphism allows methods to behave differently based on the object it is called on. This helps create more flexible and extensible code.

*Common Interview Questions on Inheritance and Polymorphism:*

1. Explain inheritance and polymorphism in Python with examples.

2. What is method overriding? Can you give an example?

3. Can you explain multiple inheritance and its potential issues in Python?

4. How does polymorphism help in making a program more flexible?

5. What is the difference between a parent class and a child class?

6. How would you handle method overloading in Python

02/05/2025

Now, let's move to the next topic in the Python Learning Series.

*Classes and Objects*

*What is a Class?*

A class is a blueprint — just like an architect’s plan for building houses.

In Python, you create a class using the class keyword.

class Dog:
# This is a class
pass

This doesn't do much yet — it's just an empty plan.

*What is an Object?*

An object is something created from the class — like an actual house built from the plan.

my_dog = Dog()

Now, my_dog is an object (or instance) of the Dog class.

*Let’s Build a Useful Example*

*1. Define the Class*

class Dog:
def __init__(self, name, breed):
self.name = name # Attribute
self.breed = breed # Attribute

def bark(self):
print(f"{self.name} says: Woof!")

__init__() is a special method that runs automatically when you create an object.

self refers to the object being created.

name and breed are attributes.

*2. Create Objects*

dog1 = Dog("Bruno", "Labrador")
dog2 = Dog("Tommy", "Pug")

Now you’ve created two objects of the Dog class.

*3. Call Methods on Objects*

dog1.bark() # Output: Bruno says: Woof!
dog2.bark() # Output: Tommy says: Woof!

*Another Simple Example: Student Class*

class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade

def display_info(self):
print(f"Name: {self.name}, Grade: {self.grade}")

s1 = Student("Alice", "A")
s2 = Student("Bob", "B")

s1.display_info() # Output: Name: Alice, Grade: A
s2.display_info() # Output: Name: Bob, Grade: B

*Quick Recap:*

- Class: A blueprint or design for creating objects.

- Object: An instance created from the class.

- __init__: A special method (called constructor) that runs automatically when an object is created.

- self: Refers to the current object itself.

- Method: A function defined inside a class that performs an action on the object.

- Attribute: A variable that belongs to the object, usually defined inside __init__.

02/05/2025

Now, let’s move to the next topic in the Python Learning Series

*Working with Dates & Time* 📅⏰

*1. Importing the datetime module*

To work with dates and times, Python provides a built-in module called datetime.

import datetime

*2. Getting the current date and time*

from datetime import datetime

now = datetime.now()
print(now) # Shows full date and time
print(now.date()) # Only date part
print(now.time()) # Only time part

*3. Creating a specific date or time*

from datetime import datetime

my_birthday = datetime(1995, 8, 25) # Year, Month, Day
print(my_birthday)

You can also add hours, minutes, and seconds:

specific_time = datetime(2023, 10, 5, 15, 30, 45)

*4. Formatting Dates (strptime & strftime)*

strftime() — Convert datetime to string in a desired format.

now = datetime.now()
print(now.strftime("%Y-%m-%d")) # Output: 2025-05-01
print(now.strftime("%d/%m/%Y")) # Output: 01/05/2025

strptime() — Convert string back to a datetime object.

date_str = "01/05/2025"
date_obj = datetime.strptime(date_str, "%d/%m/%Y")
print(date_obj)

*5. Doing math with dates (timedelta)*

Use timedelta to add or subtract days, hours, etc.

from datetime import timedelta

today = datetime.now()
tomorrow = today + timedelta(days=1)
yesterday = today - timedelta(days=1)

print("Tomorrow:", tomorrow)
print("Yesterday:", yesterday)

You can also calculate the difference between two dates:

d1 = datetime(2025, 5, 10)
d2 = datetime(2025, 5, 1)
difference = d1 - d2
print(difference.days) # Output: 9

*How to calculate someone’s age*

dob = datetime(1998, 4, 15)
today = datetime.now()
age = today.year - dob.year

# Adjust if birthday hasn’t occurred yet this year

if (today.month, today.day) < (dob.month, dob.day):
age -= 1

print("Age:", age)

*Useful formatting codes for dates*

%Y – Full year (2025)

%y – Short year (25)

%m – Month (01-12)

%d – Day (01-31)

%H – Hour (00-23)

%M – Minute (00-59)

%S – Second (00-59)

This topic is super useful in automation, data analysis, and even web scraping.

02/05/2025

Now, let's move to the next important topic in the Python Learning Series

*Scope & Global Variables*

*1. What is Scope?*

Scope refers to the region in a program where a variable is recognized and can be used. There are different types of scopes in Python:

*Local Scope:* Refers to variables that are defined inside a function or block of code. These variables are accessible only within that function.

*Global Scope:* Refers to variables that are defined outside of any function. These variables are accessible from anywhere in the code, including inside functions.

*2. Global Variables*

A global variable is defined outside of all functions and is accessible throughout the program. However, to modify a global variable inside a function, you need to use the global keyword.

*Example:*

x = 10 # global variable

def my_function():
global x # using the global variable
x = 20 # modifying global variable

my_function()
print(x) # Output: 20

Without using the global keyword, Python would treat the variable as a local one inside the function.

*3. Local Variables*

Local variables are those defined inside a function. They are accessible only within that function.

*Example:*

def my_function():
x = 10 # local variable
print(x)

my_function()
# print(x) # Error: x is not defined outside the function

In the example above, x is a local variable and can't be accessed outside the function.

*4. Best Practices for Using Global Variables*

While global variables are useful, it's best to avoid using them excessively.

Over-reliance on global variables can lead to code that is harder to debug and maintain.

It's often better to pass variables to functions or return values from functions instead of modifying global variables directly.

02/05/2025

Let’s now understand the next useful concept in the Python Learning Series

*Modules and Packages*

These help you organize your code better and reuse it efficiently.

*1. What is a Module?*

A module is simply a .py file that contains Python definitions, functions, classes, or variables.

For example, if you have a file named math_utils.py:

def add(a, b):
return a + b

You can use it in another file like this:

import math_utils
print(math_utils.add(2, 3)) # Output: 5

You can also import specific parts:

from math_utils import add
print(add(2, 3))

*2. What is a Package?*

A package is a directory containing multiple related Python modules and an __init__.py file. This helps structure large projects.

*Example folder structure:*

myproject/

├── math_utils/
│ ├── __init__.py
│ └── operations.py

Then you can import like this:

from math_utils.operations import add

*3. Standard Modules You Should Know*

Python comes with many built-in modules. Here are a few:

math → Math operations

random → Generate random numbers

datetime → Work with dates and times

os → Interact with the operating system

sys → Access system-specific parameters

json → Handle JSON data

You can also install external modules using pip:

pip install requests

And then use it in your code:

import requests
response = requests.get('https://example.com')

This is an essential skill when your projects start growing. And you'll definitely use modules when working with APIs, web scraping, automation, or any real-world project.

This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.

02/05/2025

Let's now move to the next topic in the Python Learning Series:

*map(), filter(), and reduce() in Python*

These three functions are part of functional programming in Python and are often used for concise, clean, and readable code when working with lists or other iterable data.

*1. map(function, iterable)*

Applies a function to every item in the iterable.

nums = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, nums))
print(squares) # Output: [1, 4, 9, 16]

*2. filter(function, iterable)*

Returns only the items that evaluate to True from the iterable based on the function.

nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [2, 4, 6]

*3. reduce(function, iterable)*

Applies a function cumulatively to the items of the iterable.

*Note: You must import it from functools.*

from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(product) # Output: 24

These are powerful tools when used right. You'll see them often in interview questions and real-world code!

02/05/2025

Let's now move to the next topic in the Python Learning Series

*Lambda Functions in Python*

*What is a lambda function?*

It’s a small anonymous function that you define in a single line.

It’s mostly used when you need a simple function for a short time — especially with map(), filter(), or sorted().

*Syntax:*

lambda arguments: expression

It takes inputs (arguments) and returns the result of the expression.

*Example:*

square = lambda x: x * x
print(square(4)) # Output: 16

This is the same as:

def square(x):
return x * x

*Another example:*

add = lambda a, b: a + b
print(add(3, 5)) # Output: 8

*Why is it called “anonymous”?*

Because it doesn’t have a name like regular functions.
You just write it and use it directly.

*Where is it used?*

Often with functions like:

- map() — to apply a function to each item in a list

- filter() — to filter items from a list

- sorted() — to customize how to sort things

*Example with sorted():*

points = [(2, 3), (1, 9), (4, 1)]
points.sort(key=lambda x: x[1])
print(points) # Sorted by second element

*Why use lambda?*

- Saves space (no need to define full function)

- Makes code more readable in simple cases

*When NOT to use it:*

- When the function is complex — then use def for clarity.

02/05/2025

Hey guys,

Now that we’ve covered file handling, let’s move to an extremely important concept that every Python developer should know:

*Exception Handling*

*What are Exceptions?*

Exceptions are errors detected during ex*****on. Instead of crashing the program, Python allows us to handle these gracefully.

*For example:*

num = int(input("Enter a number: "))
print(10 / num)

If the user enters 0, it causes a ZeroDivisionError. If they enter something non-numeric, it causes a ValueError.

*How to Handle Exceptions:*

Python uses a try-except block:

try:
# risky code
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input. Please enter a number.")

try = "Try running this code..."

except = "If there's an error, do this instead."

*Optional Blocks:*

else: Runs if no exception occurs.

finally: Always runs, even if an exception is raised.

try:
f = open("test.txt", "r")
print(f.read())
except FileNotFoundError:
print("File not found!")
finally:
print("Execution finished.")

*You can remember this:*

- try: risky code

- except: handle specific problems - avoid using a generic except, rather, use specific exception types (like ValueError, ZeroDivisionError, FileNotFoundError)

- else: if no errors

- finally: always runs (even if there's an error)

02/05/2025

Let's now move to the next important topic in the Python Learning Series

*File Handling in Python*

*What is File Handling?*

File handling allows Python to read from and write to files—text files, CSVs, logs, etc.

It’s used in almost every real-world project: whether it's storing user data, reading configurations, or writing logs.

*Basic File Operations:*

*1. Open a file*

file = open("example.txt", "r") # 'r' for read mode

*2. Read from a file*

content = file.read()
print(content)

*3. Write to a file*

file = open("example.txt", "w") # 'w' for write mode
file.write("Hello, Python!")
file.close()

*4. Append to a file*

file = open("example.txt", "a") # 'a' for append mode
file.write("\nNew Line")

*5. Close the file*

file.close()

*Better Practice: Using with statement*

with open("example.txt", "r") as file:
content = file.read()
print(content)

This automatically closes the file after you're done reading or writing.

*Modes to Remember:*

- 'r' – read

- 'w' – write (overwrites)

- 'a' – append

- 'r+' – read & write

File handling is commonly tested in interviews and very useful in automation scripts and data processing tasks.

Address

Blantyre

Alerts

Be the first to know and let us send you an email when CodeCraft Innovation posts news and promotions. Your email address will not be used for any other purpose, and you can unsubscribe at any time.

Share