Python Basics & Syntax
Master core Python syntax, indentation rules, variable definitions, standard operators, arithmetic flow, and basic inputs/outputs.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What is Python and what are its key features?
Python is a high-level, interpreted, dynamically-typed programming language known for readable syntax and a huge standard library.
| Feature | Meaning |
|---|---|
| Interpreted | Code runs line by line via the Python interpreter, no separate compile step |
| Dynamically typed | Variable types are determined at runtime, not declared upfront |
| Multi-paradigm | Supports procedural, object-oriented, and functional styles |
| Extensive standard library | 'Batteries included' - modules for files, networking, JSON, etc. |
x = 5 # int, type inferred
x = 'hello' # same variable can be reassigned to a different type
print(type(x)) # <class 'str'>
Q2. What is the difference between a list and a tuple in Python?
| Aspect | List | Tuple |
|---|---|---|
| Mutability | Mutable - can change after creation | Immutable - cannot change |
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Performance | Slightly slower | Faster, less memory overhead |
| Use case | Data that changes (dynamic collections) | Fixed data, dictionary keys |
my_list = [1, 2, 3]
my_list.append(4) # works fine
my_list[0] = 99 # works fine
my_tuple = (1, 2, 3)
# my_tuple.append(4) # AttributeError
# my_tuple[0] = 99 # TypeError
# Tuples can be dict keys, lists cannot
locations = {(28.7, 77.1): 'Delhi'} # works
# {[28.7, 77.1]: 'Delhi'} # TypeError - unhashable
Q3. How does Python's indentation-based syntax work, and why does it matter?
Python uses indentation (whitespace) instead of braces {} to define code blocks. Consistent indentation is mandatory - inconsistent indentation raises an IndentationError.
def check_age(age):
if age >= 18:
print('Adult')
else:
print('Minor')
# Inconsistent indentation causes an error
def broken():
if True:
print('A')
print('B') # IndentationError - mismatched spaces| Rule | Detail |
|---|---|
| Standard | 4 spaces per indentation level (PEP 8) |
| Mixing | Never mix tabs and spaces in the same file |
| Block scope | Indentation defines if/for/while/def/class bodies |
Q4. What is the difference between == and is in Python?
| Operator | Checks |
|---|---|
| == | Value equality - do the objects contain the same value? |
| is | Identity equality - are they the SAME object in memory? |
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True - same values
print(a is b) # False - different objects in memory
print(a is c) # True - c points to the SAME object as a
# Small integer caching - CPython caches small ints (-5 to 256)
x = 100
y = 100
print(x is y) # True - both point to the same cached int object
x = 1000
y = 1000
print(x is y) # False (usually) - large ints not cached, separate objects
# Best practice: use 'is' only for None, True, False comparisons
if a is None:
print('a is None')
Q5. What are Python's built-in data types?
| Category | Types |
|---|---|
| Numeric | int, float, complex |
| Sequence | str, list, tuple, range |
| Mapping | dict |
| Set | set, frozenset |
| Boolean | bool |
| Binary | bytes, bytearray, memoryview |
| None type | NoneType |
print(type(5)) # <class 'int'>
print(type(5.0)) # <class 'float'>
print(type('text')) # <class 'str'>
print(type([1, 2])) # <class 'list'>
print(type((1, 2))) # <class 'tuple'>
print(type({'a': 1})) # <class 'dict'>
print(type({1, 2})) # <class 'set'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
# Checking types
x = 5
print(isinstance(x, int)) # True - preferred over type() == comparison
Q6. What is the difference between mutable and immutable objects in Python?
| Mutable | Immutable |
|---|---|
| list, dict, set | int, float, str, tuple, frozenset, bool |
| Can be changed in place | Cannot be changed after creation |
# Mutable - list changes in place, same object id
my_list = [1, 2, 3]
print(id(my_list))
my_list.append(4)
print(id(my_list)) # SAME id - modified in place
# Immutable - string 'change' actually creates a NEW object
s = 'hello'
print(id(s))
s = s + ' world'
print(id(s)) # DIFFERENT id - new string object created
# Common gotcha: mutable default arguments
def add_item(item, items=[]): # DANGEROUS - default list is shared across calls!
items.append(item)
return items
print(add_item('a')) # ['a']
print(add_item('b')) # ['a', 'b'] - unexpected! Same default list reused
# Fix - use None as default, create new list inside
def add_item_safe(item, items=None):
if items is None:
items = []
items.append(item)
return items
Q7. What are *args and **kwargs used for in Python functions?
| Syntax | Collects | Accessed as |
|---|---|---|
| *args | Extra positional arguments | Tuple |
| **kwargs | Extra keyword arguments | Dictionary |
def describe(*args, **kwargs):
print('Positional:', args)
print('Keyword:', kwargs)
describe(1, 2, 3, name='John', age=30)
# Positional: (1, 2, 3)
# Keyword: {'name': 'John', 'age': 30}
# Practical use: flexible function signatures
def sum_all(*numbers):
return sum(numbers)
print(sum_all(1, 2, 3, 4)) # 10
# Unpacking when CALLING a function
def greet(name, greeting):
return f'{greeting}, {name}'
args_list = ['John', 'Hello']
kwargs_dict = {'name': 'John', 'greeting': 'Hello'}
print(greet(*args_list)) # unpacks list as positional args
print(greet(**kwargs_dict)) # unpacks dict as keyword args
# Combining with regular parameters (order matters)
def func(a, b, *args, **kwargs):
print(a, b, args, kwargs)
func(1, 2, 3, 4, x=5, y=6) # 1 2 (3, 4) {'x': 5, 'y': 6}
Q8. What is the difference between deep copy and shallow copy in Python?
| Type | Behavior |
|---|---|
| Shallow copy | Copies the outer object; nested objects are still shared references |
| Deep copy | Recursively copies everything; nested objects are fully independent |
import copy
original = [[1, 2], [3, 4]]
# Shallow copy - outer list is new, but inner lists are SHARED
shallow = copy.copy(original)
shallow[0].append(99)
print(original) # [[1, 2, 99], [3, 4]] - original affected too!
# Deep copy - fully independent
original2 = [[1, 2], [3, 4]]
deep = copy.deepcopy(original2)
deep[0].append(99)
print(original2) # [[1, 2], [3, 4]] - original untouched
# list.copy() and slicing also do SHALLOW copies
shallow2 = original2.copy() # or original2[:]
shallow2[0].append(100)
print(original2) # affected - same nested reference
Q9. What is the difference between a Python list, dictionary, and set in terms of use case?
| Structure | Ordered? | Duplicates? | Access by | Best for |
|---|---|---|---|---|
| list | Yes | Allowed | Index | Ordered sequences, need duplicates |
| dict | Yes (insertion, Python 3.7+) | Keys unique, values can repeat | Key | Key-value lookups |
| set | No | Not allowed (auto-dedupes) | Membership only | Uniqueness, fast membership tests |
# List - ordered, allows duplicates
tags = ['python', 'web', 'python']
print(tags) # ['python', 'web', 'python']
# Dict - key-value pairs
user = {'name': 'John', 'age': 30}
print(user['name']) # John
# Set - unique values, fast membership check
unique_tags = set(tags)
print(unique_tags) # {'python', 'web'}
print('python' in unique_tags) # O(1) average - much faster than list 'in'
# Choosing based on need
visited_ids = set() # fast duplicate checking
for user_id in [1, 2, 1, 3]:
if user_id not in visited_ids:
visited_ids.add(user_id)
print(f'Processing {user_id}')
Q10. What is PEP 8 and why does it matter?
PEP 8 is Python's official style guide, defining conventions for naming, indentation, line length, imports, and formatting to keep code consistent and readable across projects and teams.
| Rule | Convention |
|---|---|
| Indentation | 4 spaces, no tabs |
| Line length | Max 79 characters (some teams use 88-120) |
| Variable/function names | snake_case |
| Class names | PascalCase (CapWords) |
| Constants | UPPER_SNAKE_CASE |
# PEP 8 compliant
MAX_RETRIES = 5
class UserAccount:
def __init__(self, user_name):
self.user_name = user_name
def get_display_name(self):
return self.user_name.title()
# Not PEP 8 compliant
class useraccount:
def __init__(self,UserName):
self.UserName=UserNameTools like flake8, pylint, and black help automatically check or enforce PEP 8 compliance.
Python Basics & Syntax
Master core Python syntax, indentation rules, variable definitions, standard operators, arithmetic flow, and basic inputs/outputs.
What is Python and what are its key features?
Python is a high-level, interpreted, dynamically-typed programming language known for readable syntax and a hu...
What is the difference between a list and a tuple in Python?
AspectListTupleMutabilityMutable - can change after creationImmutable - cannot changeSyntax[1, 2, 3](1, 2, 3)P...
How does Python's indentation-based syntax work, and why does it matter?
Python uses indentation (whitespace) instead of braces {} to define code blocks. Consistent indentation is man...
What is the difference between == and is in Python?
OperatorChecks==Value equality - do the objects contain the same value?isIdentity equality - are they the SAME...
What are Python's built-in data types?
CategoryTypesNumericint, float, complexSequencestr, list, tuple, rangeMappingdictSetset, frozensetBooleanboolB...
What is the difference between mutable and immutable objects in Python?
MutableImmutablelist, dict, setint, float, str, tuple, frozenset, boolCan be changed in placeCannot be changed...
What are *args and **kwargs used for in Python functions?
SyntaxCollectsAccessed as*argsExtra positional argumentsTuple**kwargsExtra keyword argumentsDictionarydef desc...
What is the difference between deep copy and shallow copy in Python?
TypeBehaviorShallow copyCopies the outer object; nested objects are still shared referencesDeep copyRecursivel...
What is the difference between a Python list, dictionary, and set in terms of use case?
StructureOrdered?Duplicates?Access byBest forlistYesAllowedIndexOrdered sequences, need duplicatesdictYes (ins...
What is PEP 8 and why does it matter?
PEP 8 is Python's official style guide, defining conventions for naming, indentation, line length, imports, an...