Artificial Intelligence
56K subscribers
487 photos
5 videos
120 files
422 links
🔰 Machine Learning & Artificial Intelligence Free Resources

🔰 Learn Data Science, Deep Learning, Python with Tensorflow, Keras & many more

For Promotions: @love_data
Download Telegram
In the previous post, we learned what variables are and how they are used to store data. But what kind of data can a variable store? That's where Data Types come in.

📖 Phase 1: Programming Fundamentals

📌 Topic 5: Data Types

A data type defines the kind of value a variable can store. Different types of data require different operations, so Python classifies them into various data types.

Think of data types as different containers designed for different kinds of items. Just as you wouldn't store water in a paper bag, you shouldn't treat every kind of data the same way in programming.

Why Do We Need Data Types?

Data types help Python:

Store data efficiently.

Perform the correct operations.

Detect invalid operations.

Manage memory effectively.

Basic Data Types in Python

1. Integer ("int")

Integers are whole numbers without decimal points.

Example:

age = 25

marks = 100

print(age)

print(marks)

Output:

25

100

2. Float ("float")

Floats are numbers with decimal points.

Example:

height = 5.8

price = 99.99

print(height)

print(price)

Output:

5.8

99.99

3. String ("str")

A string is a sequence of characters enclosed in single or double quotes.

Example:

name = "Narayan"

city = 'Pune'

print(name)

print(city)

Output:

Narayan

Pune

4. Boolean ("bool")

A Boolean has only two possible values:

"True"

"False"

Example:

is_student = True

has_job = False

print(is_student)

print(has_job)

Output:

True

False

Checking the Data Type

Python provides the type() function to check the data type of a variable.

Example:

age = 21

price = 99.99

name = "Radhe"

print(type(age))

print(type(price))

print(type(name))

Output:

Type Conversion (Preview)

Sometimes you need to convert one data type into another.

Example:

age = "25"

print(int(age))

Output:

25

We'll learn Type Casting in detail in the next topic.

Summary of Common Data Types

Data Type: Integer ("int")

Example: "10"

Data Type: Float ("float")

Example: "3.14"

Data Type: String ("str")

Example: "Hello"

Data Type: Boolean ("bool")

Example: "True"

Key Takeaways

Every value in Python has a data type.

The four basic data types are "int", "float", "str", and "bool".

Python automatically identifies the data type of a value.

Use the type() function to check a variable's data type.

Understanding data types is essential before performing operations on data.

➡️ Double Tap ❤️ For More
❤22👎1🔥1
In the previous post, we learned about Python data types and how different kinds of data are stored. Now, let's learn how to interact with users by taking input and displaying output.

📖 Phase 1: Programming Fundamentals

📌 Topic 6: Input & Output

Every program performs two basic operations:

• Input – Receiving data from the user.

• Output – Displaying information to the user.

For example, when you enter your username and password on a website, that's input. When the website displays "Login Successful," that's output.

Output in Python

Python uses the print() function to display output on the screen.

Example:

print("Hello, World!")

Output:

Hello, World!

You can also print numbers and variables.

name = "Surya"

age = 25

print(name)

print(age)

Output:

Surya

25

Printing Multiple Values

name = "Ajay"

age = 25

print("Name:", name)

print("Age:", age)

Output:

Name: Ajay

Age: 25

Input in Python

Python uses the input() function to accept input from the user.

Example:

name = input("Enter your name: ")

print("Hello,", name)

Sample Output:

Enter your name: Deepak

Hello, Deepak

Taking Numeric Input

By default, input() returns a string.

age = input("Enter your age: ")

print(type(age)) #

To use it as a number, convert with int() or float().

age = int(input("Enter your age: "))

Example: Adding Two Numbers

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))

sum = num1 + num2

print("Sum =", sum)

Sample Output:

Enter first number: 10

Enter second number: 20

Sum = 30

Common Beginner Mistakes

❌ Forgetting that input() always returns a string.

❌ Trying to add two numbers without converting them.

num1 = input("Enter first number: ")

num2 = input("Enter second number: ")

print(num1 + num2)

If user enters 10 and 20 → Output: 1020

This happens because Python joins two strings instead of adding two numbers.

Best Practices

✅ Use clear prompts while taking input.

✅ Convert numeric input using int() or float() whenever required.

✅ Use meaningful variable names.

Key Takeaways

• print() is used to display output.

• input() is used to receive input from the user.

• input() always returns a string.

• Convert user input using int() or float() for mathematical operations.

• Input and Output are the foundation of interactive Python programs.

➡️ Double Tap ❤️ For More
❤21👏1
🤖💻 HOW TO BUILD YOUR FIRST AI PROJECT — A BEGINNER'S ROADMAP 🚀

You know Python.

You've learned the basics of AI.

You've experimented with prompts.

Now comes the important question:

How do you actually build an AI application?

You don't need to start with a complicated AI agent.

Start with a simple project and understand every layer.

1️⃣ START WITH A REAL PROBLEM

Don't begin with:

❌ "I want to use an LLM."

Begin with:

✅ "What problem can AI solve?"

Examples:

• Summarize documents

• Answer questions about a knowledge base

• Classify customer feedback

• Extract information from invoices

• Generate product descriptions

• Analyze support tickets

👉 The problem comes before the technology.

2️⃣ CHOOSE YOUR INPUT

Determine what information your application will receive.

It could be:

📝 Text

📄 Documents

🖼️ Images

🎙️ Audio

📊 Structured data

🌐 API data

Your input determines how your application should process the information.

3️⃣ CHOOSE THE AI MODEL

Different tasks may require different model capabilities.

For example:

Text generation → Language model

Image understanding → Vision-capable model

Speech processing → Speech model

Semantic search → Embedding model

👉 Don't choose a model simply because it's popular.

Choose based on the task, quality requirements, speed, cost, and context needs.

4️⃣ CONNECT YOUR APPLICATION TO THE MODEL

Your Python application can communicate with an AI model through an API or another supported interface.

Basic flow:

Your Application → AI Model → Response

Your code sends the input.

The model processes it.

Your application receives the result.

5️⃣ WRITE A GOOD SYSTEM INSTRUCTION

Give the model clear instructions about its role and expected behavior.

For example:

"You are a customer-support assistant. Answer using the provided company information. If the answer isn't available, clearly say that you don't have enough information."

Clear instructions can make application behavior more consistent.

6️⃣ ADD USER INPUT

Now make your application interactive.

For example:

User: "Summarize this document."

Application: Receives the document.

AI: Generates the summary.

Application: Displays the result.

You've now created a basic AI-powered application.

7️⃣ HANDLE THE OUTPUT

Don't assume the model will always return exactly what you expect.

Your application should consider:

• Unexpected responses

• Missing information

• Invalid formats

• Long responses

• API failures

• Timeouts

👉 AI output should be treated as data that needs validation.

8️⃣ ADD YOUR OWN DATA

This is where AI applications become much more interesting.

Suppose you're building a company knowledge assistant.

The model itself may not know your internal documents.

You can provide relevant information from your own knowledge base.

For example:

Documents ↓ Process ↓ Retrieve relevant information ↓ AI model ↓ Answer

This is the foundation of many RAG applications.

9️⃣ UNDERSTAND EMBEDDINGS

Embeddings convert information into numerical representations that capture aspects of meaning.

They allow applications to perform semantic similarity searches.

For example:

"How do I request annual leave?"

can retrieve a document titled:

"Employee Vacation Policy"
❤12👍2
even though the wording isn't identical.

🔟 BUILD A SIMPLE RAG SYSTEM

A beginner-friendly RAG pipeline looks like:

📄 Documents ↓ Split into smaller sections ↓ Create embeddings ↓ Store vectors ↓ User asks a question ↓ Find relevant sections ↓ Provide them to the model ↓ Generate answer

You don't need to build the most sophisticated RAG system on your first attempt.

Understand the basic pipeline first.

1️⃣1️⃣ ADD TOOLS WHEN NEEDED

Suppose your AI assistant needs information it cannot know by itself.

Give it tools.

For example:

🔎 Search

🗄️ Database lookup

🌤️ Weather API

📅 Calendar

🧮 Calculator

Now your application becomes more capable.

1️⃣2️⃣ DON'T CONFUSE CHATBOTS WITH AGENTS

A chatbot may simply:

Input → Model → Response

An agentic application may:

Goal → Plan → Tool → Result → Next action → Final response

Agents are useful for multi-step tasks, but they also introduce additional complexity.

👉 Start simple before building agents.

1️⃣3️⃣ ADD VALIDATION

Never assume the AI response is automatically correct.

Validate important outputs.

For example:

If the model is extracting:

Name → Email → Amount → Date

your application should check whether those fields have valid formats.

1️⃣4️⃣ HANDLE SECURITY

AI applications can introduce new security concerns.

Think about:

🔐 Authentication

🔐 Authorization

🔐 Sensitive information

🔐 Prompt injection

🔐 Tool permissions

🔐 Input validation

🔐 Output validation

🔐 API key protection

Never expose secret API keys in frontend code or public repositories.

1️⃣5️⃣ TEST YOUR AI APPLICATION

Traditional software testing isn't enough.

You should test:

• Normal inputs

• Unexpected inputs

• Ambiguous questions

• Missing information

• Very long inputs

• Incorrect assumptions

• Potentially harmful requests

For AI applications, evaluate not just whether the application runs — but whether its responses are appropriate and reliable.

1️⃣6️⃣ MEASURE QUALITY

Ask:

👉 Is the answer correct?

👉 Is it relevant?

👉 Is it grounded in the provided information?

👉 Is it consistent?

👉 Is it fast enough?

👉 Is the cost acceptable?

AI development isn't just about making something that works once.

It's about making something that works reliably.

1️⃣7️⃣ DEPLOY IT

Once your application works locally, make it accessible.

A typical architecture might look like:

Frontend ↓ Backend API ↓ AI Model ↓ Database / Vector Store ↓ External Tools

You don't need complex infrastructure for your first project.

Keep the architecture simple.

1️⃣8️⃣ IMPROVE IT ITERATIVELY

Your first version won't be perfect.

Improve:

• Prompts

• Model selection

• Retrieval

• Error handling

• UI

• Speed

• Cost

• Evaluation

Build → Test → Learn → Improve.

If you are beginner, start with building something small.

• Understand every component.

• Break it.

• Debug it.

• Improve it.

Then build something bigger.

🚀 Don't wait until you know everything about AI before building.

Build to learn AI.

💬 Double Tap ❤️ For More
❤21🥰2
This media is not supported in your browser
VIEW IN TELEGRAM
🚀 GigaChat 3.5 Reasoning — a new open-source LLM that thinks before it answers.

It breaks problems into stages, builds a plan, checks intermediate results, and self-corrects. Built on GigaChat 3.5 Ultra, it explores multiple step-by-step reasoning paths for math & coding, using automated verification to reinforce correct answers.

⚡️ Proprietary linear attention makes it highly efficient on long contexts, retaining key points without re-matching from scratch. It’s also token-efficient: uses 37% fewer tokens than DeepSeek V4 Flash Preview on math problems!

📈 Benchmark gains over non-reasoning version:
• IFBench: 44 → 77
• Natural Plan: 64 → 80
• LiveCodeBench v6: 56 → 85

📦 MIT license. Weights on Hugging Face: fp8 | bf16
❤2👏1
In the previous post, we learned how to take input from users and display output. One important thing we discovered was that input() always returns a string. So, how do we convert one data type into another? That's where Type Casting comes in.

📖 Phase 1: Programming Fundamentals

📌 Topic 7: Type Casting

Type Casting is the process of converting a value from one data type to another.

For example, you may receive a number as a string from the user, but you need to perform mathematical operations on it. In such cases, type casting is required.

Why Do We Need Type Casting?
Type casting helps us:
• Convert user input into numbers.
• Perform mathematical calculations.
• Change data from one type to another.
• Prevent type-related errors.

Types of Type Casting
There are two types of type casting in Python:
• Implicit Type Casting (Automatic)
• Explicit Type Casting (Manual)

1. Implicit Type Casting
Python automatically converts one data type into another when it is safe to do so.

Example:

num = 10
price = 5.5

result = num + price

print(result)
print(type(result))


Output:

15.5
<class 'float'>


Python automatically converts the integer into a float.

2. Explicit Type Casting
In explicit type casting, the programmer manually converts the data type using built-in functions.

Some commonly used conversion functions are:
• int() → Converts to Integer
• float() → Converts to Float
• str() → Converts to String
• bool() → Converts to Boolean

Converting String to Integer

age = "25"
age = int(age)

print(age)
print(type(age))


Output:

25
<class 'int'>


Converting Integer to Float

marks = 90
marks = float(marks)

print(marks)


Output:

90.0


Converting Number to String

num = 100
text = str(num)

print(text)
print(type(text))


Output:

100
<class 'str'>


Converting Values to Boolean

print(bool(1))
print(bool(0))
print(bool(""))
print(bool("Python"))


Output:

True
False
False
True


Common Beginner Mistakes
❌ Trying to convert invalid values.

Example:

num = int("Hello")  

This will produce an error because "Hello" is not a valid integer.

❌ Forgetting to convert user input before performing calculations.

Best Practices
✅ Convert data only when necessary.
✅ Validate user input before converting.
✅ Use the correct conversion function for the required data type.

Key Takeaways
• Type Casting means converting one data type into another.
• Python supports both Implicit and Explicit type casting.
• int(), float(), str(), and bool() are the most commonly used conversion functions.
• Always convert user input before performing mathematical operations.
• Understanding type casting helps you write error-free and efficient programs.

➡️ Double Tap ❤️ For More
❤10👏1
In the previous post, we learned how to convert one data type into another using Type Casting. Now, let's explore Operators, which allow us to perform calculations, compare values, and make decisions in our programs.

📖 Phase 1: Programming Fundamentals

📌 Topic 8: Operators

Operators are special symbols or keywords used to perform operations on variables and values.
Think of operators as tools that help you calculate, compare, assign values, or combine conditions in a program.

Why Do We Need Operators?
Operators help us:
• Perform mathematical calculations
• Compare values
• Assign values to variables
• Combine multiple conditions
• Make decisions in programs

1. Arithmetic Operators
Used for mathematical calculations.

Operators:
• + Addition: 10 + 5 = 15
• - Subtraction: 10 - 5 = 5
• * Multiplication: 10 * 5 = 50
• / Division: 10 / 5 = 2.0
• // Floor Division: 10 // 3 = 3
• % Modulus (Remainder): 10 % 3 = 1
• ** Exponent: 2 ** 3 = 8

Example:

a = 10
b = 3

print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.333...
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 1000


2. Comparison Operators
Compare two values and always return True or False.

Operators:
• == Equal to
• != Not equal to
• > Greater than
• < Less than
• >= Greater than or equal to
• <= Less than or equal to

Example:

x = 10
y = 20

print(x == y) # False
print(x != y) # True
print(x < y) # True
print(x >= y) # False


3. Assignment Operators
Used to assign or update values.

x = 10

x += 5 # 15
print(x)

x *= 2 # 30
print(x)

x -= 4 # 26
print(x)


4. Logical Operators
Combine multiple conditions.

Operators:
• and Returns True if both conditions are true
• or Returns True if at least one condition is true
• not Reverses the result

Example:

age = 25

print(age > 18 and age < 60) # True
print(age < 18 or age > 60) # False
print(not(age > 18)) # False


5. Membership Operators
Check whether a value exists in a sequence.

Operators:
• in Value exists
• not in Value does not exist

Example:

fruits = ["Apple", "Banana", "Mango"]

print("Apple" in fruits) # True
print("Orange" not in fruits) # True


6. Identity Operators
Check whether two variables refer to the same object in memory.

Operators:
• is Same object
• is not Different objects

Example:

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

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


Common Beginner Mistakes
❌ Using = instead of == while comparing values
❌ Confusing / with //
❌ Forgetting that and requires both conditions to be True

Best Practices
✅ Use meaningful variable names
✅ Choose the correct operator for the task
✅ Use parentheses to make complex conditions easier to read

Key Takeaways
• Operators perform calculations, comparisons, and logical operations
• Arithmetic operators are used for math
• Comparison operators return True or False
• Assignment operators simplify updating variables
• Logical operators combine multiple conditions
• Membership and Identity operators help work with collections and objects

➡️ Double Tap ❤️ For More
❤6
In the previous post, we explored Python operators and even tested ourselves with some tricky questions. Now, let's learn how Python makes decisions using Conditional Statements.

📖 Phase 1: Programming Fundamentals 
📌 Topic 9: Conditional Statements (if, elif, else)

Conditional statements allow a program to make decisions based on whether a condition is "True" or "False".

Think about a real-life decision: 
👉 If it is raining → Take an umbrella. ☔ 
👉 Otherwise → Don't take an umbrella.

Programming works in a similar way.

Why Do We Need Conditional Statements? 
They allow programs to:
• Make decisions
• Execute different blocks of code
• Validate user input
• Control program behavior
• Handle different scenarios

1. The "if" Statement 
The "if" statement executes a block of code only when a condition is "True".

Example:
age = 25
if age >= 18:
    print("You are eligible to vote.")

Output: You are eligible to vote.

If the condition is "False", the code inside the "if" block will not execute.

Important: Indentation 
Python uses indentation to define blocks of code.

Correct:
age = 25
if age >= 18:
    print("Eligible")

Incorrect:
age = 25
if age >= 18:
print("Eligible")

The second example will produce an indentation error.

2. The "else" Statement 
"else" executes when the "if" condition is "False".

Example:
age = 16
if age >= 18:
    print("Eligible to vote")
else:
    print("Not eligible to vote")

Output: Not eligible to vote

Think of it as: If condition is true → Do this. Otherwise → Do that.

3. The "elif" Statement 
"elif" means "else if". It allows you to check multiple conditions.

Example:
marks = 75
if marks >= 90:
    print("Grade A+")
elif marks >= 75:
    print("Grade A")
elif marks >= 60:
    print("Grade B")
else:
    print("Grade C")

Output: Grade A

Python checks the conditions from top to bottom and executes the first condition that is "True".

4. Multiple Conditions 
You can combine conditions using logical operators.

Example:
age = 25
has_id = True
if age >= 18 and has_id:
    print("Access granted")
else:
    print("Access denied")

Output: Access granted

5. Nested "if" Statements 
An "if" statement can be placed inside another "if" statement.

Example:
age = 25
country = "India"
if age >= 18:
    if country == "India":
        print("Eligible")

Nested conditions are useful when one decision depends on another.

6. Short-Hand "if" 
For simple conditions, Python allows a one-line "if".
age = 25
if age >= 18: print("Adult")

Output: Adult

Common Beginner Mistakes 
❌ Forgetting the colon ":" after "if", "elif", and "else" 
❌ Using incorrect indentation 
❌ Using "=" instead of "==" for comparison 
❌ Writing conditions in the wrong order

Example of wrong order:
marks = 95
if marks >= 60:
    print("Grade B")
elif marks >= 90:
    print("Grade A+")

Output: Grade B 

Why? Because Python stops at the first condition that is true.

Correct order:
if marks >= 90:
    print("Grade A+")
elif marks >= 60:
    print("Grade B")

Real-World AI Example 
Conditional statements are also used in AI applications.
confidence = 0.92
if confidence >= 0.90:
    print("High confidence prediction")
elif confidence >= 0.70:
    print("Medium confidence prediction")
else:
    print("Low confidence prediction")

Output: High confidence prediction 

This type of logic can be used alongside Machine Learning models to decide what action to take based on a prediction or confidence score.

Key Takeaways 
• "if" checks a condition
• "elif" checks additional conditions
• "else" handles everything that doesn't match the previous conditions
• Python uses indentation to define code blocks
• Conditions can be combined using "and", "or", and "not"
• Python executes the first matching condition in an "if/elif/else" chain

➡️ Double Tap ❤️ For More
❤11
In the previous post, we learned how conditional statements allow Python programs to make decisions. Now let's learn how to repeat tasks efficiently using loops.

📖 Phase 1: Programming Fundamentals

📌 Topic 10: Loops — for and while

Loops are used to execute a block of code repeatedly.

Imagine you need to print numbers from 1 to 100. Writing print() 100 times would be inefficient. A loop lets you do it with just a few lines of code.

Why Do We Need Loops?

Loops help us:

• Repeat tasks automatically.
• Process large amounts of data.
• Iterate through lists and other collections.
• Automate repetitive operations.
• Reduce duplicate code.

1. for Loop

A for loop is commonly used when you want to iterate over a sequence or a known range of values.

Example:

for i in range(5):
print(i)


Output:

0
1
2
3
4


Notice that range(5) starts from 0 and stops before 5.

Using range()

You can specify a starting point and step.

for i in range(1, 11):
print(i)


Output:

1
2
3
4
5
6
7
8
9
10


With a step:

for i in range(2, 11, 2):
print(i)


Output:

2
4
6
8
10


2. Looping Through a List

You can directly iterate through a list.

fruits = ["Apple", "Banana", "Mango"]

for fruit in fruits:
print(fruit)


Output:

Apple
Banana
Mango


3. while Loop

A while loop executes as long as a condition remains True.

Example:

count = 1

while count <= 5:
print(count)
count += 1


Output:

1
2
3
4
5


Here, the loop continues until count <= 5 becomes False.

⚠️ Infinite Loops

Be careful with while loops.

This loop never stops:

count = 1

while count <= 5:
print(count)


Why?

Because count never changes, so the condition always remains True. Always make sure the condition can eventually become False.

4. break

break immediately stops the loop.

for i in range(1, 10):
if i == 5:
break
print(i)


Output:

1
2
3
4


5. continue

continue skips the current iteration and moves to the next one.

for i in range(1, 6):
if i == 3:
continue
print(i)


Output:

1
2
4
5


The number 3 is skipped.

6. Nested Loops

A loop can exist inside another loop.

for i in range(1, 4):
for j in range(1, 4):
print(i, j)


Nested loops are commonly used when working with grids, matrices, and combinations of data.

for vs while

Use a for loop when:

👉 You want to iterate through a sequence or range.

Use a while loop when:

👉 You want to continue running code until a condition changes.

Real-World AI Example

Loops are extremely common in AI and Data Science.

For example, you may need to process multiple files:

files = ["data1.csv", "data2.csv", "data3.csv"]

for file in files:
print("Processing:", file)


Output:

Processing: data1.csv
Processing: data2.csv
Processing: data3.csv


The same concept can be used when processing datasets, documents, images, API responses, or multiple AI model outputs.

Common Beginner Mistakes

❌ Creating an infinite while loop.
❌ Forgetting to update the counter.
❌ Misunderstanding the stopping point of range().
❌ Using break when you actually need continue.

Key Takeaways

• Loops allow you to repeat code efficiently.
• for loops are commonly used for sequences and ranges.
• while loops continue while a condition is True.
• break stops a loop completely.
• continue skips the current iteration.
• Nested loops allow you to work with multiple levels of repetition.

➡️ Double Tap ❤️ For More
❤9
🚀 Welcome back to our AI Engineer Roadmap! ❤️

In the previous post, we explored functions and their significance in programming. Now, let's delve deeper into some advanced concepts related to functions that will further enhance your programming skills.

📖 Phase 1: Programming Fundamentals

📌 Topic 12: Advanced Function Concepts

Understanding advanced function concepts will help you write more efficient, readable, and maintainable code.

1. Lambda Functions

Lambda functions are small anonymous functions defined using the lambda keyword. They can take any number of arguments but only have one expression.

Example:

add = lambda x, y: x + y
print(add(5, 3)) # Output: 8


Lambda functions are often used for short operations where defining a full function would be unnecessary.

2. Higher-Order Functions

Higher-order functions are functions that can take other functions as arguments or return them as results.

Example:

def square(x):
return x * x

def apply_function(func, value):
return func(value)

result = apply_function(square, 5)
print(result) # Output: 25


In this example, apply_function takes another function as a parameter and applies it to the given value.

3. Map, Filter, and Reduce

These built-in functions allow you to apply operations on collections like lists.

• map() applies a function to all items in an iterable.

Example:

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


• filter() filters items out of an iterable based on a condition.

Example:

  even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4]


• reduce() (from the functools module) reduces an iterable to a single value using a binary function.

Example:

  from functools import reduce

total = reduce(lambda x, y: x + y, numbers)
print(total) # Output: 10


4. Decorators

Decorators are a powerful way to modify the behavior of a function or class. They allow you to "wrap" another function to extend its behavior without permanently modifying it.

Example:

def decorator_function(original_function):
def wrapper_function():
print("Wrapper executed before {}".format(original_function.__name__))
return original_function()
return wrapper_function

@decorator_function
def display():
print("Display function executed")

display()


Output:

Wrapper executed before display
Display function executed


The @decorator_function syntax is a shorthand for applying the decorator.

5. Function Annotations

Python allows you to add annotations to function parameters and return values for better documentation.

Example:

def greet(name: str) -> str:
return f"Hello, {name}"

print(greet("Alice")) # Output: Hello, Alice


Annotations don't affect the program's execution but serve as hints for developers.

6. Recursive Functions

A recursive function is one that calls itself to solve a problem. It must have a base case to prevent infinite recursion.

Example:

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(5)) # Output: 120


In this example, factorial calls itself until it reaches the base case of n == 0.

7. Scope of Variables

Understanding variable scope is crucial when working with functions.

• Local Scope: Variables defined inside a function are local to that function.

• Global Scope: Variables defined outside any function are global and can be accessed throughout the program.

Example:

x = "global"

def my_function():
global x
x = "local"
print("Inside function:", x)

my_function()
print("Outside function:", x)


Output:

Inside function: local
Outside function: local


Here, the global keyword allows the function to modify the global variable x.

➡️ Double Tap ❤️ For More
❤9
🚀 Welcome back to our AI Engineer Roadmap! ❤️

In the previous posts, we learned about functions and solved some tricky function-based MCQs. Now let's move to the next topic in Python fundamentals.

📖 Phase 1: Programming Fundamentals

📌 Topic 12: Lambda Functions

A Lambda Function is a small, anonymous function that can be written in a single line.

Unlike regular functions created using def, lambda functions are created using the lambda keyword.

Why Do We Need Lambda Functions?

Lambda functions are useful when:
• You need a small function for a short task
• You don't want to define a full function using def
• You need a function temporarily
• You're working with functions like map(), filter(), and sorted()

1. Creating a Lambda Function

A normal function:

def square(x):
return x * x


The same function using lambda:

square = lambda x: x * x
print(square(5))


Output: 25

Lambda Syntax

lambda arguments: expression


For example: lambda x: x + 10
• lambda → Keyword used to create the function
• x → Argument
• x + 10 → Expression that is returned

2. Lambda with Multiple Arguments

A lambda function can accept multiple arguments.

add = lambda a, b: a + b
print(add(10, 20))


Output: 30

multiply = lambda x, y: x * y
print(multiply(5, 4))


Output: 20

3. Lambda with if-else

Lambda functions can also contain conditional expressions.

check = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check(10))
print(check(7))


Output:

Even
Odd


4. Lambda with map()

map() applies a function to every item in an iterable.

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x * x, numbers))
print(squares)


Output: [1, 4, 9, 16, 25]

5. Lambda with filter()

filter() selects elements based on a condition.

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)


Output: [2, 4, 6]

6. Lambda with sorted()

Lambda functions are very useful when sorting complex data.

Example:

students = [
("Rahul", 80),
("Priya", 95),
("Amit", 70)
]

students.sort(key=lambda x: x[1])
print(students)


Output: [('Amit', 70), ('Rahul', 80), ('Priya', 95)]

Here, lambda x: x[1] tells Python to sort using the second element of each tuple.

Lambda vs Regular Function
• Regular function:

def square(x):
return x * x


• Lambda function:

square = lambda x: x * x


Both produce the same result.

When Should You Use Lambda?

Use lambda when:
✅ The function is very small
✅ The operation is simple
✅ You need the function temporarily
✅ You're working with map(), filter(), or sorted()

Avoid lambda when:
❌ The logic becomes complicated
❌ The function needs multiple statements
❌ A meaningful function name and documentation would improve readability

In those situations, a regular def function is usually better.

Real-World AI/Data Example

Lambda functions are commonly used while preprocessing data.

scores = [45, 67, 82, 91, 38]
updated_scores = list(map(lambda x: x / 100, scores))
print(updated_scores)


Output: [0.45, 0.67, 0.82, 0.91, 0.38]

This kind of transformation can be useful when preparing data before feeding it into a Machine Learning model.

Common Beginner Mistakes
❌ Trying to put complex logic into a lambda
❌ Forgetting that a lambda automatically returns its expression
❌ Confusing map() and filter()

Key Takeaways
• Lambda functions are small anonymous functions
• They are created using the lambda keyword
• They can accept multiple arguments
• They return the result of a single expression
• They're especially useful with map(), filter(), and sorted()
• For complex logic, prefer a regular def function

➡️ Double Tap ❤️ For More
❤11