Tuesday, 7 April 2026

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

 


Code Explanation:

1️⃣ Importing dataclass
from dataclasses import dataclass

Explanation

Imports the dataclass decorator.
It auto-generates methods like __init__, __repr__, etc.

2️⃣ Applying @dataclass
@dataclass

Explanation

Converts class A into a dataclass.
Automatically creates constructor like:
def __init__(self, x=[]):
    self.x = x

⚠️ Important: x=[] is evaluated once, not per object.

3️⃣ Defining Class
class A:

Explanation

Defines class A.

4️⃣ Defining Attribute with Default Value
x: list = []

Explanation ⚠️ CRITICAL

x is given a default value of an empty list.
This list is shared across all instances.

๐Ÿ‘‰ Only ONE list is created in memory.

5️⃣ Creating First Object
a1 = A()

Explanation

a1.x refers to the shared list.

6️⃣ Creating Second Object
a2 = A()

Explanation

a2.x refers to the same shared list.

๐Ÿ‘‰ So:

a1.x is a2.x → True

7️⃣ Modifying List from a1
a1.x.append(1)

Explanation

Adds 1 to the shared list.

๐Ÿ‘‰ Now shared list becomes:

[1]

8️⃣ Printing from a2
print(a2.x)

Explanation

Since a2.x points to the same list:
[1]

๐Ÿ“ค Final Output
[1]

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

 


Code Explanation:

1️⃣ Importing Enum
from enum import Enum

Explanation

Imports the Enum class from Python’s enum module.
Used to create enumerations (named constants).

2️⃣ Defining Enum Class
class Color(Enum):

Explanation

Creates an enum class named Color.
It inherits from Enum.

3️⃣ Defining Enum Members
RED = 1
BLUE = 2

Explanation

Defines two enum members:
Color.RED → value 1
Color.BLUE → value 2

๐Ÿ‘‰ These are unique objects, not just numbers.

4️⃣ Comparing Enum Values
print(Color.RED == Color(1))

Explanation

Color.RED → enum member
Color(1) → converts value 1 into enum member

๐Ÿ‘‰ So:

Color(1) → Color.RED

5️⃣ Final Comparison
Color.RED == Color.RED

Explanation

Both refer to the same enum member.

๐Ÿ“ค Final Output
True

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

 


Code Explanation:

1️⃣ Importing lru_cache
from functools import lru_cache

Explanation

Imports lru_cache from the functools module.
It is used for memoization (caching function results).

2️⃣ Applying Decorator
@lru_cache(None)

Explanation

This decorator caches results of function calls.
None means unlimited cache size.

๐Ÿ‘‰ So once a value is computed, it is stored and reused.

3️⃣ Defining Function
def f(n):

Explanation

Defines function f that takes input n.

4️⃣ Base Condition
if n <= 1:
    return n

Explanation

If n is 0 or 1, return n.
This is the base case of recursion.

5️⃣ Recursive Case
return f(n-1) + f(n-2)

Explanation

This is Fibonacci logic.
Computes:
f(n) = f(n-1) + f(n-2)

6️⃣ Calling Function
print(f(5))

Explanation

Calls f(5).
๐Ÿ”„ Execution (Step-by-Step)

Without cache:

f(5)
= f(4) + f(3)
= (f(3)+f(2)) + (f(2)+f(1))
= ...

๐Ÿ‘‰ Many repeated calls!

⚡ With lru_cache

Each value is computed once only:

Call Value
f(0) 0
f(1) 1
f(2) 1
f(3) 2
f(4) 3
f(5) 5

๐Ÿ“ค Final Output
5

Monday, 6 April 2026

Python Coding Challenge - Question with Answer (ID -070426)

 


Code Explanation:

1. Global Variable Declaration
x = 14
A variable x is created in the global scope.
Its value is 14.
This means x can be accessed anywhere in the program unless shadowed locally.

⚙️ 2. Function Definition
def func():
A function named func is defined.
No parameters are passed to this function.

๐Ÿ–จ️ 3. First Statement Inside Function
print(x)
Python looks for x inside the function first (local scope).
But notice: later in the function, x = 5 exists.
Because of that assignment, Python treats x as a local variable throughout the function.

๐Ÿ‘‰ Important rule:

If a variable is assigned anywhere inside a function, Python considers it local to that function (unless declared global).

❗ 4. Local Assignment
x = 5
This creates a local variable x inside func.
It does NOT affect the global x.

๐Ÿšจ 5. Function Call
func()
When the function runs:
Python sees x = 5 → decides x is local
Then tries print(x) BEFORE assigning it

๐Ÿ’ฅ 6. Error Occurs

You will get:

UnboundLocalError: local variable 'x' referenced before assignment
Why?
Python thinks x is local
But print(x) tries to use it before it's assigned

Final Output:
Error

Book: Python Functions in Depth — Writing Clean, Reusable, and Powerful Code

Fundamentals of Deep Learning Models

 


Artificial Intelligence is transforming industries at an unprecedented pace — and at the heart of this transformation lies deep learning. From voice assistants to self-driving cars, deep learning models are powering the most advanced technologies of our time.

Fundamentals of Deep Learning Models is a beginner-friendly guide that helps you understand the core concepts, architectures, and techniques behind these intelligent systems. Whether you’re starting your AI journey or strengthening your foundation, this book provides a solid entry point. ๐Ÿš€


๐Ÿ’ก Why Deep Learning Matters

Deep learning is a subset of machine learning that uses multi-layered neural networks to learn patterns from data.

It is widely used in:

  • ๐Ÿง  Natural Language Processing (chatbots, translation)
  • ๐Ÿ‘ Computer Vision (image recognition)
  • ๐ŸŽง Speech recognition systems
  • ๐ŸŽฏ Recommendation engines

Its ability to learn complex patterns from large datasets has made it one of the most powerful tools in modern AI .


๐Ÿง  What This Book Covers

This book focuses on building a strong conceptual foundation, making it easier for readers to understand and apply deep learning techniques.

๐Ÿ”น Introduction to AI, ML, and Deep Learning

The book begins by explaining how:

  • Artificial Intelligence → broad field
  • Machine Learning → subset of AI
  • Deep Learning → subset of ML

This layered understanding helps learners see the big picture of intelligent systems .


๐Ÿ”น Neural Networks Fundamentals

At the core of deep learning are neural networks. You’ll learn:

  • Structure of neurons and layers
  • Activation functions (ReLU, Sigmoid, etc.)
  • Forward propagation

These are the building blocks of all deep learning models.


๐Ÿ”น Training Deep Learning Models

The book explains how models learn using:

  • Gradient descent optimization
  • Backpropagation algorithms
  • Loss functions and error minimization

These concepts are essential for improving model performance and accuracy.


๐Ÿ”น Popular Deep Learning Architectures

You’ll explore widely used architectures such as:

  • Feedforward Neural Networks (FNNs)
  • Convolutional Neural Networks (CNNs)
  • Recurrent Neural Networks (RNNs)

These architectures power applications in image processing, text analysis, and sequence prediction .


๐Ÿ”น Model Evaluation and Challenges

The book also highlights real-world challenges like:

  • Overfitting and underfitting
  • Bias-variance tradeoff
  • Model generalization

Understanding these helps you build more reliable AI systems.


๐Ÿ›  Learning Approach

One of the strengths of this book is its beginner-friendly approach:

  • Simple explanations without heavy math
  • Visual illustrations and examples
  • Step-by-step concept building

It focuses on helping readers understand concepts intuitively, rather than just memorizing formulas .


๐ŸŽฏ Who Should Read This Book?

This book is ideal for:

  • Beginners in AI and machine learning
  • Students in computer science or data science
  • Developers exploring deep learning
  • Professionals transitioning into AI

It’s designed to take you from basic understanding → practical awareness.


๐Ÿš€ Why This Book Stands Out

What makes this book valuable:

  • Covers fundamentals in a structured way
  • Explains concepts with clarity and simplicity
  • Connects theory to real-world applications
  • Suitable for both beginners and intermediate learners

It acts as a foundation builder before diving into advanced deep learning topics.


Hard Copy: Fundamentals of Deep Learning Models

๐Ÿ“Œ Final Thoughts

Deep learning is one of the most exciting and impactful areas of technology today. But to truly master it, you need a strong understanding of its fundamentals.

Fundamentals of Deep Learning Models provides that foundation — helping you understand how models work, how they learn, and how they are applied in real-world scenarios.

If you’re starting your journey in AI or looking to strengthen your basics, this book is a great place to begin. ๐Ÿ“Š๐Ÿค–

FROM FORGOTTEN TECHNOLOGIES TO ARTIFICIAL INTELLIGENCE: Tracing the Evolution of Artificial Intelligence

 


Artificial Intelligence may seem like a modern breakthrough, but its roots stretch back decades — even centuries. Behind today’s powerful AI systems lies a long history of forgotten ideas, experimental technologies, and visionary thinkers.

From Forgotten Technologies to Artificial Intelligence: Tracing the Evolution of Artificial Intelligence takes readers on a fascinating journey through time, revealing how past innovations shaped the intelligent systems we use today. ๐Ÿš€


๐Ÿ’ก Why Understanding AI’s History Matters

AI didn’t appear overnight. It evolved through multiple phases — from early theoretical ideas to modern deep learning breakthroughs.

In fact:

  • The foundations of AI began as early as the early 1900s
  • Major developments took place in the 1950s, marking the birth of AI as a field
  • Progress came in waves, including periods of rapid growth and “AI winters” where interest declined

Understanding this journey helps us:

  • Appreciate current technologies
  • Learn from past failures
  • Predict future trends in AI

๐Ÿง  What This Book Explores

This book offers a historical and conceptual exploration of AI, focusing on both well-known breakthroughs and overlooked innovations.

๐Ÿ”น Forgotten Technologies That Shaped AI

Many early technologies and ideas contributed to AI but are often overlooked. The book highlights:

  • Early computational theories
  • Primitive automation systems
  • Historical attempts at machine intelligence

These “forgotten” innovations laid the groundwork for modern AI systems.


๐Ÿ”น The Birth and Evolution of AI

The book traces key milestones such as:

  • The creation of artificial neural models in the 1940s
  • The rise of symbolic AI and rule-based systems
  • The transition to machine learning and deep learning

It shows how AI evolved from simple rule-based systems to complex learning models.


๐Ÿ”น The Cyclical Nature of AI Progress

AI development has not been linear. Instead, it has gone through cycles:

  • AI Booms → periods of excitement and funding
  • AI Winters → periods of decline and skepticism

Even “forgotten waves” like the Semantic Web era played a crucial role in shaping today’s intelligent systems .


๐Ÿ”น Modern AI and the Rise of Intelligent Systems

The book connects history to the present, explaining how we arrived at:

  • Machine learning and deep learning
  • Generative AI and large language models
  • Autonomous agents and intelligent systems

Today’s AI is built on decades of accumulated knowledge and experimentation.


๐Ÿ›  Key Takeaways from the Book

By reading this book, you will:

  • Understand the historical roots of AI
  • Learn about forgotten innovations that influenced modern systems
  • See how AI evolved through successes and failures
  • Gain insights into future directions of AI

It helps you move beyond just using AI — to truly understanding its evolution.


๐ŸŽฏ Who Should Read This Book?

This book is ideal for:

  • Students and beginners in AI
  • Tech enthusiasts curious about AI history
  • Researchers and professionals in machine learning
  • Anyone interested in how technology evolves over time

No deep technical knowledge is required — just curiosity about AI and its journey.


๐Ÿš€ Why This Book Stands Out

Unlike many technical AI books, this one focuses on storytelling and historical context.

What makes it unique:

  • Highlights overlooked and forgotten technologies
  • Connects past innovations to present breakthroughs
  • Explains AI evolution in a simple, engaging way
  • Provides a broader perspective beyond coding and algorithms

It shows that AI is not just a technology — it’s a continuously evolving story.


Hard Copy: FROM FORGOTTEN TECHNOLOGIES TO ARTIFICIAL INTELLIGENCE: Tracing the Evolution of Artificial Intelligence

Kindle: FROM FORGOTTEN TECHNOLOGIES TO ARTIFICIAL INTELLIGENCE: Tracing the Evolution of Artificial Intelligence

๐Ÿ“Œ Final Thoughts

Artificial Intelligence is often seen as the future — but to truly understand it, we must look at the past.

From Forgotten Technologies to Artificial Intelligence reminds us that innovation is built on layers of ideas, experiments, and even failures. Every breakthrough today stands on the shoulders of forgotten technologies.

If you want to understand not just how AI works, but how it came to be, this book is a fascinating and insightful read. ๐ŸŒŸ

MATHEMATICS FOR AI AND MACHINE LEARNING: A Comprehensive Mathematical Reference for Artificial Intelligence and Machine Learning

 


Artificial Intelligence and Machine Learning may seem like magic — but behind every smart system lies a powerful engine of mathematics. From recommendation systems to generative AI, math is what enables machines to learn, adapt, and make decisions.

Mathematics for AI and Machine Learning: A Comprehensive Mathematical Reference is designed to give learners a complete and structured understanding of the math behind AI, making it an essential resource for anyone serious about mastering the field. ๐Ÿš€


๐Ÿ’ก Why Mathematics is the Backbone of AI

AI models don’t “think” — they calculate. Every prediction, classification, or generation is powered by mathematical principles.

Mathematics helps:

  • Represent and process data efficiently
  • Optimize models for better performance
  • Understand uncertainty and predictions
  • Train neural networks effectively

Core areas like linear algebra, calculus, and probability form the foundation of modern machine learning systems.


๐Ÿง  What This Book Covers

This book acts as a comprehensive reference guide, bringing together all the essential mathematical concepts needed for AI and machine learning.

๐Ÿ”น Linear Algebra: The Language of Data

Linear algebra is fundamental for representing and transforming data.

You’ll learn:

  • Vectors and matrices
  • Matrix operations and transformations
  • Eigenvalues and eigenvectors

These concepts are used in neural networks, image processing, and dimensionality reduction techniques like PCA.


๐Ÿ”น Calculus: The Engine of Learning

Calculus powers how models learn from data.

Key topics include:

  • Derivatives and gradients
  • Optimization techniques
  • Backpropagation in neural networks

Without calculus, machine learning models wouldn’t be able to improve or minimize errors effectively.


๐Ÿ”น Probability & Statistics: Handling Uncertainty

AI systems often deal with uncertainty, and probability provides the tools to manage it.

You’ll explore:

  • Probability distributions
  • Bayesian thinking
  • Statistical inference

These are crucial for prediction, decision-making, and evaluating models.


๐Ÿ”น Optimization Techniques

Optimization is what makes AI models accurate and efficient.

The book explains:

  • Loss functions
  • Gradient-based optimization
  • Convex and non-convex problems

These techniques help fine-tune models for better performance.


๐Ÿงฉ Structured Learning Approach

The book is designed to be both comprehensive and practical, helping readers:

  • Build a strong mathematical foundation
  • Connect theory with real-world AI applications
  • Progress from basic concepts to advanced topics

Many modern resources emphasize that understanding these mathematical pillars is essential for mastering machine learning and deep learning.


๐Ÿ›  Real-World Applications of Math in AI

Mathematics is not just theoretical — it directly powers real-world AI systems:

  • ๐Ÿ“ธ Computer vision (image recognition)
  • ๐Ÿง  Natural language processing
  • ๐ŸŽฏ Recommendation systems
  • ๐Ÿ“Š Predictive analytics
  • ๐Ÿค– Generative AI models

For example, neural networks rely heavily on matrix operations and gradient-based optimization to function effectively.


๐ŸŽฏ Who Should Read This Book?

This book is ideal for:

  • Aspiring AI and machine learning engineers
  • Data scientists and analysts
  • Students in computer science or mathematics
  • Professionals looking to strengthen their math foundations

A basic understanding of programming and algebra will help you get the most out of it.


๐Ÿš€ Why This Book Stands Out

What makes this book valuable is its all-in-one approach:

  • Covers all essential math topics in one place
  • Connects theory with practical AI applications
  • Suitable as both a learning guide and reference book
  • Helps bridge the gap between math and implementation

It’s not just about formulas — it’s about understanding how math drives intelligent systems.


Hard Copy: MATHEMATICS FOR AI AND MACHINE LEARNING: A Comprehensive Mathematical Reference for Artificial Intelligence and Machine Learning

Kindle: MATHEMATICS FOR AI AND MACHINE LEARNING: A Comprehensive Mathematical Reference for Artificial Intelligence and Machine Learning

๐Ÿ“Œ Final Thoughts

In the world of AI, tools and frameworks may change — but mathematics remains constant. If you truly want to understand how machine learning models work, math is the key.

Mathematics for AI and Machine Learning is more than just a reference book — it’s a roadmap to mastering the core principles behind intelligent systems.

If you’re serious about building a career in AI, strengthening your mathematical foundation is one of the smartest investments you can make. ๐Ÿ“Š๐Ÿค–

Statistics Made Simple: Understand better. Measure better. Decide better. (Quick Guide to Data Science Book 2)

 


In today’s data-driven world, statistics is no longer just a subject for mathematicians — it’s a life skill. Whether you’re analyzing business data, interpreting reports, or making everyday decisions, understanding statistics can give you a powerful advantage.

Statistics Made Simple: Understand Better. Measure Better. Decide Better. is designed to break down complex statistical concepts into easy, practical, and beginner-friendly insights. It’s a perfect guide for anyone who wants to overcome the fear of numbers and start thinking analytically. ๐Ÿš€


๐Ÿ’ก Why Statistics Matters More Than Ever

We are surrounded by data — from social media metrics to financial reports and scientific studies. But data alone is not useful unless we can interpret it correctly.

Statistics helps you:

  • Make informed decisions
  • Identify patterns and trends
  • Avoid misleading conclusions
  • Understand uncertainty and risk

In simple terms, statistics turns raw numbers into meaningful insights that guide better choices.


๐Ÿง  What This Book Offers

This book is designed for absolute beginners, making statistics approachable and easy to understand.

It focuses on:

  • Clear explanations without heavy math
  • Real-world examples
  • Practical applications of statistical concepts

The goal is to help readers learn by understanding, not memorizing formulas.


๐Ÿ”น Core Concepts Explained Simply

๐Ÿ“Œ Understanding Data

The book starts with the basics:

  • What is data?
  • Types of data (categorical vs numerical)
  • How data is collected and organized

These fundamentals are essential for any kind of analysis.


๐Ÿ“Œ Measures and Summaries

You’ll learn how to summarize data using:

  • Mean, median, and mode
  • Range and variability
  • Standard deviation

These measures help describe datasets clearly and accurately.


๐Ÿ“Œ Probability Made Easy

Probability is at the heart of statistics. The book explains:

  • Likelihood of events
  • Randomness and uncertainty
  • Real-world probability examples

This helps you understand risk and make predictions.


๐Ÿ“Œ Making Better Decisions

One of the most valuable aspects of the book is its focus on decision-making. It shows how to:

  • Interpret data correctly
  • Avoid common statistical mistakes
  • Use insights to make smarter choices

Statistics is not just about numbers — it’s about thinking logically and critically.


๐Ÿ›  Beginner-Friendly Learning Approach

The book emphasizes simplicity and clarity. It uses:

  • Step-by-step explanations
  • Practical examples
  • Easy language for non-technical readers

Many beginner-friendly statistics resources highlight that simplifying concepts and using real examples makes learning much more effective.


๐ŸŽฏ Who Should Read This Book?

This book is ideal for:

  • Students starting with statistics
  • Data science beginners
  • Business professionals
  • Anyone who wants to understand data better

You don’t need a strong math background — just curiosity and willingness to learn.


๐Ÿš€ Why This Book Stands Out

Unlike traditional textbooks that focus heavily on formulas, this book:

  • Focuses on practical understanding
  • Uses simple language and examples
  • Connects statistics to real-life decisions
  • Builds confidence step by step

It helps you move from “I don’t understand statistics” to “I can use data confidently.”


Kindle: Statistics Made Simple: Understand better. Measure better. Decide better. (Quick Guide to Data Science Book 2)

๐Ÿ“Œ Final Thoughts

Statistics doesn’t have to be complicated or intimidating. With the right approach, it becomes a powerful tool for understanding the world around you.

Statistics Made Simple is more than just a book — it’s a guide to thinking smarter, analyzing better, and making informed decisions.

If you want to build a strong foundation in data literacy and start making sense of numbers in everyday life, this book is a great place to begin. ๐Ÿ“Š✨


๐Ÿš€ Day 13/150 – Simple Calculator in Python

 

๐Ÿš€ Day 13/150 – Simple Calculator in Python

Welcome back to the 150 Days of Python series! ๐Ÿ”ฅ
Today, we’ll build a Simple Calculator — one of the most important beginner projects.

This project helps you understand:

  • Conditional statements
  • Functions
  • User input
  • Error handling

๐ŸŽฏ Problem Statement

Create a Python program that performs basic operations:

  • Addition ➕
  • Subtraction ➖
  • Multiplication ✖️
  • Division ➗

✅ Method 1 – Using if-elif-else

print("Simple Calculator") a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) operation = input("Enter operation (+, -, *, /): ") if operation == "+": print("Result:", a + b) elif operation == "-": print("Result:", a - b) elif operation == "*": print("Result:", a * b) elif operation == "/": if b != 0: print("Result:", a / b) else: print("Division by zero is not allowed") else: print("Invalid operation")


















๐Ÿ” Explanation:
input() → takes user input
float() → converts input into numbers
if-elif-else → checks which operation user selected

๐Ÿ‘‰ Important:
Always check b != 0 before division to avoid errors.

✅ Method 2 – Using Functions

def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): if y != 0: return x / y else: return "Division by zero not allowed" print(add(10, 5)) print(subtract(10, 5)) print(multiply(10, 5)) print(divide(10, 5))









๐Ÿ” Why use functions?

Code becomes modular

Easy to reuse

Cleaner structure

๐Ÿ‘‰ This approach is closer to real-world coding.

✅ Method 3 – Using Lambda Functions

add = lambda x, y: x + y subtract = lambda x, y: x - y multiply = lambda x, y: x * y divide = lambda x, y: x / y if y != 0 else "Cannot divide by zero" print(add(10, 5)) print(subtract(10, 5)) print(multiply(10, 5)) print(divide(10, 5))







๐Ÿ” Explanation:
lambda → creates small anonymous functions
Useful for short, one-line operations

๐Ÿ‘‰ Best for concise code, but not always readable for beginners.

⚠️ Important Things to Remember

✔ Always convert input (int() or float())
✔ Handle division by zero
✔ Validate user input
✔ Keep code clean and readable


๐Ÿง  Summary

MethodConcept
if-elif-elseBasic logic
FunctionsReusability
LambdaShort & compact

April Python Bootcamp Day 3


 

 

Introduction

In Python, operators are fundamental building blocks used to perform operations on variables and values. Whether you're building a calculator, writing conditions, or designing logic — operators are everywhere.

Key Insight:
Operators are the backbone of decision-making and computation in programming.


 What is an Operator?

An operator is a symbol that performs an operation on operands (values or variables).

a = 10
b = 5
print(a + b) # Output: 15
  • + → Operator
  • a, b → Operands

 Why Operators Matter

Operators are used in:

  •  Calculations → price + tax
  •  Conditions → age > 18
  •  Logic → is_logged_in and is_verified
  •  Control flow → loops, decisions

 Types of Operators in Python


 1. Arithmetic Operators

Used for mathematical operations.

print(10 + 5) # 15
print(10 - 5) # 5
print(10 * 5) # 50
print(10 / 5) # 2.0
print(10 // 3) # 3
print(10 % 3) # 1
print(2 ** 3) # 8

Notes:

  • / → always returns float
  • // → floor division
  • % → useful for even/odd checks

 2. Assignment Operators

Used to assign and update values.

x = 10
x += 5 # 15
x -= 2 # 13
x *= 2 # 26
x /= 2 # 13.0

Notes:

  • Short-hand operations improve readability
  • Common in loops and updates

 3. Comparison Operators

Used to compare values → returns Boolean

print(10 == 10) # True
print(10 != 5) # True
print(10 > 5) # True
print(10 < 5) # False

Notes:

  • Always returns True or False
  • Used in conditions (if, loops)

 4. Logical Operators

Combine multiple conditions

print(True and False) # False
print(True or False) # True
print(not True) # False

Notes:

  • and → all conditions must be True
  • or → at least one True
  • not → reverses result

 5. Identity Operators

Check if two variables refer to the same object

a = [1, 2]
b = a
c = [1, 2]

print(a is b) # True
print(a is c) # False
print(a == c) # True

Notes:

  • is → checks memory location
  • == → checks value

 6. Membership Operators

Check if a value exists in a sequence

print("a" in "apple") # True
print(10 in [1, 2, 3]) # False
print(1 in (1, 2, 3)) # True

Notes:

  • Works with strings, lists, tuples, sets

 Operator Precedence

Precedence determines which operator executes first.

print(2 + 3 * 4) # 14

 Multiplication happens before addition


 Associativity

Associativity determines evaluation order when precedence is same.


 Left to Right

print(10 - 5 - 2) # 3

 Right to Left

print(2 ** 3 ** 2) # 512

 Precedence + Associativity Table

PriorityOperatorsAssociativity
1()Left → Right
2**Right → Left
3+x, -x, notRight → Left
4* / // %Left → Right
5+ -Left → Right
6ComparisonsLeft → Right
7andLeft → Right
8orLeft → Right
9AssignmentRight → Left

 Important Notes (Exam / Interview Level)

  • True = 1, False = 0
  • and returns first falsy value
  • or returns first truthy value
  • is==
  • Exponent is right-associative
  • Division always returns float

 Practice Questions (NEW)


 Q1

print(8 + 2 * 5 - 3)

 Q2

print(20 // 3 + 2 ** 2)

 Q3

print(5 > 3 and 8 < 5 or 10 > 2)

 Q4

print(not (4 == 4 and 2 > 3))

 Q5

x = 10
x -= 3 * 2
print(x)

 Q6

print(6 + 3 * 2 ** 2)

 Q7

print("p" in "python" and 5 not in [1,2,3])

 Q8

a = [1,2,3]
b = a
c = a[:]

print(a is c)

 Q9

print(0 or 5 and 10)

 Q10 (Advanced)

print(2 ** 2 ** 3 + 1)

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (237) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (28) Azure (10) BI (10) Books (262) Bootcamp (3) C (78) C# (12) C++ (83) Course (87) Coursera (300) Cybersecurity (30) data (5) Data Analysis (29) Data Analytics (21) data management (15) Data Science (339) Data Strucures (16) Deep Learning (144) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (19) Finance (10) flask (4) flutter (1) FPL (17) Generative AI (68) Git (10) Google (51) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (277) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (13) PHP (20) Projects (32) pytho (1) Python (1286) Python Coding Challenge (1124) Python Mistakes (50) Python Quiz (465) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (48) Udemy (18) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)