Google now writes 75% of its code using AI.
If Google, the tech giant, is doing that, then it’s a proof that:
Tomorrow's recruiters will only hire people who can build with AI.
So before you get irrelevant, check out the E&ICT Academy IIT Roorkee's AI & ML Program.
✅ Live sessions from IIT professors & industry mentors
✅ Hands-on projects with Flipkart & Mamaearth
✅ Networking through Campus Immersion
✅ Placement support through Masai's network of 5000+ companies
🗓 Entrance Test: 26th July
🔗 https://tinyurl.com/DS-26Jul-005
Last 6 Hours Remaining!
Before the application closes for E&ICT IIT Roorkee AI & ML Program.
Don't miss out on the chance to:
• Learn live from IIT professors & industry experts
• Build real AI projects
• Get Placement Support from Masai.
Register NOW
🚀 AI Interview Questions with Answers (Part 13)
121. What is OpenCV, and what are its applications?
OpenCV (Open Source Computer Vision Library) is an open-source library used for computer vision and image processing.
Applications:
• Face detection and recognition
• Object detection
• Image filtering and enhancement
• Motion tracking
• OCR (Optical Character Recognition)
• Video analysis
• Autonomous vehicles
OpenCV supports Python, C++, and Java.
122. What is the Hugging Face Transformers library?
Hugging Face Transformers is an open-source Python library that provides access to thousands of pre-trained Transformer models for NLP, computer vision, audio, and multimodal AI.
Popular models include: BERT, GPT, T5, Llama, Mistral
Benefits:
• Easy-to-use APIs
• Pre-trained models
• Fine-tuning support
• Integration with PyTorch and TensorFlow
123. What is LangChain, and how is it used in LLM applications?
LangChain is an open-source framework for building applications powered by Large Language Models.
It helps developers connect LLMs with: Databases, APIs, Documents, Vector databases, External tools
Common use cases: AI chatbots, RAG applications, AI agents, Document Q&A, Workflow automation
124. What is LlamaIndex, and what problem does it solve?
LlamaIndex is a framework that helps connect Large Language Models with private or enterprise data.
It simplifies: Data ingestion, Index creation, Retrieval, Querying documents
LlamaIndex is widely used in Retrieval-Augmented Generation (RAG) applications.
125. What is Ollama, and how is it used for running local LLMs?
Ollama is a tool that allows users to download, run, and manage Large Language Models locally on their own computers.
Benefits:
• Runs models offline
• Better privacy
• Lower latency
• No API costs
• Supports models such as Llama, Mistral, Gemma, and Phi
Used for local AI development and experimentation.
126. How do you use the OpenAI API in AI applications?
The OpenAI API enables dev
🚨 Two headlines from the same month:
→ TCS cuts 12,000 jobs → AI/ML hiring grows 45%
AI isn’t ending careers. It’s sorting them.
Pick your side of the sort with the Certification in AI & ML - Vishlesan i-Hub, IIT Patna.
✅ 9 Months | Online | Open to 12th pass & above
✅ IIT faculty & industry mentors, live
✅ Curriculum built for 2026: LLMs, RAG, AI Agents, MLOps
✅ Placement support through Masai's network of 5000+ companies
The sorting has already started. Your test is this Sunday.
🗓 ₹99 Qualifier - 2nd August
🔗 https://tinyurl.com/DS-29JUL-005
⏳ The sorting doesn’t wait for you.
TCS cut 12,000. AI/ML hiring grew 45%. Tomorrow decides which list you’re building toward.
Certification in AI & ML - Vishlesan i-Hub, IIT Patna ₹99 qualifier · Sunday · one attempt, no retakes
Slots close before the test.
🔗 https://tinyurl.com/DS-29JUL-005
🚀 Thanks for the amazing response on the last post! ❤️
Today, let's start with the first topic of the roadmap:
🚀 Phase 1: Programming Fundamentals
📌 Topic 1: What is Programming?
Programming is the process of giving instructions to a computer so it can perform specific tasks. These instructions are written in a programming language such as Python, Java, C++, or JavaScript.
Think of programming like writing a recipe. Just as a recipe tells a chef how to prepare a dish step by step, a program tells a computer exactly what to do, step by step.
Why is Programming Important?
Programming allows us to:
• Build websites and mobile apps
• Create AI and Machine Learning models
• Analyze data
• Automate repetitive tasks
• Develop games
• Build robots and IoT devices
• Create business software
Without programming, computers cannot make decisions or perform useful work.
How Does Programming Work?
The basic flow is:
1. Write code.
2. The code is translated into machine-understandable instructions.
3. The computer executes those instructions.
4. The desired output is produced.
Example:
Input: 5 + 10
Output: 15
The computer follows the instruction exactly as written.
Characteristics of a Good Program
✅ Correct – Produces the right output.
✅ Efficient – Uses minimum time and memory.
✅ Readable – Easy to understand.
✅ Reusable – Can be used again in different projects.
✅ Maintainable – Easy to update and fix.
Real-Life Examples of Programming
• ATM machines process transactions using programs.
• Google Maps finds the best route using programs.
• Netflix recommends movies using AI programs.
• ChatGPT generates responses using AI programs.
• Banking apps securely transfer money using programs.
Programming Languages
Some popular programming languages include:
• Python – AI, Data Science, Automation, Web Development
• Java – Enterprise Applications, Android
• JavaScript – Websites
• C++ – Games, High-performance Softw
In the previous post, we learned what programming is and why it is the foundation of every software application. Today, let's move to the next topic.
📖 Phase 1: Programming Fundamentals
📌 Topic 2: What is Python?
Python is a high-level, interpreted, and general-purpose programming language that is known for its simple syntax and readability. It was created by Guido van Rossum and first released in 1991.
Python allows you to write powerful programs with fewer lines of code compared to many other programming languages, making it an excellent choice for beginners as well as professionals.
Why is Python So Popular?
Python is one of the most widely used programming languages because it is:
• Easy to learn and read
• Beginner-friendly
• Supports multiple programming styles
• Has a huge collection of libraries
• Works on Windows, macOS, and Linux
• Backed by a large developer community
Where is Python Used?
Python is used in many industries and applications, including:
• Artificial Intelligence (AI)
• Machine Learning
• Data Science
• Data Analysis
• Web Development
• Automation and Scripting
• Cybersecurity
• Cloud Computing
• Game Development
• Internet of Things (IoT)
Why is Python the First Choice for AI?
Most AI engineers use Python because it provides powerful libraries that make AI development much easier.
Some popular Python libraries include:
• NumPy – Numerical computing
• Pandas – Data analysis
• Matplotlib – Data visualization
• Scikit-learn – Machine Learning
• TensorFlow – Deep Learning
• PyTorch – Deep Learning
• OpenCV – Computer Vision
• Transformers – Large Language Models (LLMs)
Features of Python
✅ Simple and readable syntax
✅ Free and open source
✅ Interpreted language
✅ Object-oriented
✅ Platform independent
✅ Huge ecosystem of libraries
✅ Easy to integrate with other technologies
Python vs Other Languages
Compared to languages like C++ or Java, Python requi
In the previous post, we learned what Python is and why it is the most popular programming language for AI. Before writing our first program, we need to set up our development environment.
📖 Phase 1: Programming Fundamentals
📌 Topic 3: Installing Python & VS Code
To start coding in Python, you need two things:
• Python – The programming language that will run your code.
• Visual Studio Code (VS Code) – A lightweight and powerful code editor where you'll write and manage your programs.
Step 1: Install Python
1. Visit the official Python website.
2. Download the latest stable version for your operating system.
3. Run the installer.
4. Make sure to check "Add Python to PATH" before clicking Install Now.
5. Complete the installation.
Step 2: Verify the Installation
Open Command Prompt (Windows) or Terminal (macOS/Linux) and type:
python --version
or
python3 --version
If Python is installed successfully, you'll see something like:
Python 3.x
Step 3: Install VS Code
1. Download and install Visual Studio Code.
2. Open VS Code after installation.
3. Go to the Extensions tab.
4. Search for Python.
5. Install the official Python extension by Microsoft.
Step 4: Create Your First Python File
• Open VS Code.
• Create a new folder for your project.
• Create a new file named: hello.py
Step 5: Write Your First Python Program
print("Hello, World!")
Step 6: Run the Program
Click the Run button in VS Code or open the terminal and run:
python hello.py
Output:
Hello, World!
Why Use VS Code?
VS Code is one of the most popular code editors because it offers:
✅ Intelligent code suggestions (IntelliSense)
✅ Built-in debugging
✅ Integrated terminal
✅ Git & GitHub support
✅ Extensions for almost every programming language
✅ Lightweight and fast
Common Beginner Mistakes
❌ Forgetting to check "Add Python to PATH" during installation.
❌ Installing Python but not verifying it using the terminal.
❌ Saving the file without the ".py" extension.
❌ Runni
In the previous post, we successfully installed Python and VS Code and wrote our first Python program. Now, let's learn one of the most important concepts in programming.
📖 Phase 1: Programming Fundamentals
📌 Topic 4: Variables
A variable is a named container used to store data in memory. Instead of using the actual value repeatedly, we store it in a variable and use the variable name whenever needed.
Think of a variable like a labeled box. You can store different items inside the box, and whenever you need that item, you simply refer to the label instead of searching for the item.
Why Do We Need Variables?
Variables help us:
• Store data for later use.
• Reuse values multiple times.
• Make programs easier to read.
• Update values whenever required.
• Avoid writing the same value repeatedly.
Creating Variables in Python
In Python, you don't need to declare the data type. Simply assign a value using the "=" operator.
Example:
name = "Ajay"
age = 29
salary = 400000
Here:
• "name" stores a string.
• "age" stores an integer.
• "salary" stores a number.
Printing Variables
You can display variable values using the "print()" function.
name = "Aman"
age = 25
print(name)
print(age)
Output:
Aman
25
Updating Variables
Variables can be changed anytime.
score = 80
score = 95
print(score)
Output:
95
The old value is replaced with the new value.
Multiple Variable Assignment
You can assign multiple variables in one line.
x, y, z = 10, 20, 30
print(x)
print(y)
print(z)
Output:
10
20
30
Naming Rules for Variables
✅ Variable names can contain letters, numbers, and underscores.
✅ Variable names must start with a letter or underscore.
✅ Variable names are case-sensitive ("age" and "Age" are different).
❌ Variable names cannot start with a number.
❌ Variable names cannot contain spaces or special characters.
Good vs Bad Variable Names
✅ Good:
student_name = "Rahul"
total_marks = 450
is_logged_in = Tr
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")
Examp
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 usin
🤖💻 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
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
Video Sber_gigachat_50mb_compressed.mp4 · 7.7 MB · click to show
🚀 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
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.
Exa
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.
Op
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 =
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:
🚀 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. Th
🚀 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),