0% found this document useful (0 votes)
2 views9 pages

Python Interview Notes

This document contains comprehensive interview notes on Python programming, covering 17 core topics including variables, operators, loops, and string methods. It provides beginner-friendly explanations, real-world examples, and interview questions and answers. The notes are tailored for Avinash Chandra, an SDET/Automation Engineer, and serve as a foundational guide for Python programming concepts.

Uploaded by

avinash.chandra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views9 pages

Python Interview Notes

This document contains comprehensive interview notes on Python programming, covering 17 core topics including variables, operators, loops, and string methods. It provides beginner-friendly explanations, real-world examples, and interview questions and answers. The notes are tailored for Avinash Chandra, an SDET/Automation Engineer, and serve as a foundational guide for Python programming concepts.

Uploaded by

avinash.chandra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming

Complete Interview Notes


Fundamentals to String Methods — 17 Core Topics
Beginner-friendly explanations with real-world examples & interview Q&A

Prepared for: Avinash Chandra


SDET / Automation Engineer

Python Interview Notes | Page 1


Table of Contents
1. Comments & Print
2. Variables
3. Operators
4. = vs ==
5. Deleting Variables (del)
6. Data Types
7. Concatenation
8. Taking Input from User
9. Formatting Output
10. Conditional Statements
11. While Loop
12. Range Function
13. Match Statement
14. For Loop
15. Break & Continue
16. Strings
17. String Methods

Python Interview Notes | Page 2


1. Comments & Print
Comments code mein notes hote hain jo Python ignore kar deta hai. Single-line ke liye # aur
multi-line ke liye triple quotes use hote hain. print() output console par dikhata hai.

Example
# Single line comment
"""
Multi-line
comment
"""
print("Hello, World!")
print("Testing", "Automation", sep=" - ") # custom separator

Q: Python mein comment kaise likhte hain?


A: Single line ke liye # aur multi-line documentation ke liye triple-quoted string (docstring) use karte
hain.

Q: print() ke common arguments kaun se hain?


A: sep (values ke beech separator) aur end (line ke aakhir mein, default '\n').

2. Variables
Variable ek named container hai jo value store karta hai. Python mein type declare karne ki zaroorat
nahi — assignment se hi type decide ho jaata hai (dynamic typing).

name = "Avinash"
age = 32
is_tester = True
x = y = z = 0 # multiple assignment
a, b = 10, 20 # tuple unpacking

Naming Rules
Letter ya underscore se start; number se nahi. Case-sensitive. Reserved keywords (if, for, class) use
nahi kar sakte. Convention: snake_case.
Q: Python statically typed hai ya dynamically typed?
A: Dynamically typed — variable ka type runtime par value se decide hota hai aur reassign par badal
sakta hai.

3. Operators
Operators values par operations karte hain. Main categories niche table mein hain.

Type Operators Example

Arithmetic + - * / // % ** 7 // 2 = 3

Comparison == != > < >= <= 5 > 3 = True

Python Interview Notes | Page 3


Logical and or not True and False

Assignment = += -= *= /= x += 1

Membership in, not in 'a' in 'cat'

Identity is, is not a is b

Q: / aur // mein difference?


A: / float division deta hai (7/2 = 3.5), // floor division integer-style result deta hai (7//2 = 3).

Q: % operator kya karta hai?


A: Modulo — division ka remainder return karta hai. 10 % 3 = 1. Even/odd check ke liye common hai.

4. = vs ==
= assignment operator hai (value variable mein daalta hai). == comparison operator hai (do values
equal hain ya nahi, True/False return karta hai).

x = 10 # assign 10 to x
if x == 10: # compare x with 10
print("Match")

Q: Sabse common beginner mistake = aur == mein kya hoti hai?


A: Condition mein galti se = likhna jabki == chahiye. Python isse SyntaxError de deta hai, isliye
accidental bug se bachata hai.

5. Deleting Variables (del)


del statement variable ko memory se hata deta hai. Uske baad use karne par NameError aata hai.
Lists mein specific index/element delete karne ke liye bhi use hota hai.

x = 5
del x
# print(x) -> NameError

nums = [1, 2, 3]
del nums[1] # removes 2 -> [1, 3]

Q: del aur clearing a value (x = None) mein difference?


A: del variable reference ko poori tarah remove kar deta hai; x = None variable rakhta hai par usme
None store karta hai.

6. Data Types
Python ke built-in core data types:

Category Types Example

Numeric int, float, complex 10, 3.14, 2+3j

Text str 'hello'

Python Interview Notes | Page 4


Boolean bool True, False

Sequence list, tuple, range [1,2], (1,2)

Mapping dict {'a':1}

Set set, frozenset {1,2,3}

None NoneType None

Type check karne ke liye type(x) aur isinstance(x, int) use karte hain.

Q: Mutable aur immutable types kaun se hain?


A: Mutable: list, dict, set. Immutable: int, float, str, tuple, frozenset, bool. Immutable objects change
nahi kiye ja sakte after creation.

7. Concatenation
Strings ko jodne ko concatenation kehte hain. + operator ya f-strings use hote hain. Numbers ko
string ke saath jodne ke liye pehle str() conversion zaroori hai.

first = "Avinash"
last = "Chandra"
full = first + " " + last # Avinash Chandra
age = 32
msg = "Age: " + str(age) # str() needed
better = f"{first} is {age}" # f-string (recommended)

Q: String concatenation ke liye + vs join() — kab kaun sa?


A: Chhote cases mein + theek hai. Bahut saari strings (loop) ke liye ''.join(list) zyada efficient hai
kyunki + har baar naya string banata hai.

8. Taking Input from User


input() user se data leta hai aur hamesha string return karta hai. Number chahiye to int() ya float()
se convert karein.

name = input("Enter name: ")


age = int(input("Enter age: ")) # convert to int
price = float(input("Price: ")) # convert to float
print(f"Hi {name}, next year you will be {age + 1}")

Q: input() ka return type kya hai?


A: Hamesha str. Arithmetic ke liye int() ya float() se explicit conversion karni padti hai, warna
TypeError ya unexpected concatenation hota hai.

9. Formatting Output
Output format karne ke 3 main tareeke:

Python Interview Notes | Page 5


name, score = "Avinash", 95.5

# 1. f-strings (best, Python 3.6+)


print(f"{name} scored {score:.1f}")

# 2. .format()
print("{} scored {}".format(name, score))

# 3. % formatting (old)
print("%s scored %.2f" % (name, score))

Q: f-string mein decimal places kaise control karte hain?


A: Format spec se: f"{value:.2f}" do decimal places dikhata hai. Width aur alignment ke liye
{value:>10} jaisa syntax use hota hai.

10. Conditional Statements


Decision-making ke liye if / elif / else use hote hain. Python indentation se block define karta hai.

score = 85
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
else:
grade = "C"
print(grade)

# Ternary (one-liner)
status = "Pass" if score >= 40 else "Fail"

Q: Python mein switch statement hai?


A: Pehle nahi tha; elif chains use hote the. Python 3.10+ se match-case structural pattern matching
available hai (Topic 13).

11. While Loop


while loop tab tak chalti hai jab tak condition True hai. Infinite loop se bachne ke liye condition update
karna zaroori hai.

count = 1
while count <= 5:
print(count)
count += 1 # important: update karna na bhulein

# else with while (runs if no break)


while count < 10:
count += 1
else:
print("Loop finished normally")

Q: Infinite loop kab banta hai aur kaise rokte hain?


A: Jab condition kabhi False na ho (variable update na karein). break statement se ya condition ko
sahi update karke rokte hain.

Python Interview Notes | Page 6


12. Range Function
range() numbers ka sequence generate karta hai — loops mein bahut use hota hai. Memory-efficient
hai (lazy).

range(5) # 0,1,2,3,4
range(2, 8) # 2,3,4,5,6,7
range(0, 10, 2) # 0,2,4,6,8 (step=2)
range(5, 0, -1) # 5,4,3,2,1 (reverse)

for i in range(1, 4):


print(i)

Q: range(start, stop) mein stop include hota hai?


A: Nahi. stop exclusive hota hai — range(2,8) 2 se 7 tak deta hai, 8 nahi.

13. Match Statement


Python 3.10+ ka match-case structural pattern matching deta hai — multiple conditions ke liye clean
alternative.

def http_status(code):
match code:
case 200:
return "OK"
case 404:
return "Not Found"
case 500 | 502 | 503: # multiple values
return "Server Error"
case _: # default (wildcard)
return "Unknown"

Q: match-case mein _ ka matlab?


A: Wildcard / default case — jab koi pattern match na ho. switch ke default jaisa.

14. For Loop


for loop kisi bhi iterable (list, string, range, dict) par iterate karta hai.

fruits = ["apple", "banana", "mango"]


for f in fruits:
print(f)

# enumerate for index + value


for i, f in enumerate(fruits):
print(i, f)

# iterate dict
person = {"name": "Avinash", "role": "SDET"}
for key, value in [Link]():
print(key, value)

Q: enumerate() kya karta hai?

Python Interview Notes | Page 7


A: Iterable par loop karte waqt index aur value dono deta hai, manually counter rakhne ki zaroorat
nahi padti.

15. Break & Continue


break loop ko turant rok deta hai. continue current iteration skip karke agle par chala jaata hai.

for i in range(1, 10):


if i == 5:
break # 5 par loop khatam
print(i) # prints 1,2,3,4

for i in range(1, 6):


if i == 3:
continue # 3 skip
print(i) # prints 1,2,4,5

Q: break aur continue mein core difference?


A: break poori loop exit karta hai; continue sirf current iteration skip karke loop continue rakhta hai.

16. Strings
String characters ka immutable sequence hai. Indexing (0 se) aur slicing support karta hai.

s = "Automation"
s[0] # 'A' (first char)
s[-1] # 'n' (last char)
s[0:4] # 'Auto' (slice)
s[::-1] # reverse -> 'noitamotuA'
len(s) # 10
"auto" in [Link]() # membership check

Q: Strings immutable hone ka matlab?


A: Ek baar bani string change nahi hoti. s[0]='X' error dega. Modify karne par hamesha nayi string
banti hai.

17. String Methods


Aksar use hone wale built-in string methods:

Method Kaam Example

upper() / lower() Case change 'Hi'.upper() = 'HI'

strip() Whitespace trim ' hi '.strip() = 'hi'

replace(a,b) Replace substring 'a-b'.replace('-','_')

split(sep) String to list 'a,b'.split(',')

join(list) List to string '-'.join(['a','b'])

find() / index() Position dhundo 'cat'.find('a') = 1

Python Interview Notes | Page 8


startswith() Prefix check 'test'.startswith('te')

count(x) Occurrences ginti 'aaa'.count('a') = 3

Example
s = " Hello Automation World "

[Link]() # ' HELLO AUTOMATION WORLD '


[Link]() # ' hello automation world '
[Link]() # 'Hello Automation World'
[Link]("World", "QA") # ' Hello Automation QA '
[Link]().split(" ") # ['Hello', 'Automation', 'World']
"-".join(["a", "b", "c"]) # 'a-b-c'
[Link]("Auto") # 8 (index of substring)
[Link]().startswith("Hello") # True
[Link]("o") # 3

Q: find() aur index() mein difference?


A: Dono substring position dete hain, par agar substring na mile to find() -1 return karta hai jabki
index() ValueError raise karta hai.

Q: split() aur join() kaise complementary hain?


A: split() string ko list mein todta hai (delimiter par), join() list ko wapas string mein jodta hai. Ek dusre
ke ulte operations hain.

Note: Yeh handbook 17 core topics cover karta hai. Lists, Tuples, Dicts, Functions, OOPs, Pytest,
Selenium & Playwright jaise advanced topics agle volume mein add kiye ja sakte hain.

Python Interview Notes | Page 9

You might also like