Friday, 28 August 2026

๐Ÿš€ DAY 105/150 – Number guessing game

 



๐Ÿš€ Day 105/150 – Number Guessing Game in Python


A Number Guessing Game is a simple and fun Python project that helps beginners understand **random numbers, user input, conditional statements, loops, and comparison operators**.

In this post, we'll explore three different ways to build a Number Guessing Game in Python — from a basic version to a version with hints and limited attempts.


Method 1 – Basic Guess


The simplest version generates a random number between 1 and 10 and asks the user to guess it.


import random n = random.randint(1, 10) g = int(input("Guess: ")) print("Correct!" if g == n else "Wrong!")


Sample Output

Guess: 7
Correct!

Explanation

`import random` imports Python's random module.

`random.randint(1, 10)` generates a random integer between 1 and 10.

`input()` takes the user's guess.

`int()` converts the entered value into an integer.

The conditional expression checks whether the guess is equal to the generated number.

If both numbers match, `"Correct!"` is displayed; otherwise, `"Wrong!"` is displayed.

This is the easiest version and is perfect for understanding the basic concept.


Method 2 – Guess With Hint


We can make the game more interactive by telling the player whether their guess is too high or too low.

import random n = random.randint(1, 10) g = int(input("Guess: ")) if g < n: print("Too Low!") elif g > n: print("Too High!") else: print("Correct!")











Sample Output


Guess: 4
Too Low!


Explanation

The program first generates a random number between 1 and 10.

The player enters a guess.

If the guess is smaller than the secret number, `"Too Low!"` is displayed.

If the guess is greater than the secret number, `"Too High!"` is displayed.

If neither condition is true, the guess must be correct, so `"Correct!"` is displayed.

This version introduces **if, elif, and else**, making the game more interactive.


Method 3 – Number Guessing Game With 3 Attempts

We can make the game more challenging by giving the player only three attempts.

import random n = random.randint(1, 10) for i in range(3): g = int(input("Guess: ")) if g == n: print("๐ŸŽ‰ Correct!") break else: print("❌ Game Over!")











Sample Output

Guess: 3
Guess: 8
Guess: 6
๐ŸŽ‰ Correct!


Explanation

`random.randint(1, 10)` generates the secret number.

`for i in range(3)` allows the player to make a maximum of three guesses.

Inside the loop, the user enters a guess.

If the guess matches the secret number, `"๐ŸŽ‰ Correct!"` is displayed.

The `break` statement immediately stops the loop when the correct answer is found.

The `else` block belongs to the `for` loop. It executes only when the loop finishes all three attempts without encountering `break`.

If the player fails all three attempts, `"❌ Game Over!"` is displayed.

This version introduces an important Python concept: **`for...else`**.

---

Comparison of Methods


| Method                  | Best For                               |
| ---------------          | -------------------------------------- |
| Basic Guess           | Understanding random numbers and input |
| Guess With Hint     | Learning conditional statements        |
| 3 Attempts              | Practicing loops and `break`           |

๐Ÿ”ฅ Key Takeaways


* `random.randint()` can be used to generate a random number.
* `input()` allows the player to enter a guess.
* `if`, `elif`, and `else` help compare the user's guess with the secret number.
* `for` loops can be used to provide multiple attempts.
* `break` stops the game when the correct number is guessed.
* Python's `for...else` can detect when all attempts are completed without success.
* Number Guessing Game is a great beginner project for practicing Python fundamentals.

๐Ÿš€ **Stay tuned for Day 106 of the #150DaysOfPython series!**







๐Ÿš€ Day 100/150 – Decorator Example in Python


 

๐Ÿš€ Day 100/150 – Decorator Example in Python

A decorator is a special function in Python that allows you to add extra functionality to another function without modifying its original code. Decorators are commonly used for logging, authentication, timing functions, and more.

In this post, we'll explore four common examples of decorators in Python.


Method 1 – Basic Decorator

Create a simple decorator that prints a message before calling a function.

def decorator(func): def wrapper(): print("Before the function is called") func() return wrapper @decorator def greet(): print("Hello, World!") greet()









Output

Before the function is called 
Hello, World!

Explanation

  • decorator() accepts a function as an argument.

  • wrapper() adds extra functionality before calling the original function.

  • @decorator applies the decorator to greet().

  • Calling greet() actually executes wrapper().


Method 2 – Decorator with Function Arguments

Decorators can also work with functions that take parameters.

def decorator(func): def wrapper(name): print("Welcome!") func(name) return wrapper @decorator def greet(name): print("Hello,", name) greet("Alice")











Output
Welcome!
Hello, Alice

Explanation

  • wrapper(name) accepts the argument passed to greet().

  • It prints a welcome message before calling the original function.

  • The original function receives the same argument.


Method 3 – Decorator that Executes Code Before and After

A decorator can execute code both before and after the original function.

def decorator(func): def wrapper(): print("Starting...") func() print("Finished!") return wrapper @decorator def task(): print("Task is running") task()










Output

Starting... 
Task is running 
Finished!

Explanation

  • The decorator prints "Starting...".

  • It then calls the original function.

  • After the function finishes, it prints "Finished!".

  • This is useful for logging and monitoring function execution.


Method 4 – Taking User Input

Use a decorator with a function that accepts user input.

def decorator(func): def wrapper(name): print("Welcome to Python!") func(name) return wrapper @decorator def greet(name): print("Hello,", name) name = input("Enter your name: ") greet(name)












Sample Input

Sam

Output

Welcome to Python! 
Hello, Sam

Explanation

  • The user enters a name.

  • The decorator displays a welcome message.

  • The original function greets the user using the entered name.


Comparison of Methods

MethodBest For
Basic DecoratorUnderstanding how decorators work
Decorator with ArgumentsFunctions that accept parameters
Before and After ExecutionLogging and monitoring
User InputInteractive programs

๐Ÿ”ฅ Key Takeaways

  • A decorator adds extra functionality to a function without changing its original code.

  • Decorators are created using functions that return another function.

  • The @decorator syntax is used to apply a decorator.

  • Decorators can work with functions that have parameters.

  • They are commonly used for logging, authentication, timing, caching, and validation.

Stay tuned for Day 101 of the #150DaysOfPython series! ๐Ÿš€

Python Coding challenge - Day 1192| What is the output of the following Python Code?


Code Explanation:

๐Ÿ”น 1. Creating a List
nums = [2, 4, 6, 8]
✅ Explanation:

A list named nums is created containing four numbers.

Current list:

[2, 4, 6, 8]

Visual:

Index : 0  1  2  3

Value : 2  4  6  8

๐Ÿ”น 2. Calling all()
result = all(
✅ Explanation:
all() is a built-in Python function.
It checks whether every element in an iterable is True.
If all values are True, it returns True.
If even one value is False, it immediately returns False.

Syntax:

all(iterable)


๐Ÿ”น 3. Generator Expression
x % 2 == 0
for x in nums
✅ Explanation:

This is a generator expression.

It checks every number in the list.

Condition:

x % 2 == 0

means:

Is the number even?

Equivalent loop:

for x in nums:
    print(x % 2 == 0)

๐Ÿ”น 4. First Iteration

Current value:

x = 2

Calculation:

2 % 2

Result:

0

Condition:

0 == 0

Result:

True ✅

๐Ÿ”น 5. Second Iteration

Current value:

x = 4

Calculation:

4 % 2

Result:

0

Condition:

0 == 0

Result:

True ✅

๐Ÿ”น 6. Third Iteration

Current value:

x = 6

Calculation:

6 % 2

Result:

0

Condition:

0 == 0

Result:

True ✅

๐Ÿ”น 7. Fourth Iteration

Current value:

x = 8

Calculation:

8 % 2

Result:

0

Condition:

0 == 0

Result:

True ✅

๐Ÿ”น 8. Final Decision of all()

Results obtained:

True
True
True
True

Since every value is True, all() returns:

True

Stored in:

result

Current state:

result = True

๐Ÿ”น 9. Printing the Result
print(result)
✅ Explanation:

Python prints the value stored in result.

Output:

True

๐ŸŽฏ Final Output
True

Books : Application of Python in Audio and Video Processing

Python Automation Cookbook: 100+ New and Updated Recipes for Scalable Workflows, MCP Integrations, and AI-Powered Automation

 


If you are a Python developer looking to move beyond writing simple scripts and start building practical, scalable automation workflows, Python Automation Cookbook – Third Edition by Jaime Buelta is a book worth exploring.

This third edition expands the cookbook approach with updated recipes and new material focused on AI, MCP, and intelligent automation.

๐Ÿ“– What Is the Book About?

Python Automation Cookbook takes a practical, recipe-based approach to automation. Instead of focusing only on theory, the book shows how Python can be used to solve real-world automation problems through reusable techniques and examples.

The book progresses from fundamental Python automation concepts toward more advanced topics involving web scraping, APIs, system operations, testing, AI models, MCP, and AI agents.

๐Ÿš€ Key Topics Covered

Some of the major areas covered include:

  • Python automation fundamentals
  • Working with files and directories
  • System and command-line automation
  • Web scraping
  • API integration
  • Network automation
  • Testing and debugging
  • Scalable automation workflows
  • Calling AI models from Python
  • Model Context Protocol (MCP)
  • AI-powered agents
  • Business workflow automation
  • Generative AI-assisted development

๐Ÿค– Why the AI Content Matters

One of the most interesting aspects of this edition is its focus on AI-powered automation.

Traditional automation generally follows predefined rules:

Input → Python Script → Rules → Output

AI-powered automation can introduce another layer:

Input → Python → AI Model → Decision → Action

This allows developers to build workflows that can interpret information, make decisions, interact with external systems, and automate more complex tasks.

The inclusion of AI models, MCP, and intelligent agents makes this edition particularly relevant for developers interested in the future of automation.

๐Ÿงฉ The Cookbook Format

The cookbook-style structure is one of the book's biggest strengths.

You don't necessarily have to read the entire book from beginning to end. Instead, you can use individual recipes as a reference when you encounter a particular automation problem.

This makes the book especially useful for developers who prefer learning by building and experimenting with practical examples.

๐Ÿ‘จ‍๐Ÿ’ป Who Should Read This Book?

This book is particularly useful for:

  • Python developers
  • Automation engineers
  • DevOps professionals
  • System administrators
  • Backend developers
  • AI/ML developers
  • Developers exploring MCP
  • Developers interested in AI agents
  • Python programmers looking for project ideas

It is better suited to readers who already have a basic understanding of Python rather than complete beginners.

⭐ My Review

Overall Rating: 4.5/5

The biggest strength of Python Automation Cookbook – Third Edition is its practical approach.

Python is one of the most popular languages for automation, but knowing Python syntax is only the beginning. The real value comes from learning how to connect Python with files, operating systems, APIs, websites, external services, and now AI systems.

This book provides a useful bridge between Python programming and real-world automation.

The addition of AI-focused content is another major advantage. Developers can learn how traditional automation techniques can be combined with modern AI capabilities to create smarter workflows.

The book is also substantial enough to work as a long-term reference, rather than something you simply read once.

๐Ÿ‘ What I Like

  • Practical, recipe-based approach
  • Focus on real-world automation
  • Covers traditional Python automation
  • Includes modern AI automation concepts
  • Introduces MCP and AI agents
  • Useful for developers with existing Python knowledge
  • Good progression from fundamentals to advanced topics
  • Works well as a reference book

⚠️ Things to Keep in Mind

This isn't a book I'd recommend as your first-ever Python resource. Beginners should learn Python fundamentals before diving into many of the recipes.

Also, AI, MCP, and agent technologies are evolving rapidly. Some AI-specific approaches may change over time, while the fundamental Python automation techniques are likely to remain useful much longer.

Hard Copy: Python Automation Cookbook: 100+ new and updated recipes for scalable workflows, MCP integrations, and AI-powered automation


๐ŸŽฏ Final Verdict

Python Automation Cookbook – Third Edition is a strong choice for developers who want to turn their Python skills into useful automation systems.

What makes this edition especially interesting is the combination of Python automation + AI + MCP + intelligent agents.

If you want to learn how Python can automate repetitive tasks, connect different systems, work with APIs, scrape information, and interact with modern AI technologies, this book is a valuable addition to your technical library.

Recommended for: Python developers, automation enthusiasts, DevOps professionals, and developers interested in AI-powered workflows.

Rating: ⭐ 4.5/5

Python Coding Challenge - Question with Answer (ID 280826)

 


Explanation:

1. Create the Set
x = {i*i % 5 for i in range(10)}

This is a set comprehension. Python will calculate i*i % 5 for every value of i from 0 to 9.

2. range(10)
range(10)

Generates numbers from:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

So i takes each of these values one by one.

3. Calculate i*i % 5

Now Python calculates the expression for each value:

i i*i i*i % 5
0 0 0
1 1 1
2 4 4
3 9 4
4 16 1
5 25 0
6 36 1
7 49 4
8 64 4
9 81 1

The resulting values are:

0, 1, 4, 4, 1, 0, 1, 4, 4, 1

4. Why Does the Set Remove Duplicates?

The { ... } syntax creates a set.

A set automatically keeps only unique values.

So:

0, 1, 4, 4, 1, 0, 1, 4

becomes:

{0, 1, 4}

Therefore:

x = {0, 1, 4}

5. len(x)
len(x)

len() counts the number of elements in the set.

The set contains:

0 → 1 element
1 → 1 element
4 → 1 element

So:

len(x) = 3

6. print()
print(len(x))

The calculated value 3 is displayed.

✅ Final Output
3

Book: Python for Cybersecurity

Thursday, 27 August 2026

Statistical Divergences between Densities of Truncated Exponential Families with Nested Supports: Duo Bregman and Duo Jensen Divergences (Free PDF)

Probability distributions are often compared using statistical divergences. These measures tell us how different two probability distributions are. One of the best-known examples is the Kullback–Leibler (KL) divergence, which is widely used in statistics, information theory, and Machine Learning.

The paper “Statistical Divergences between Densities of Truncated Exponential Families with Nested Supports: Duo Bregman and Duo Jensen Divergences” by Frank Nielsen explores what happens when the probability distributions being compared belong to truncated exponential families with nested supports. The work introduces new forms of divergence called duo Fenchel–Young, duo Bregman, and duo Jensen divergences.


Download the PDF for free: 
Statistical Divergences between Densities of Truncated Exponential Families with Nested Supports


What Are Exponential Families?

An exponential family is a broad class of probability distributions that can be represented using a common mathematical structure.

It includes important distributions such as:

  • Normal distributions
  • Exponential distributions
  • Poisson distributions
  • Gamma distributions
  • Beta distributions
  • Wishart distributions

The paper describes exponential families using parameters, sufficient statistics, and a log-normalizer (cumulant function).


What Is a Truncated Distribution?

A truncated distribution is created by restricting the possible values of a random variable to a particular region.

For example, a normal distribution normally has support:

(-∞, +∞)

If we only keep values greater than zero:

[0, +∞)

we obtain a truncated version of the distribution.

The paper uses the half-normal distribution as an example of a truncated exponential family whose support is contained within the support of the original normal family.


Understanding Nested Supports

The idea of nested support is central to the paper.

Suppose:

Support A ⊂ Support B

Then every possible value in A is also contained in B.

For example:

[0, +∞) ⊂ (-∞, +∞)

This relationship allows the paper to study divergences between distributions defined over related but different regions.


Kullback–Leibler Divergence

The KL divergence measures how one probability distribution differs from another.

It can be represented conceptually as:

Distribution P

Compare With Q

KL Divergence

A fundamental property is:

KL(P || Q) ≥ 0

and it becomes zero when the distributions are identical under the usual conditions. The paper uses KL divergence as the starting point for developing its generalized divergence formulas.


From KL Divergence to Bregman Divergence

For distributions belonging to the same exponential family, KL divergence has an important connection with Bregman divergence.

A Bregman divergence is generated by a convex function and measures a generalized notion of difference between two parameter points.

Conceptually:

Probability Distributions

Exponential Family

Convex Function

Bregman Divergence

This connection is one of the foundations of information geometry.


The Duo Bregman Idea

The interesting contribution of the paper is that when distributions come from different exponential families, particularly truncated families with nested supports, the ordinary Bregman formulation is no longer sufficient.

The paper introduces a duo Fenchel–Young divergence, which can equivalently be expressed as a duo Bregman divergence. Under a majorization condition on the convex generators, the resulting divergence is guaranteed to be non-negative.

The idea can be summarized as:

Two Statistical Families

Two Convex Generators

Duo Divergence

Measure of Difference


Duo Jensen Divergence

The paper also studies skewed Bhattacharyya distances between truncated exponential families.

It shows that these distances can be represented using corresponding skewed duo Jensen divergences.

This creates another connection between:

Probability → Convexity → Divergences → Information Geometry


Truncated Normal Distributions

One practical mathematical example in the paper is the KL divergence between truncated normal distributions.

Normal distributions are extremely important in statistics and Machine Learning, so understanding how their divergence behaves after truncation is useful for probabilistic modeling.

The paper derives a formula expressing this KL divergence using the proposed duo divergence framework.


Why This Matters in Machine Learning

Comparing probability distributions is important in many areas of AI and Data Science.

For example:

  • Probabilistic Machine Learning
  • Generative models
  • Statistical inference
  • Distribution matching
  • Information geometry
  • Bayesian modeling
  • Anomaly detection

If two datasets or models produce different probability distributions, a suitable divergence can provide a quantitative measure of that difference.


Connection With Information Geometry

The paper sits at the intersection of several mathematical fields:

Probability Theory

Statistics

Convex Analysis

Information Geometry

Machine Learning

Information geometry treats probability distributions as geometric objects. Divergences such as Bregman and Jensen-type divergences can then be interpreted as ways of measuring relationships between these objects.


Why Convexity Is Important

Convex functions are central to the paper.

Convexity provides useful mathematical properties for defining divergences and optimization objectives.

For example, a convex function has the general shape:

Curve bends upward

and this structure allows us to construct meaningful measures of difference between parameter values.

The paper uses relationships between convex generators to establish non-negativity of its duo divergences.


A Simple Conceptual Example

Imagine two distributions:

P = Normal distribution restricted to [0, 5]

Q = Normal distribution restricted to [0, 10]

Their supports are nested:

[0, 5] ⊂ [0, 10]

We want to measure:

How different is P from Q?

The paper's framework provides a mathematical way to express such divergences using the corresponding exponential-family structures and convex generators.


Main Contributions

The paper's key contributions can be summarized as:

1. Duo Fenchel–Young Divergence

A generalized divergence for pairs of exponential-family structures.

2. Duo Bregman Divergence

An equivalent Bregman-style representation.

3. KL Divergence for Truncated Families

A framework for calculating KL divergence between truncated exponential-family distributions with nested supports.

4. Truncated Normal Example

A concrete formula for KL divergence between truncated normal distributions.

5. Duo Jensen Divergence

A connection between skewed Bhattacharyya distances and skewed duo Jensen divergences.


Who Should Read This Paper?

This paper is most suitable for readers interested in:

  • Advanced Data Science
  • Machine Learning
  • Probability
  • Statistics
  • Information Theory
  • Information Geometry
  • Convex Analysis
  • Mathematical AI

A background in probability, linear algebra, calculus, convexity, and exponential families will make the mathematics considerably easier to follow.


Download the PDF for free: 
Statistical Divergences between Densities of Truncated Exponential Families with Nested Supports

Final Verdict

Statistical Divergences between Densities of Truncated Exponential Families with Nested Supports is a mathematically advanced paper that extends familiar ideas such as KL divergence and Bregman divergence to a more complicated setting involving truncated exponential families with nested supports.

Its central progression can be summarized as:

Exponential Families

Truncated Distributions

KL Divergence

Duo Fenchel–Young Divergence

Duo Bregman Divergence

Duo Jensen Divergence

The paper is particularly valuable for understanding how convex geometry and probability theory can work together to create new ways of comparing statistical distributions.

Python Coding challenge - Day 1130| What is the output of the following Python Code?




Code Explanation: 

๐Ÿ”น 1. Class Definition
class Test:

✅ Explanation:
A class named Test is created.
This class contains a variable and two special methods.

๐Ÿ”น 2. Class Variable
x = 10

✅ Explanation:
x is a class variable.
It is shared by all objects of the class.
Can be accessed using:
Test.x
cls.x (inside class methods)

๐Ÿ”น 3. Class Method
@classmethod
def show(cls):
    return cls.x

✅ Explanation:
@classmethod decorator makes this method a class method.
It takes cls (class reference) as the first parameter.
๐Ÿ” What happens:
cls refers to the class (Test)
cls.x → accesses class variable x
✔️ Returns:
10

๐Ÿ”น 4. Static Method
@staticmethod
def display():
    return Test.x

✅ Explanation:
@staticmethod defines a method that:
Does NOT take self or cls
Acts like a normal function inside class

๐Ÿ” What happens:
Directly accesses class using:
Test.x

✔️ Returns:
10

๐Ÿ”น 5. Calling Methods
print(Test.show(), Test.display())

✅ What happens:
➤ Test.show()
Calls class method
cls = Test
Returns:
10
➤ Test.display()
Calls static method
Returns:
10

๐ŸŽฏ Final Output
10 10

Python Coding challenge - Day 1111| What is the output of the following Python Code?

 




Code Explanation:

1️⃣ Importing Threading Module

import threading

Explanation

Imports Python’s built-in threading module.
Used to create and manage threads.

2️⃣ Defining Task Function
def task():
    print("X")

Explanation

A function task is defined.
This will run inside a thread.
It simply prints:
X

3️⃣ Creating a Thread Object
t = threading.Thread(target=task)

Explanation

A thread t is created.
target=task means:
When thread runs → it executes task().

4️⃣ Starting the Thread (First Time)
t.start()

Explanation

Starts execution of the thread.
Internally calls:
task()

๐Ÿ‘‰ Output:

X

5️⃣ Waiting for Thread to Finish
t.join()

Explanation

Main thread waits until thread t completes.
Ensures thread has fully finished execution.

6️⃣ Starting the Same Thread Again ❌
t.start()

Explanation ⚠️ IMPORTANT

You are trying to restart the same thread object.
This is NOT allowed in Python.

๐Ÿ‘‰ A thread can be started only once.

❌ What Happens?
Python raises an error:
RuntimeError: threads can only be started once

๐Ÿ“ค Final Output
X
RuntimeError

Python Coding Challenge - Question with Answer (ID 270826)

 


Explanation:

๐Ÿ’ป Code
x = [] or [1] or [2]
print(x)

๐Ÿ”น Line 1: x = [] or [1] or [2]
x = [] or [1] or [2]

Python evaluates the values from left to right.

๐Ÿ”น Step 1: []
[]

[] is an empty list, so Python considers it Falsy.

Therefore, Python moves to the next value.

๐Ÿ”น Step 2: [1]
[1]

[1] is a non-empty list, so it is Truthy.

Python stops here because or has already found a Truthy value.

๐Ÿ”น Step 3: [2]
[2]

This value is never evaluated as the result, because Python already found [1].

๐Ÿ”น Line 2: print(x)
print(x)

x contains the first Truthy value, which is [1].

๐ŸŽฏ Output
[1]

Book: 100 Python Automation Projects for Smart Developers

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (340) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (31) Azure (12) BI (10) book (1) Books (347) Bootcamp (14) C (78) C# (12) C++ (83) cloud (1) Course (89) Coursera (302) Cybersecurity (36) data (10) Data Analysis (46) Data Analytics (31) data management (16) Data Science (422) Data Strucures (18) Deep Learning (217) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (24) Finance (13) flask (4) flutter (1) FPL (17) Generative AI (77) Git (13) Google (54) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (43) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (393) Meta (24) MICHIGAN (5) microsoft (13) Nvidia (8) Pandas (16) PHP (20) Projects (34) Python (1363) Python Coding Challenge (1228) Python Library (1) Python Mathematics (13) Python Mistakes (51) Python Quiz (613) Python Tips (104) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (21) SQL (55) Udemy (20) UX Research (1) web application (11) Web development (9) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)