Gen AI · Interview Prep

Python for AIinterview questions & answers

125+ real Python for AIinterview questions with model answers, plus free lessons to learn the concepts. Prepare in English & Hinglish, then practise with an AI mock interview.

11 topics · 125+ questions

Lessons available in both languages

What you’ll learn

  • Why Python for AI?
  • Python syntax basics
  • Functions & modulesFree account
  • Data structuresFree account
  • Working with JSONFree account
  • File handling & .envFree account
  • venv & pipFree account
  • Async PythonFree account
  • Calling APIs (requests)Free account
  • RecapFree account
  • Project: Your first AI script

Why Python for AI?

Think of programming languages like spoken languages. Some are hard to pronounce with tricky grammar; others feel natural and easy to read. Python is the easy-to-read one — a line of Python often looks almost like plain English. That is exactly why the whole AI world picked it.

In Python, you write less to do more. There are no curly braces {} and no semicolons ; at the end of lines — you just indent your code and Python understands the structure. A beginner can read a Python program and roughly guess what it does, even before learning the language. That low barrier is a superpower when you are learning AI, because you spend your energy on ideas, not on fighting the syntax.

But readability is only half the story. The real reason AI runs on Python is the ecosystem: almost every AI tool, model provider, and library ships a Python SDK first. OpenAI, Anthropic (Claude), Google Gemini, Hugging Face, LangChain, PyTorch — all Python-first. If you know Python, you can plug into the entire Gen AI universe.

🌍 Real-world example: To ask an AI model a question, in Python it can be as little as 3 lines: import the library, create a client, send your message. The same task in a language like Java would take many more lines of boilerplate. Fewer lines = fewer bugs = faster learning.

💡 SDK = Software Development Kit — a ready-made library that lets your code talk to a service (like an AI model) without you writing the low-level networking yourself.

💡 Ecosystem = the whole collection of libraries, tools, and community built around a language. Python's AI ecosystem is the biggest in the world.

You do NOT need to be a Python expert to build AI apps. You need the basics — variables, functions, lists/dicts, and calling an API. This chapter gives you exactly that, from zero.

Standard definition: Python is a high-level, readable, interpreted programming language, and it is the default language for AI/ML because every major model provider and framework ships a Python-first SDK.

from openai import OpenAI

client = OpenAI()  # reads your API key from the environment

response = client.responses.create(
    model="gpt-4o-mini",
    input="Explain what an LLM is in one line."
)

print(response.output_text)

Python syntax basics

Think of a recipe card. It has labeled ingredients ("sugar = 2 cups"), and it has steps written one under another, some steps nested under a condition ("if the batter is runny, add more flour"). Python code reads the same way — you label values with names, and you write steps line by line, with nested steps indented underneath.

In Python, a variable is just a labeled box for a value: name = "Riya" puts the text "Riya" in a box called name. You don't declare a type upfront — Python figures it out from the value. The core building-block types are int (whole numbers like 25), float (decimals like 3.14), str (text like "hello"), bool (True/False), and None (Python's way of saying "nothing here"). To print a value mixed with text, use an f-string: f"Hi {name}" — the f before the quotes tells Python to fill in {name} with the variable's value. print(...) shows output on screen.

Decisions use if / elif / else, and repetition uses for (loop over a known sequence, e.g. for i in range(5):) or while (loop while a condition stays True). The single biggest rule that trips up every beginner: Python has no { } braces to mark a blockindentation itself is the block. Everything at the same indent level under an if, for, or while belongs to that block; the moment you un-indent, you're back outside it.

🌍 Real-world example: When you build an AI chat app, you'll write something like: read the user's message into a variable, if the message is empty, print an error; else, loop for each word to count tokens roughly. Every AI script is built from exactly these basic pieces.

💡 Variable = a named box that holds a value, which can change ("vary") later.

💡 f-string = a text string prefixed with f that lets you drop {variable} values straight inside it.

💡 Indentation = the spaces at the start of a line; in Python it is not just style, it defines which lines belong inside a block.

Use 4 spaces per indent level (the Python community standard) and never mix tabs with spaces — mixing them is the #1 cause of a confusing IndentationError. Comments start with # and are ignored by Python — use them to explain why, not what.

Standard definition: Python defines code blocks (for if, for, while, functions, etc.) purely through consistent indentation rather than braces or keywords, and it is dynamically typed — a variable's type is inferred from the value it's assigned, not declared upfront.

# A tiny script using every basic piece
name = "Riya"          # str
age = 21                # int
height = 5.4             # float
is_student = True        # bool
mentor = None             # None = nothing assigned yet

print(f"{name} is {age} years old.")

if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teenager")
else:
    print("Child")

for i in range(3):
    print(f"Loop iteration {i}")

count = 0
while count < 2:
    print(f"While count = {count}")
    count = count + 1

Project: Your first AI script

What we're building: A tiny, complete script — maybe 12 real lines — that talks to a real AI model. This is the moment every piece of Chapter 1 clicks together: variables hold your key and prompt, a dict shapes the request and the response, a file (.env) keeps your secret safe, and requests/the openai SDK carries your message over the network and brings the answer back. By the end you will have run your first real AI call from Python.


Step 0 — The mental model (read first, 30 seconds)

Every AI API call is the same five-beat dance, no matter which library you use:

  1. Load a secret — your API key, kept OUT of your code, read from a .env file.
  2. Build a request — a small dict describing what you want (model, your input/prompt).
  3. Send it — over HTTPS, to the provider's server (OpenAI, in this project).
  4. Get a response — the server replies with JSON; your code turns it into a Python dict.
  5. Read the answer out of the dict and print it.

💡 API key = a secret password that proves the request is coming from you (and lets the provider bill your account). Never hardcode it, never commit it to git.

Keep those five beats in your head — every step below is just one beat, in code.


Step 1 — Store the secret in a .env file

Create a file named .env in your project folder (NOT inside your .py file):

OPENAI_API_KEY=sk-your-real-key-here

What's happening: .env is just a plain text file of KEY=value lines — nothing magic about it. It sits next to your script but is never imported or hardcoded. Add .env to your .gitignore so it never reaches GitHub — a leaked key means someone else spends your money.

🌍 Real-world example: every real AI startup does exactly this — local .env for your machine, and the same variable set as an "Environment Variable" in the hosting dashboard (Vercel, Render, etc.) for production. The code never changes; only where the key comes from changes.


Step 2 — Load the key into Python with python-dotenv

import os
from dotenv import load_dotenv

load_dotenv()
api_key = os.environ["OPENAI_API_KEY"]

What's happening, line by line:

  • import os — the standard library module that reads environment variables.
  • from dotenv import load_dotenv — from the python-dotenv package (pip install python-dotenv).
  • load_dotenv() — opens .env in the current folder and copies every KEY=value line into the process's environment variables. This is a file being read, exactly like with open(...), just automated for you.
  • os.environ["OPENAI_API_KEY"]os.environ behaves like a dict: square brackets look up a key and return its value. api_key is now just a normal Python string variable sitting in memory — never printed, never logged.

💡 Environment variable = a value that lives outside your code, in the process running it. .env + load_dotenv() is the beginner-friendly way to set one for local development.


Step 3 — Build the client

from openai import OpenAI

client = OpenAI(api_key=api_key)

What's happening: OpenAI(...) is a function call that returns an object — the client. It stores your api_key and knows the provider's base URL, so every call you make through client is already authenticated. You built exactly one object and you'll reuse it for every request in this script (and in a bigger app, for the whole program's lifetime).


Step 4 — Build the request

Under the hood, every AI API call wants a small dict shaped roughly like this:

{
  "model": "gpt-4o-mini",
  "input": "What is one interesting fact about the Moon?"
}

What's happening: model picks which AI model answers you; input is your prompt — plain text, the exact same string type you've used since Step 1 of this chapter. The SDK will turn this dict into the JSON body of an HTTPS POST request for you — you never write raw JSON by hand.

💡 Payload = the data you send in the body of a request — here, your model choice + prompt, as a dict that becomes JSON on the wire.


Step 5 — Send it and get a response back

response = client.responses.create(
    model="gpt-4o-mini",
    input="What is one interesting fact about the Moon?"
)

What's happening — trace the network round trip:

  1. client.responses.create(...) packs model + input into that dict, converts it to JSON text, and sends it as the body of an HTTPS POST request to OpenAI's servers, with your api_key in the headers proving it's you.
  2. Your script pauses here — this is a blocking, synchronous call — while the request travels over the internet, the model generates an answer, and the reply travels back. (In Chapter 1's async lesson you saw await exists to not block like this; for one call at a time, blocking is fine.)
  3. The server's reply arrives as raw JSON text. The SDK automatically parses it and hands you back a Python response object — this already did the json.loads() step for you.

Step 6 — Parse the response into a dict

data = response.model_dump()
answer = data["output"][0]["content"][0]["text"]

What's happening: response is a rich Python object, but underneath it is just structured data — the same shape as the JSON the server sent. .model_dump() converts it into a plain dict (nested dicts and lists, exactly like json.loads() would give you from raw JSON text). Then data["output"][0]["content"][0]["text"] walks down into it: "output" is a list of message blocks, [0] grabs the first one, "content" is its list of content pieces, [0] grabs the first piece, and "text" is the actual answer string. This is exactly the list/dict-indexing you practiced in working-with-json — real API responses nest exactly like this.

💡 In practice, the SDK also gives you a shortcut — response.output_text — that does this exact walk for you. Knowing how to do it manually (like above) is what lets you debug when a response looks unexpected, or when you switch to a provider without a shortcut.


Step 7 — Print the answer

print("AI says:", answer)

What's happening: answer is a plain str at this point — all the API machinery is done. print takes it to the terminal, exactly like every print() you've written since Step 1 of this chapter. The AI's reply is now on your screen.


🔁 The raw requests alternative

You don't need the openai SDK — it's a convenience wrapper. Here's the exact same call using plain requests, which makes the JSON parsing fully visible:

import requests

url = "https://api.openai.com/v1/responses"
headers = {"Authorization": f"Bearer {api_key}"}
payload = {"model": "gpt-4o-mini", "input": "What is one interesting fact about the Moon?"}

resp = requests.post(url, headers=headers, json=payload)
data = resp.json()  # <-- this line does the json.loads() for you
answer = data["output"][0]["content"][0]["text"]
print("AI says:", answer)

What's different: requests.post(url, headers=headers, json=payload) builds and sends the exact same HTTPS request the SDK built for you in Step 5 — json=payload tells requests to turn your dict into a JSON body itself. resp.json() is the line to notice: it reads the raw JSON text the server sent back and converts it straight into a Python dict — the manual version of what the SDK did automatically. Same five beats, same dict-walking in the end. The openai SDK exists so you don't have to remember the URL, headers, or endpoint shape by hand.


🔎 The full flow (recap the wiring)

  1. .env file on disk holds OPENAI_API_KEY=... — a secret, never in your .py file.
  2. load_dotenv() reads that file and copies it into environment variables; os.environ["OPENAI_API_KEY"] pulls it into a Python string variable.
  3. OpenAI(api_key=api_key) builds a client object that already knows how to authenticate.
  4. model + input form a small dict — the request payload.
  5. client.responses.create(...) sends that payload as JSON over HTTPS, blocks until the model replies, and parses the JSON reply back into a Python object automatically.
  6. .model_dump() turns that object into a plain dict; dict/list indexing (data["output"][0]["content"][0]["text"]) pulls out the answer string.
  7. print(...) puts it on your screen.

Every single piece — variables, dicts, files, functions, requests/SDKs, JSON — that you learned across this chapter shows up in these 12 lines. This is Chapter 1, assembled.


✅ What you just learned — and what's next

  • Secrets live in .env, loaded with python-dotenv — never hardcoded, never committed.
  • os.environ behaves like a dict — square-bracket lookup by key.
  • A "client" object wraps your key + the provider's connection details so every call is pre-authenticated.
  • Every AI request is a dict (model + input/prompt) that becomes a JSON body.
  • Every AI response is JSON, parsed into a Python dict (.model_dump() or resp.json()) — then you index into it like any nested dict/list.
  • requests (raw HTTP) and the openai SDK (convenience wrapper) do the same underlying HTTPS POST + JSON parse — the SDK just remembers the details for you.

You just wrote and ran your first real AI script. Chapter 2 (LLM Foundations) builds directly on this: what a "prompt" really is, how models use tokens, system vs. user messages, temperature, and how to design prompts that get reliable answers — all sent through the exact same client.responses.create(...) shape you just used.

Standard definition: A minimal AI script loads an API key from environment configuration (never hardcoded), builds a request payload as a dict, sends it to the provider's HTTPS endpoint (via an SDK or raw requests), parses the JSON reply into a dict, and reads the answer out of it — the same five-step pattern behind every LLM API integration.

import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()  # reads .env and loads it into environment variables

api_key = os.environ["OPENAI_API_KEY"]
client = OpenAI(api_key=api_key)

response = client.responses.create(
    model="gpt-4o-mini",
    input="What is one interesting fact about the Moon?"
)

data = response.model_dump()  # response object -> plain Python dict
answer = data["output"][0]["content"][0]["text"]

print("AI says:", answer)

Python for AIinterview questions & answers

10 sample questions below — 125+ in the full bank inside.

What does the `await` keyword do?

`await` pauses the current async function and waits for another async operation to finish, then resumes with the result. It tells Python 'stop here, wait for this task to complete, and give me the result when it's done.'

In simple terms: Think of `await` like pausing a video to wait for a package to arrive, then hitting play once the package is at your door. Example: `data = await fetch_from_api()` pauses the function, waits for the API response, and then stores the result in `data`.

What is an f-string and write a quick example.

An f-string (formatted string literal) lets you embed variables directly into a string using curly braces. Write `f"text {variable}"` instead of concatenating with + or using .format().

In simple terms: Think of f-strings as a template with placeholders. Instead of gluing strings with +, you mark slots with {} and fill them. Example: `name = "Alice"; print(f"Hello {name}")` outputs `Hello Alice`. Cleaner than `"Hello " + name`.

What is the difference between sync and async code?

Sync code runs line-by-line, waiting for each task to finish before moving to the next. Async code can start a task and move on to other work while waiting for it to complete, then come back when it's ready. Async is much faster when you have many tasks that involve waiting (like API calls).

In simple terms: Think of sync like ordering food at a restaurant where you wait at the counter until your order is done before leaving. Async is like ordering and getting a number — you go sit down and do other things, and when your number is called, you pick up your food. Example: sync waits for one API call to finish before starting the next; async starts all 10 API calls at once and processes results as they come back.

What does `async def` mean in Python?

`async def` is how you declare a function that can pause itself and let other code run while it waits. A regular `def` function runs to completion without pausing; an `async def` function returns a coroutine (a pausable task) that you have to `await` or run with `asyncio.run()`.

In simple terms: Think of `async def` like a function that can take a nap and let other things happen while it sleeps. A normal function is stubborn — it runs all the way through. Example: `async def fetch_data():` creates a function that can pause at `await` points, and you'd call it like `await fetch_data()` or `asyncio.run(fetch_data())`.

What does an HTTP 401 status code mean, and when would you see it?

HTTP 401 means 'Unauthorized' — the server received your request but rejected it because you didn't provide valid authentication (like a missing or incorrect API key). This is common when calling APIs that require authentication.

In simple terms: A 401 is like showing up to a password-protected exam but forgetting your roll number — the exam hall staff knows it's you, but the rules say 'No roll number, no entry.' Example: if you call an LLM API without an API key or with an expired one, you'll get a 401 response instead of the AI-generated text.

How do you extract JSON data from a requests response?

Call the .json() method on the Response object. It parses the response body (which is a JSON string) and returns a Python dict. For example, response.json() converts the JSON text into a dictionary you can work with.

In simple terms: The .json() method is like a translator who reads a foreign instruction manual and converts it into your language — you get a Python dict you can actually use. Example: if the API returns '{"name": "Aman", "age": 25}' as text, response.json() gives you {'name': 'Aman', 'age': 25}, a dict you can access with data['name'].

What is the difference between HTTP GET and POST requests?

GET requests retrieve data from a server without modifying it; the data is passed in the URL. POST requests send data to the server to create or modify something; the data goes in the request body, which is more secure for sensitive information like passwords or API keys.

In simple terms: Think of GET like asking the librarian 'Can you show me the book titled XYZ?' — you're only requesting information. POST is like 'Please add this new book to the library' — you're sending something to be stored. Example: requests.get('https://api.example.com/users?id=5') retrieves user 5, but requests.post('https://api.example.com/users', json={'name':'Raj'}) creates a new user.

Where should you store your API key when building an app?

Store your API key in environment variables, typically in a .env file that you add to .gitignore so it never gets committed to git. Load it using a library like python-dotenv, then pass it to your API requests as a header.

In simple terms: An API key is like your bank PIN — you'd never write it on a sticky note on your desk or shout it in public. A .env file is like a locked drawer in your desk (that stays on your computer), and .gitignore ensures it never leaves your machine. Example: in .env write API_KEY=abc123, then use os.getenv('API_KEY') to load it in your code.

What does the requests.get() method return?

It returns a Response object that contains the server's reply, including the status code, headers, and the response body (usually as text or JSON). You can access the body as JSON using response.json() or as text using response.text.

In simple terms: A Response object is like opening an envelope from the postal service — the envelope itself is the Response, and inside you have the letter (text), a stamp (headers), and a note about delivery status (status_code). Example: resp = requests.get('https://api.example.com/data'), then resp.status_code gives you 200, resp.json() gives you the data as a dict.

What is a coroutine?

A coroutine is a pausable task that an `async def` function creates. When you call an `async def` function without `await`, it returns a coroutine object (not the result). Coroutines can be paused and resumed, which is exactly what `await` does.

In simple terms: Think of a coroutine like a recipe card you write but haven't started cooking yet. The recipe is ready to go, but no one is cooking. When you `await` it, someone starts cooking and you wait for the dish. Example: `async def cook(): ...` creates a recipe; `cook()` gives you a coroutine (recipe card); `await cook()` actually cooks it.

115+ more Python for AI questions inside

Create a free account to read the full question bank, learn every topic, and practise with an AI mock interview.

Unlock all questions — free

Ready to practise Python for AI?

Unlock every topic free, then face an AI interviewer that asks follow-ups and grades your answers.