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

Python Basic

Uploaded by

Om Takale
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)
3 views9 pages

Python Basic

Uploaded by

Om Takale
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
You are on page 1/ 9

keyboard_arrow_down Python Interview Prep: Core Concepts, Common Patterns & Trick Questions

1. Core Python Concepts

1.1. Variables and Data Types

Q: What are the fundamental built-in data types in Python? Give an example of each.

A:

Numeric: int , float , complex (e.g., age = 30 , pi = 3.14 , c = 1 + 2j )


Sequence: str , list , tuple , range (e.g., name = "Alice" , nums = [1, 2, 3] , coords = (10, 20) , r =
range(5) )
Mapping: dict (e.g., person = {"name": "Bob", "age": 25} )
Set: set , frozenset (e.g., unique_nums = {1, 2, 3} , immutable_set = frozenset({4, 5}) )
Boolean: bool (e.g., is_active = True )
None Type: NoneType (e.g., result = None )

Trick Q: What's the difference between list and tuple ? When would you use one over the other?
A:

Mutability: list is mutable (can be changed after creation), tuple is immutable (cannot be changed).

Syntax: list uses [] , tuple uses () .


Use Cases:

List: When you need a collection where elements might be added, removed, or modified (e.g., a shopping cart, a
dynamically growing list of data).
Tuple: When you need an immutable sequence, such as representing coordinates (x, y), returning multiple fixed values
from a function, or using it as a dictionary key (since dict keys must be hashable, and mutable types like lists are not).

# List example
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]

# Tuple example
my_tuple = (1, 2, 3)
# my_tuple.append(4) # This would raise an AttributeError
print(my_tuple) # Output: (1, 2, 3)

keyboard_arrow_down 1.2. Operators

Q: Explain the difference between / , // , and % operators.

A:

/ (Division): Floating-point division. Always returns a float.

// (Floor Division): Returns the integer part of the division.


% (Modulo): Returns the remainder of the division.

print(10 / 3) # Output: 3.3333333333333335


print(10 // 3) # Output: 3
print(10 % 3) # Output: 1

keyboard_arrow_down 1.3. Control Flow

Q: Write a simple for loop to print numbers from 1 to 5.

A:

for i in range(1, 6):


print(i)

Q: How do break and continue statements work in loops?

A:

break : Terminates the loop entirely and execution continues at the statement immediately following the loop.
continue : Skips the rest of the current iteration and proceeds to the next iteration of the loop.
# break example
for i in range(10):
if i == 5:
break
print(i) # Prints 0, 1, 2, 3, 4

print("---")

# continue example
for i in range(10):
if i % 2 == 0: # Skip even numbers
continue
print(i) # Prints 1, 3, 5, 7, 9

keyboard_arrow_down 1.4. Functions

Q: Define a simple function that takes two arguments and returns their sum.

A:

def add(a, b):


return a + b

print(add(5, 3)) # Output: 8

Trick Q: Explain *args and **kwargs . Provide a simple example.


A:

*args (arbitrary arguments): Allows a function to accept a variable number of non-keyword (positional) arguments. These
arguments are packed into a tuple .
**kwargs (arbitrary keyword arguments): Allows a function to accept a variable number of keyword arguments. These

arguments are packed into a dictionary .


Use Case: Useful when you don't know in advance how many arguments will be passed to a function, or when creating flexible
APIs.

def my_function(arg1, *args, **kwargs):


print("arg1:", arg1)
print("args (tuple):", args)
print("kwargs (dict):", kwargs)

my_function("hello", 1, 2, 3, name="Alice", age=30)


# Output:
# arg1: hello
# args (tuple): (1, 2, 3)
# kwargs (dict): {'name': 'Alice', 'age': 30}

keyboard_arrow_down 1.5. Object-Oriented Programming (OOP)

Q: What are classes and objects in Python?

A:

Class: A blueprint or a template for creating objects. It defines the structure (attributes/data) and behavior
(methods/functions) that objects of that class will have.
Object: An instance of a class. It's a concrete entity created from the class blueprint, possessing the attributes and methods
defined by the class.

Q: Explain __init__ method and self keyword.

A:

__init__ : This is a special method (constructor) that is automatically called when a new object of the class is created.
It's used to initialize the object's attributes.
self : Represents the instance of the class itself. It's the first parameter in any instance method (including __init__ )
and refers to the object on which the method is called. It allows you to access and modify the object's attributes and call
other methods within the same object.

class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} says Woof!")

my_dog = Dog("Buddy", "Golden Retriever") # __init__ is called here


print(my_dog.name) # Output: Buddy
my_dog.bark() # Output: Buddy says Woof!

Q: What is inheritance in Python?

A: Inheritance is a mechanism where a new class (subclass/derived class) derives properties (attributes and methods) from an
existing class (superclass/base class). It promotes code reusability and establishes an "is-a" relationship (e.g., a "Car is a
Vehicle").

class Animal:
def speak(self):
raise NotImplementedError("Subclass must implement abstract method")

class Dog(Animal): # Dog inherits from Animal


def speak(self):
return "Woof!"

class Cat(Animal): # Cat inherits from Animal


def speak(self):
return "Meow!"

buddy = Dog()
whiskers = Cat()
print(buddy.speak()) # Output: Woof!
print(whiskers.speak()) # Output: Meow!

Trick Q: What is Polymorphism in Python?

A: Polymorphism means "many forms." In Python, it allows objects of different classes to be treated as objects of a common
superclass. It enables a single interface to be used for different data types. This is often achieved through method overriding
(where a subclass provides its own implementation of a method already defined in its superclass) or method overloading (though
Python doesn't support traditional method overloading, it achieves similar behavior through default arguments or
*args/**kwargs ). The example with Animal , Dog , and Cat 's speak() method demonstrates polymorphism. Each

animal "speaks" in its own way, but you can call animal.speak() without knowing its specific type.

keyboard_arrow_down 1.6. Error Handling

Q: Explain try , except , else , and finally blocks.

A:

try : Code inside this block is executed. If an error occurs, it's caught by an except block.

except : Catches specific exceptions that occur in the try block. You can have multiple except blocks for different
error types.
else : (Optional) Code inside this block is executed only if the try block completes without raising any exceptions.
finally : (Optional) Code inside this block is always executed, regardless of whether an exception occurred or not. It's
often used for cleanup operations (e.g., closing files).

try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("Division successful, result:", result)
finally:
print("Execution complete.")

keyboard_arrow_down 1.7. Generators and Iterators

Q: What's the difference between a list and a generator ?


A:
List: Stores all its elements in memory at once. Created using [] or list() . Useful when you need to access elements by
index or iterate multiple times.
Generator: Generates values on the fly (lazy evaluation) and yields one item at a time. It doesn't store all values in memory,
making it memory-efficient for large datasets. Created using generator expressions () or functions with the yield
keyword. Can only be iterated once.

# List
my_list = [i * i for i in range(1000000)] # All 1M values in memory

# Generator
my_generator = (i * i for i in range(1000000)) # Values generated on demand
print(next(my_generator)) # Output: 0
print(next(my_generator)) # Output: 1
# print(my_generator[0]) # This would raise a TypeError (generators are not subscriptable)

def fibonacci_generator(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b

fib_gen = fibonacci_generator(5)
print(list(fib_gen)) # Output: [0, 1, 1, 2, 3]

keyboard_arrow_down 1.8. Decorators

Trick Q: What is a decorator in Python? Provide a simple example.

A: A decorator is a design pattern that allows you to modify or enhance the behavior of a function or class without permanently
altering its source code. It's essentially a function that takes another function as an argument, adds some functionality, and
returns a new function. Decorators are typically used with the @ syntax.
Common Use Cases: Logging, timing execution, authentication, caching, validation.

def my_decorator(func):
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
result = func(*args, **kwargs)
print("Something is happening after the function is called.")
return result
return wrapper

@my_decorator
def say_hello(name):
print(f"Hello, {name}!")

say_hello("Alice")
# Output:
# Something is happening before the function is called.
# Hello, Alice!
# Something is happening after the function is called.

keyboard_arrow_down 2. Common Interview Patterns & Data Structures

2.1. Strings

Q: How do you reverse a string in Python?

A: Using slicing is the most Pythonic way.

my_string = "hello"
reversed_string = my_string[::-1]
print(reversed_string) # Output: olleh

my_sequence = "Python" # Also works for lists/tuples


print(my_sequence[0]) # 'P' (first element)
print(my_sequence[1:4]) # 'yth' (from index 1 up to, but not including, 4)
print(my_sequence[::2]) # 'Pto' (every second element)
print(my_sequence[1:]) # 'ython' (from index 1 to the end)
print(my_sequence[:3]) # 'Pyt' (from beginning up to index 3)
print(my_sequence[::-1]) # 'nohtyP' (reverses the sequence)
print(my_sequence[4:1:-1]) # 'oh' (from index 4 down to, but not including, 1, reversed)
olleh
P
yth
Pto
ython
Pyt
nohtyP
oht

Q: Explain string immutability.

A: Strings in Python are immutable, meaning once a string is created, its content cannot be changed. Any operation that appears
to modify a string (like concatenation or slicing) actually creates a new string. This is why my_string[0] = 'H' would raise a

TypeError .
Q: Explain string immutability.

A: Strings in Python are immutable, meaning once a string is created, its content cannot be changed. Any operation that appears to modify a
string (like concatenation or slicing) actually creates a new string. This is why my_string[0] = 'H' would raise a TypeError. Core Concept:
Slicing ([start:end:step])

Slicing is a powerful way to extract portions (subsequences) from sequences like strings, lists, and tuples. Syntax : sequence[start:end:step]

start: The starting index (inclusive). If omitted, defaults to 0.

end: The ending index (exclusive). If omitted, defaults to the end of the sequence.

step: The increment between elements. If omitted, defaults to 1. A negative step value reverses the sequence.

keyboard_arrow_down 2.2. Lists

Q: How do you remove duplicates from a list?

A: The most common way is to convert to a set and then back to a list (loses order). If order is important, iterate and append.

# Method 1: Using set (order not preserved)


my_list = [1, 2, 2, 3, 1, 4]
unique_list_set = list(set(my_list))
print(unique_list_set) # Output: [1, 2, 3, 4] (order might vary)

# Method 2: Preserving order


unique_list_ordered = []
seen = set()
for item in my_list:
if item not in seen:
unique_list_ordered.append(item)
seen.add(item)
print(unique_list_ordered) # Output: [1, 2, 3, 4]

Q: What is list comprehension? Give an example.

A: List comprehension provides a concise way to create lists. It's a compact and efficient way to transform or filter a sequence
(like a list or tuple) and create a new list.

# Traditional loop
squares = []
for i in range(5):
squares.append(i * i)
print(squares) # Output: [0, 1, 4, 9, 16]

# List comprehension
squares_comp = [i * i for i in range(5)]
print(squares_comp) # Output: [0, 1, 4, 9, 16]

# With condition
even_squares = [i * i for i in range(10) if i % 2 == 0]
print(even_squares) # Output: [0, 4, 16, 36, 64]

keyboard_arrow_down 2.3. Dictionaries

Q: How do you iterate through a dictionary?

A:

my_dict = {"name": "Alice", "age": 30, "city": "New York"}

# Iterate through keys (default)


print("Keys:")
for key in my_dict:
print(key)

# Iterate through values


print("\nValues:")
for value in my_dict.values():
print(value)

# Iterate through key-value pairs


print("\nKey-Value Pairs:")
for key, value in my_dict.items():
print(f"{key}: {value}")

Trick Q: What happens if you try to access a non-existent key in a dictionary? How can you handle it safely?

A: If you try to access a non-existent key directly ( my_dict['non_existent_key'] ), it will raise a KeyError .
Safe Handling:

Using the get() method: Returns None (or a specified default value) if the key is not found.

Using in operator: To check for key existence before accessing.

Using a try-except block.

my_dict = {"a": 1}

# Unsafe access (will raise KeyError)


# print(my_dict['b'])

# Safe access using get()


value = my_dict.get('b')
print(f"Value with get(): {value}") # Output: Value with get(): None

value_with_default = my_dict.get('b', 'default_value')


print(f"Value with get() and default: {value_with_default}") # Output: Value with get() and default: default_valu

# Safe access using 'in'


if 'b' in my_dict:
print(my_dict['b'])
else:
print("Key 'b' not found.") # Output: Key 'b' not found.

# Safe access using try-except


try:
print(my_dict['b'])
except KeyError:
print("Key 'b' not found in try-except.") # Output: Key 'b' not found in try-except.

keyboard_arrow_down 3. "Trick" Interview Questions (Deeper Understanding)

3.1. Immutability & Side Effects

Trick Q: What's the output of this code and why?

def modify_list(lst):
lst.append(4)
return lst

my_list = [1, 2, 3]
new_list = modify_list(my_list)
print(my_list)
print(new_list)

A:

```
[1, 2, 3, 4]
[1, 2, 3, 4]
```
Explanation: Lists are mutable. When my_list is passed to modify_list , it's passed by object reference. Both my_list
and lst refer to the same list object in memory. Therefore, lst.append(4) modifies the original my_list object directly.

new_list also refers to this same modified object.

Trick Q: What's the output of this code and why?

def modify_string(s):
s = s + " world"
return s

my_string = "hello"
new_string = modify_string(my_string)
print(my_string)
print(new_string)

A:

```
hello
hello world
```

Explanation: Strings are immutable. When s = s + " world" is executed inside the function, a new string object "hello
world" is created and s is made to refer to this new object. The original my_string in the global scope remains unchanged
because it still refers to the original "hello" object.

keyboard_arrow_down 3.2. Default Mutable Arguments

Trick Q: What's the output of this code and why? How would you fix it?

def add_item(item, my_list=[]):


my_list.append(item)
return my_list

print(add_item(1))
print(add_item(2))
print(add_item(3, ['a']))
print(add_item(4))

A:

```
[1]
[1, 2]
['a', 3]
[1, 2, 4]
```

Explanation: This is a classic "trick" question. Default arguments are evaluated once when the function is defined, not every time
the function is called. So, the [] list object is created only once. Subsequent calls to add_item() without providing my_list
will reuse the same list object, leading to unexpected accumulation.
Fix: The standard way to fix this is to use None as a default value and initialize the list inside the function if None is passed.

def add_item_fixed(item, my_list=None):


if my_list is None:
my_list = []
my_list.append(item)
return my_list

print(add_item_fixed(1)) # Output: [1]


print(add_item_fixed(2)) # Output: [2]
print(add_item_fixed(3, ['a'])) # Output: ['a', 3]
print(add_item_fixed(4)) # Output: [4]

keyboard_arrow_down 3.3. Scope (LEGB Rule)


Trick Q: What's the output and why?

x = 10

def outer_func():
x = 20
def inner_func():
print(x)
return inner_func

my_inner_func = outer_func()
my_inner_func()

A:

```
20
```

Explanation: This demonstrates closures and the LEGB rule (Local, Enclosing function locals, Global, Built-in). When
inner_func is defined, it "remembers" the x from its enclosing scope ( outer_func ), even after outer_func has finished

executing. So, x here refers to the x = 20 defined within outer_func , not the global x = 10 .
Trick Q: What's the output and why?

x = 10

def func():
print(x)
x = 20 # This line creates a new local x

func()

A:

```
UnboundLocalError: local variable 'x' referenced before assignment
```

Explanation: When Python encounters x = 20 inside func , it determines that x is a local variable within func . Because x is

assigned to within the function, Python expects it to be initialized before it's used. The print(x) statement tries to use x
before it's locally assigned, leading to UnboundLocalError . If x = 20 were removed, print(x) would correctly print the

global x = 10 . To modify the global x inside func , you'd need to use the global keyword.

x = 10

def func_global():
global x # Declare intent to modify global x
print(x) # Accesses global x
x = 20 # Modifies global x

func_global() # Output: 10
print(x) # Output: 20

keyboard_arrow_down 3.4. is vs ==

Trick Q: Explain the difference between is and == in Python.

list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1

print(list1 == list2)
print(list1 is list2)
print(list1 == list3)
print(list1 is list3)
a = 5
b = 5
c = 257
d = 257

print(a == b)
print(a is b)
print(c == d)
print(c is d)

A:

* `==` (Equality operator): Compares the *values* of two objects. It checks if the objects have
* `is` (Identity operator): Compares the *identities* of two objects. It checks if two variable

* **Output:**
```
True
False
True
True
True
True
True
False
```
* **Explanation:**
* `list1 == list2`: `True` because their contents are the same.
* `list1 is list2`: `False` because `list1` and `list2` are two separate list objects in me
* `list1 == list3`: `True` (same content).
* `list1 is list3`: `True` because `list3 = list1` makes `list3` reference the *exact same

* **Integer Caching (for `a` and `b`, `c` and `d`):** Python often caches small integers (t
 

keyboard_arrow_down 4. Other Important Topics to Review

File I/O: Reading from and writing to files ( open() , with open() , read() , write() , readline() , readlines() ).
Modules and Packages: How to import ( import , from ... import ), purpose of __init__.py .
Virtual Environments: Why use them ( venv , conda )?
Pip: Package installer for Python.
Lambda Functions: Anonymous, small functions ( lambda x: x * 2 ).
Map, Filter, Reduce: Functional programming tools.
Error Types: Common exceptions (e.g., ValueError , TypeError , IndexError , FileNotFoundError ).
Docstrings: How to write good documentation for functions/classes.

This comprehensive overview should give you a strong foundation for your Python interview! Practice coding these snippets and explaining
the concepts in your own words. Good luck!

Sources

1. https://github.com/cyborg1432/hpkvn
2. https://cdnwebdev.com/the-ultimate-python-cheat-sheet-a-quick-reference-guide/
3. https://github.com/sakthivel-dev/python100Days
4. https://github.com/iqbalal13/PYTHON-BASIC
5. https://www.wanghao.me/pythonjijianmeixueyixingdaimawanchengde26gerichangrenwu.html
6. https://github.com/dearnidhi/Data-science-material
7. https://github.com/zerosum99/js_fluentpython_study
8. https://www.bestdivision.com/questions/is-string-a-primitive-type
9. https://github.com/shkim960520/data_structure

You might also like