Hirenix kaise padhata hai
Ek chapter. 90 minute.
Interview ke liye taiyaar.
Har concept ek real-world problem se — jaisa production code mein aata hai, waisa. Ratna nahi padta, samajh aa jaata hai. Har question ka model answer diya hai: interviewer ko exactly kya bolna hai, aur kyun. Phir usi chapter ka AI mock interview.
- 📖Concept, 5 min meinJargon nahi — seedhi baat
- 🛠️Real-world problemJaisa production code mein aata hai
- 💬Model answerInterview mein kya bolna hai
- 🧠FlashcardsRevision 10 min mein
- 🤖AI mock interviewFollow-up bhi poochta hai
- 📊Weak topicsKahan phans rahe ho, pata chale

Farq content ka nahi, filter ka hai — sirf wahi jo production mein actually use hota hai aur interview mein actually poocha jaata hai. Kitaabi topics jo industry mein kahin nahi chalte, wo yahan nahi milenge.
What you’ll learn
- ●AI ke liye Python kyun?
- ●Python syntax basics
- Functions & modulesFree account
- Data structuresFree account
- JSON ke saath kaamFree account
- File handling & .envFree account
- venv & pipFree account
- Async PythonFree account
- API calls (requests)Free account
- RecapFree account
- ●Project: Tera pehla AI script
AI ke liye Python kyun?
Programming languages ko bolne wali languages ki tarah socho. Kuch languages ka pronunciation mushkil hota hai, grammar tedhi hoti hai; kuch natural aur padhne me easy lagti hai. Python wahi easy-to-read wali hai — Python ki ek line aksar plain English jaisi dikhti hai. Isi wajah se poori AI duniya ne ise chuna.
Python me tu kam likh ke zyada kaam karta hai. Na curly braces {} hote hain, na line ke end me semicolon ; — bas apne code ko indent (thoda andar) karta hai aur Python structure samajh jaata hai. Ek beginner Python program padh ke lagbhag guess kar sakta hai ki kya ho raha hai, language seekhne se pehle bhi. Ye low barrier AI seekhte waqt superpower hai, kyunki teri energy ideas pe lagti hai, syntax se ladne me nahi.
Par readability aadhi kahani hai. AI Python pe chalne ka asli reason hai ecosystem: lagbhag har AI tool, model provider, aur library sabse pehle Python SDK deti hai. OpenAI, Anthropic (Claude), Google Gemini, Hugging Face, LangChain, PyTorch — sab Python-first. Python aata hai toh poore Gen AI universe me plug ho sakta hai.
🌍 Real-world example: AI model se sawaal poochhne ke liye, Python me sirf 3 lines lag sakti hain: library import karo, client banao, message bhejo. Wahi kaam Java jaisi language me bahut zyada boilerplate lines lega. Kam lines = kam bugs = fast learning.
💡 SDK = Software Development Kit — ek ready-made library jo tere code ko kisi service (jaise AI model) se baat karne deti hai, bina tere low-level networking khud likhe.
💡 Ecosystem = ek language ke around bani poori libraries, tools aur community. Python ka AI ecosystem duniya ka sabse bada hai.
AI apps banane ke liye Python expert hona zaroori NAHI hai. Basics chahiye — variables, functions, lists/dicts, aur ek API call karna. Ye chapter tujhe wahi deta hai, zero se.
Standard definition (interview me bolo): 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
Ek recipe card soch. Usme labeled ingredients hote hain ("sugar = 2 cups"), aur steps ek ke niche ek likhe hote hain, kuch steps ek condition ke andar nested hote hain ("agar batter runny hai, toh aur flour daalo"). Python code bhi waise hi padhta hai — tu values ko naam deta hai, aur steps line by line likhta hai, jaha nested steps indent (andar) hoke likhe jaate hain.
Python me, ek variable bas ek labeled box hota hai kisi value ke liye: name = "Riya" "Riya" text ko name naam ke box me daal deta hai. Type pehle se declare karne ki zaroorat nahi — Python value se khud samajh leta hai. Core building-block types hain int (whole numbers jaise 25), float (decimals jaise 3.14), str (text jaise "hello"), bool (True/False), aur None (Python ka "yaha kuch nahi hai" bolne ka tareeka). Kisi value ko text ke saath mila ke print karne ke liye f-string use karo: f"Hi {name}" — quotes se pehle wala f Python ko batata hai ki {name} ki jagah us variable ki value bhardo. print(...) screen pe output dikhata hai.
Decisions ke liye if / elif / else use hota hai, aur repetition ke liye for (kisi known sequence pe loop, jaise for i in range(5):) ya while (jab tak condition True rahe, tab tak loop). Har beginner ko trip karne wala sabse bada rule: Python me { } braces nahi hote block mark karne ke liye — indentation hi block hoti hai. if, for, ya while ke niche jitni bhi lines same indent level pe hain, wo sab us block ka hissa hain; jaise hi tu un-indent karta hai, tu us block se bahar ho jaata hai.
🌍 Real-world example: Jab tu ek AI chat app banayega, tu kuch aisa likhega: user ka message ek variable me read karo,
ifmessage empty hai, error print karo;else,forse har word pe loop karke roughly tokens count karo. Har AI script inhi basic pieces se bani hoti hai.
💡 Variable = ek named box jo ek value hold karta hai, jo baad me change ("vary") ho sakti hai.
💡 f-string = ek text string jiske aage
flagta hai, jisse tu{variable}values seedhe usme daal sakta hai.
💡 Indentation = line ke start ki spaces; Python me ye sirf style nahi hai, ye define karta hai ki konsi lines kis block ke andar hain.
Har indent level ke liye 4 spaces use karo (Python community standard) aur kabhi tabs aur spaces mix mat karo — inhe mix karna confusing IndentationError ki #1 wajah hai. Comments # se shuru hote hain aur Python inhe ignore karta hai — inhe kya nahi, kyun explain karne ke liye use karo.
Standard definition (interview me bolo): 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 + 1Project: Tera pehla AI script
Kya bana rahe hain: Ek chhota, complete script — shaayad 12 real lines — jo ek real AI model se baat karta hai. Ye wahi moment hai jab Chapter 1 ka har piece ek saath click karta hai: variables tumhari key aur prompt rakhte hain, ek dict request aur response ko shape karta hai, ek file (.env) tumhara secret safe rakhti hai, aur requests/openai SDK tumhara message network pe le jaata hai aur jawab wapas laata hai. End tak tumne Python se apni pehli real AI call chala di hogi.
Step 0 — Mental model (pehle padho, 30 second)
Har AI API call same paanch-beat dance hai, chaahe koi bhi library use karo:
- Secret load karo — apni API key, code se BAAHAR,
.envfile se padhi hui. - Request banao — ek chhota dict jo batata hai tumhe kya chahiye (
model, tumharainput/prompt). - Bhej do — HTTPS pe, provider ke server ko (is project mein, OpenAI).
- Response wapas lo — server JSON se reply karta hai; tumhara code use Python dict mein badalta hai.
- Dict se answer nikaalo aur print karo.
💡 API key = ek secret password jo prove karta hai ki request tumse aa rahi hai (aur provider ko tumhara account bill karne deta hai). Kabhi hardcode mat karo, kabhi git mein commit mat karo.
Ye paanch beats dimaag mein rakho — neeche har step bas ek beat hai, code mein.
Step 1 — Secret ko .env file mein store karo
Apne project folder mein .env naam ki file banao (apni .py file ke ANDAR nahi):
OPENAI_API_KEY=sk-your-real-key-here
Ho ye raha hai: .env bas ek plain text file hai jismein KEY=value lines hain — koi magic nahi. Ye tumhare script ke bagal mein rehti hai par kabhi import ya hardcode nahi hoti. .env ko apne .gitignore mein daalo taaki wo kabhi GitHub tak na pahunche — leaked key ka matlab hai koi aur tumhara paisa kharch kare.
🌍 Real-world example: har real AI startup bilkul yahi karti hai — apni machine ke liye local
.env, aur production mein hosting dashboard (Vercel, Render, etc.) mein wahi variable set "Environment Variable" ke roop mein. Code kabhi nahi badalta; sirf key kahaan se aati hai wo badalta hai.
Step 2 — python-dotenv se key ko Python mein load karo
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.environ["OPENAI_API_KEY"]
Line-by-line ho ye raha hai:
import os— standard library module jo environment variables padhta hai.from dotenv import load_dotenv—python-dotenvpackage se (pip install python-dotenv).load_dotenv()— current folder mein.envopen karta hai aur harKEY=valueline ko process ke environment variables mein copy karta hai. Ye ek file read hi hai, bilkulwith open(...)jaisa, bas tumhare liye automated.os.environ["OPENAI_API_KEY"]—os.environek dict jaisa behave karta hai: square brackets se key lookup hoti hai aur value milti hai.api_keyab bas ek normal Python string variable hai jo memory mein hai — kabhi print, kabhi log nahi hota.
💡 Environment variable = ek value jo tumhare code ke bahar, use chalane wale process mein rehti hai.
.env+load_dotenv()local development ke liye ek beginner-friendly tarika hai isse set karne ka.
Step 3 — Client banao
from openai import OpenAI
client = OpenAI(api_key=api_key)
Ho ye raha hai: OpenAI(...) ek function call hai jo object return karta hai — client. Ye tumhara api_key store karta hai aur provider ka base URL jaanta hai, to client se ki gayi har call already authenticated hoti hai. Tumne exactly ek object banaya aur ise is poore script mein reuse karoge (aur ek bade app mein, poore program ki lifetime ke liye).
Step 4 — Request banao
Under the hood, har AI API call ko ek chhota dict chahiye jo lagbhag aisa dikhta hai:
{
"model": "gpt-4o-mini",
"input": "What is one interesting fact about the Moon?"
}
Ho ye raha hai: model chunta hai kaunsa AI model jawab dega; input tumhara prompt hai — plain text, wahi string type jo tum is chapter ke Step 1 se use kar rahe ho. SDK is dict ko tumhare liye HTTPS POST request ke JSON body mein badal dega — tumhe kabhi raw JSON haath se nahi likhna padta.
💡 Payload = wo data jo tum request ke body mein bhejte ho — yahaan, tumhara model choice + prompt, ek dict ke roop mein jo wire pe JSON ban jaata hai.
Step 5 — Bhej do aur response wapas lo
response = client.responses.create(
model="gpt-4o-mini",
input="What is one interesting fact about the Moon?"
)
Ho ye raha hai — network round trip trace karo:
client.responses.create(...)model+inputko us dict mein pack karta hai, JSON text mein convert karta hai, aur OpenAI ke servers ko HTTPS POST request ke body mein bhej deta hai, headers mein tumharaapi_keydaal ke prove karta hai ki ye tum ho.- Tumhara script yahaan pause hota hai — ye ek blocking, synchronous call hai — jab tak request internet pe travel karti hai, model jawab generate karta hai, aur reply wapas aata hai. (Chapter 1 ke async lesson mein tumne dekha tha ki
awaitisliye hota hai taaki isi tarah block na ho; ek waqt mein ek call ke liye, blocking theek hai.) - Server ka reply raw JSON text ke roop mein aata hai. SDK use automatically parse karta hai aur tumhe wapas ek Python
responseobject deta hai — isne tumhare liyejson.loads()wala step already kar diya.
Step 6 — Response ko dict mein parse karo
data = response.model_dump()
answer = data["output"][0]["content"][0]["text"]
Ho ye raha hai: response ek rich Python object hai, par uske neeche wo bas structured data hai — bilkul us JSON jaisi shape jo server ne bheja. .model_dump() ise ek plain dict mein convert karta hai (nested dicts aur lists, bilkul waisi jaisi json.loads() raw JSON text se deta). Fir data["output"][0]["content"][0]["text"] uske andar chalta hai: "output" message blocks ki ek list hai, [0] pehla leta hai, "content" uski content pieces ki list hai, [0] pehla piece leta hai, aur "text" asli answer string hai. Ye bilkul wahi list/dict-indexing hai jo tumne working-with-json mein practice ki thi — real API responses bilkul aise hi nest hote hain.
💡 Practically, SDK tumhe ek shortcut bhi deta hai —
response.output_text— jo ye exact walk tumhare liye kar deta hai. Manually kaise karte hain (jaise upar) ye jaanna hi tumhe debug karne deta hai jab response unexpected lage, ya jab tum kisi provider pe switch karo jiska shortcut na ho.
Step 7 — Answer print karo
print("AI says:", answer)
Ho ye raha hai: answer ab bas ek plain str hai — saari API machinery ho chuki. print ise terminal pe le jaata hai, bilkul har print() jaisa jo tumne is chapter ke Step 1 se likha hai. AI ka reply ab tumhari screen pe hai.
🔁 Raw requests alternative
Tumhe openai SDK ki zaroorat nahi — ye ek convenience wrapper hai. Yahaan wahi call hai plain requests ke saath, jo JSON parsing ko poori tarah visible bana deta hai:
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() # <-- ye line tumhare liye json.loads() karti hai
answer = data["output"][0]["content"][0]["text"]
print("AI says:", answer)
Kya alag hai: requests.post(url, headers=headers, json=payload) bilkul wahi HTTPS request banata aur bhejta hai jo SDK ne Step 5 mein tumhare liye banaya tha — json=payload requests ko batata hai ki tumhara dict khud JSON body bana de. resp.json() wo line hai jo notice karni hai: ye server ka bheja raw JSON text padhta hai aur seedha Python dict mein convert kar deta hai — SDK ne jo automatically kiya uska manual version. Same paanch beats, end mein same dict-walking. openai SDK isliye hai taaki tumhe URL, headers, ya endpoint shape haath se yaad na rakhna pade.
🔎 Poora flow (wiring ka recap)
.envfile disk peOPENAI_API_KEY=...rakhti hai — ek secret, kabhi tumhari.pyfile mein nahi.load_dotenv()us file ko padhta hai aur environment variables mein copy karta hai;os.environ["OPENAI_API_KEY"]use ek Python string variable mein khinch leta hai.OpenAI(api_key=api_key)ekclientobject banata hai jo already authenticate karna jaanta hai.model+inputek chhota dict banate hain — request payload.client.responses.create(...)us payload ko JSON ke roop mein HTTPS pe bhejta hai, model ke reply tak block karta hai, aur JSON reply ko automatically wapas Python object mein parse karta hai..model_dump()us object ko plain dict mein badalta hai; dict/list indexing (data["output"][0]["content"][0]["text"]) answer string nikaalta hai.print(...)use tumhari screen pe daal deta hai.
Har ek piece — variables, dicts, files, functions, requests/SDKs, JSON — jo tumne is chapter mein seekha, in 12 lines mein dikhta hai. Yahi hai Chapter 1, assembled.
✅ Jo tumne abhi seekha — aur aage kya hai
- Secrets
.envmein rehte hain,python-dotenvse load hote hain — kabhi hardcode nahi, kabhi commit nahi. os.environdict jaisa behave karta hai — key se square-bracket lookup.- Ek "client" object tumhari key + provider ki connection details wrap karta hai, taaki har call pre-authenticated ho.
- Har AI request ek dict hai (
model+input/prompt) jo JSON body ban jaata hai. - Har AI response JSON hai, jo Python dict mein parse hota hai (
.model_dump()yaresp.json()) — fir tum usmein index karte ho kisi bhi nested dict/list ki tarah. requests(raw HTTP) auropenaiSDK (convenience wrapper) dono same underlying HTTPS POST + JSON parse karte hain — SDK bas details tumhare liye yaad rakhta hai.
Tumne abhi apna pehla real AI script likha aur chalaya. Chapter 2 (LLM Foundations) isi pe seedha banta hai: "prompt" asal mein kya hota hai, models tokens kaise use karte hain, system vs. user messages, temperature, aur reliable answers dilaane wale prompts kaise design karte hain — sab usi client.responses.create(...) shape se bheje jaate hain jo tumne abhi use kiya.
Standard definition (interview me bolo): 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.
Python me `async def` ka matlab kya hai?
`async def` ek function declare karne ka tarika hai jo apne aap ko pause kar sakta hai aur doosre code ko run hone de sakta hai jab wait kar raha ho. Normal `def` function se pehle poora chalta hai, lekin `async def` function ek coroutine return karta hai (ek pausable task) jise `await` karna padta hai ya `asyncio.run()` se chalana padta hai.
In simple terms: `async def` ko aise function samjho jo nap le sakta hai aur doosre kaam chal sakate hain jab woh so raha ho. Normal function stubborn hota hai — bilkul chalta hai. Jaise: `async def fetch_data():` ek function banata hai jo `await` points pe pause ho sakta hai, aur isko `await fetch_data()` ya `asyncio.run(fetch_data())` se bulate ho.
Python ka indentation rule kya hai, aur kyu important hai?
Python indentation (spaces, braces nahi) use karta code blocks define karne ke liye. Function, loop, ya if-block ke andar, tum code ko indent karte ho; dedent karne se block end hota hai. Ye readable code force karta hai aur Python ka syntax hai.
In simple terms: Python ka rule: indentation HI language hai, optional nahi. Dusri languages `{ }` use karti hain, Python kahta hai 'apna code line up karo, ye rule hai.' Jaise: `if x > 5: print("yes")` — print indent hai isliye if ke andar hai. Galat indent = SyntaxError.
Sync aur async code me kya farq hai?
Sync code line-by-line chalta hai, har task ke khatm hone ka wait karti hai pehle agle task se pehle. Async code ek task start kar ke aage badh sakta hai, aur jab task ready ho toh wapas aata hai. Async bahut fast hota hai jab tumhare pass bahut saari tasks ho jo waiting involve karti hain (jaise API calls).
In simple terms: Sync ko restaurant me counter par order dena samjho, jab tak order na ho jaaye tab tak wait karte ho. Async hai number lena, beithna, aur jab number call ho toh order lena. Jaise: sync ek API call khatm hone ka wait karti hai, pehle doosra shuru kare; async 10 API calls ek saath shuru karti hai aur results aate hain jaise aate hain.
F-string kya hota hai? Ek quick example likho.
F-string (formatted string literal) string me directly variables embed karne deta hai curly braces use karke. `f"text {variable}"` likho instead concatenating + se ya .format() se.
In simple terms: F-strings ko ek template samjho jisme placeholders hain. String ko + se glue karne ki jagay, tum {} se slots mark karte ho aur fill karte ho. Jaise: `name = "Alice"; print(f"Hello {name}")` output hoga `Hello Alice`. `"Hello " + name` se clean hai.
Requests response se JSON data ko extract kaise karoge?
Response object pe .json() method call karo. Yeh response body (jo JSON string hota hai) ko parse karke Python dict return karta hai. Jaise response.json() JSON text ko dictionary mein convert kar deta hai jo tum use kar sakte ho.
In simple terms: .json() method ek translator jaisa kaam karta hai jo foreign manual padhke apni language mein convert kar de — tume ek Python dict milta hai jo actually use kar sakes. Jaise API '{"name": "Aman", "age": 25}' text return kare, to response.json() se {'name': 'Aman', 'age': 25} dict milta hai aur data['name'] se 'Aman' nikal sakte ho.
HTTP GET aur POST requests mein kya farq hai?
GET request ek tarah ka puchu-putachchh hai jisme tum server se data maangta ho bina kuch badla ke; data URL mein chala jaata hai. POST request mein tum server ko data bhejta ho naya kuch banane ya modify karne ke liye; data request body mein jaata hai jo sensitive info (jaise passwords ya API keys) ke liye zyada safe hota hai.
In simple terms: GET ko socho librarian se kehne jaisa 'Mujhe XYZ naam ki kitaab dikha do?' — tum sirf kuch manga rahe ho. POST jaisa hai 'Mere pass ek nai kitaab hai, ishe library mein add karo' — tum kuch bhej rahe ho store hone ke liye. Jaise requests.get('https://api.example.com/users?id=5') user 5 ka data lata hai, lekin requests.post('https://api.example.com/users', json={'name':'Raj'}) ek naya user banata hai.
requests.get() method kya return karta hai?
Yeh ek Response object return karta hai jo server ka jawab contain karta hai — is mein status code, headers, aur response body hota hai (zyada-tar text ya JSON ke form mein). Response.json() se body ko JSON ke taur pe access kar sakte ho, ya response.text se text ke taur pe.
In simple terms: Response object ek postal envelop kholne jaisa hai — pura envelope hi Response hota hai, andar letter (text), stamp (headers), aur delivery status note (status_code) hota hai. Jaise resp = requests.get('https://api.example.com/data'), phir resp.status_code se 200 milta hai aur resp.json() se data dict ke form mein milta hai.
App banate waqt API key kahan store karega?
API key ko environment variables mein store karo, zyada-tar .env file mein jo .gitignore mein add ho taaki git mein commit na ho. Isko python-dotenv library se load karo, phir API requests mein header ke form mein pass karo.
In simple terms: API key teri bank PIN jaisa secret hota hai — tum is sticky note pe likha ke desk pe nahi rakh sakte ya public mein nahi shout kar sakte. .env file teri desk ke andar ek locked drawer jaisa hota hai (jo sirf teri machine pe rahe), aur .gitignore ensure karta hai ki ye kahi aur na jaye. Jaise .env mein likho API_KEY=abc123, phir code mein os.getenv('API_KEY') se load karo.
HTTP 401 status code ka matlab kya hota hai, aur kab aata hai?
401 ka matlab 'Unauthorized' hota hai — server ne aapka request dekha par reject kar diya kyunki aapne valid authentication nahi di (jaise API key missing hai ya galat hai). Jab APIs ko authentication chahiye tab 401 commonly milta hai.
In simple terms: 401 jaisa hai exam hall mein password ke bina pahuonch jaana — exam hall staff jaanta hai aap ho, par rules mein likha hai 'Password na ho to entry nahi.' Jaise agar LLM API ko API key diye bina call karo ya expired key dedo, to 401 response milta hai AI answer ki jagah.
`await` keyword kya karta hai?
`await` current async function ko pause karti hai aur doosre async operation ke khatm hone ka wait karti hai, phir result ke saath resume karti hai. Ye Python ko kah deti hai 'ruko yahan, is task ka wait karo, aur jab ho jaaye toh result do.'
In simple terms: `await` ko video pause karna samjho aur package aane ka wait karna — jab package door pe ho toh play karna. Jaise: `data = await fetch_from_api()` function ko pause karti hai, API response ka wait karti hai, aur result `data` me store karti hai.
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 — freeReady to practise Python for AI?
Unlock every topic free, then face an AI interviewer that asks follow-ups and grades your answers.