Python Comprehensive Module
Table of Contents
1. Python Fundamentals
Introduction to Python
Setting Up Python Environment
Python Syntax
Variables and Data Types
Operators
Control Flow
Functions
Data Structures
2. Practice MCQs
3. Debugging Exercises
Python Fundamentals
Introduction to Python
Python is a high-level, interpreted programming language known for its readability and efficiency. Created by Guido van Rossum and first released in 1991, Python
has become one of the most popular programming languages in the world due to its versatility and ease of use.
Key Features of Python:
Readable and Simple Syntax: Uses indentation to define code blocks
Interpreted Language: Code is executed line by line at runtime
Dynamically Typed: Variable types are determined at runtime
Extensive Standard Library: Comes with a rich set of modules and packages
Cross-Platform: Runs on various operating systems
Versatile: Used in web development, data science, AI, automation, and more
Python Philosophy: Python follows a philosophy that emphasizes code readability and simplicity. This philosophy is encapsulated in the "Zen of Python"
(accessible by typing import this in a Python interpreter):
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Readability counts.
Setting Up Python Environment
Installing Python:
1. Visit python.org (https://www.python.org/downloads/)
2. Download the latest version for your operating system
3. Run the installer and follow the instructions
Make sure to check "Add Python to PATH" (on Windows)
Integrated Development Environments (IDEs) and Text Editors:
PyCharm: Full-featured IDE for Python
Visual Studio Code: Lightweight editor with Python extensions
Jupyter Notebook: Web-based environment for data science
IDLE: Simple IDE that comes with Python installation
Virtual Environments: Virtual environments allow you to create isolated spaces for Python projects, each with its own dependencies:
# Create a virtual environment
python -m venv myenv
# Activate virtual environment
# On Windows:
myenv\Scripts\activate
# On macOS/Linux:
source myenv/bin/activate
# Install packages
pip install package_name
Python Syntax
Python's syntax is designed to be readable and straightforward.
Basic Structure:
# This is a comment
print("Hello, World!") # This is an inline comment
"""
This is a multi-line comment
or docstring
"""
Indentation: Python uses indentation (whitespace) to define code blocks, unlike other languages that use braces or keywords:
# Correct indentation
if True:
print("Indentation is important")
if True:
print("Nested indentation")
# Incorrect indentation will cause IndentationError
if True:
print("This will cause an error")
Line Continuation: Long lines can be broken using backslashes or implicit line continuation inside parentheses, brackets, or braces:
# Using backslash
total = 1 + 2 + 3 + \
4 + 5 + 6
# Implicit line continuation
total = (1 + 2 + 3 +
4 + 5 + 6)
Variables and Data Types
Variable Assignment: Variables in Python don't need explicit type declarations:
name = "John" # String
age = 30 # Integer
height = 5.11 # Float
is_student = True # Boolean
Multiple Assignment:
x, y, z = 1, 2, 3
x = y = z = 0
Basic Data Types:
1. Numeric Types:
int: Integers (e.g., 42, -7, 0)
float: Floating-point numbers (e.g., 3.14, -0.001, 2e-3)
complex: Complex numbers (e.g., 3+4j)
2. Sequence Types:
str: Strings (e.g., "hello", 'world')
list: Lists (e.g., [1, 2, 3])
tuple: Tuples (e.g., (1, 2, 3))
3. Mapping Type:
dict: Dictionaries (e.g., {"name": "John", "age": 30})
4. Set Types:
set: Sets (e.g., {1, 2, 3})
frozenset: Immutable sets
5. Boolean Type:
bool: Boolean values (True and False)
6. None Type:
None: Represents absence of value
Type Conversion:
# Explicit type conversion
str_num = "123"
num = int(str_num) # Convert string to integer
float_num = 10.5
int_num = int(float_num) # Convert float to integer (truncates)
# Check type
print(type(num)) # <class 'int'>
Operators
Arithmetic Operators:
+ Addition
- Subtraction
* Multiplication
/ Division (returns float)
// Floor Division (returns integer)
% Modulus (remainder)
** Exponentiation
print(10 + 5) # 15
print(10 - 5) # 5
print(10 * 5) # 50
print(10 / 5) # 2.0 (always returns float)
print(10 // 3) # 3 (floor division)
print(10 % 3) # 1 (remainder)
print(2 ** 3) # 8 (2³)
Comparison Operators:
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
x = 10
y = 5
print(x == y) # False
print(x != y) # True
print(x > y) # True
print(x < y) # False
print(x >= y) # True
print(x <= y) # False
Logical Operators:
and Logical AND
or Logical OR
not Logical NOT
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False
Assignment Operators:
= Assignment
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
//= Floor divide and assign
%= Modulus and assign
**= Exponentiate and assign
x = 10
x += 5 # Same as x = x + 5
print(x) # 15
Identity Operators:
is Returns True if both variables point to the same object
is not Returns True if both variables do not point to the same object
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a is c) # True (same object)
print(a is b) # False (different objects with same values)
print(a == b) # True (same values)
Membership Operators:
in Returns True if a value exists in the sequence
not in Returns True if a value does not exist in the sequence
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("orange" not in fruits) # True
Control Flow
Conditional Statements:
Python uses if, elif (else if), and else for conditional execution:
age = 18
if age < 13:
print("Child")
elif age < 18:
print("Teenager")
else:
print("Adult")
Ternary Operator:
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status) # Adult
Loops:
1. For Loop - iterates over a sequence (list, tuple, string, etc.):
# Looping through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Looping through a range
for i in range(5): # 0 to 4
print(i)
# Looping with index
for index, value in enumerate(fruits):
print(f"Index {index}: {value}")
2. While Loop - executes as long as a condition is true:
count = 0
while count < 5:
print(count)
count += 1
Loop Control Statements:
break: Exits the loop immediately
continue: Skips the current iteration and moves to the next
pass: Null operation (does nothing)
# break example
for i in range(10):
if i == 5:
break
print(i) # Prints 0, 1, 2, 3, 4
# continue example
for i in range(10):
if i % 2 == 0:
continue
print(i) # Prints 1, 3, 5, 7, 9
# pass example (placeholder)
for i in range(5):
if i == 2:
pass # Do nothing
else:
print(i)
Functions
Functions are blocks of reusable code that perform a specific task:
Defining and Calling Functions:
# Define a function
def greet(name):
"""This function greets the person passed in as parameter"""
return f"Hello, {name}!"
# Call the function
message = greet("John")
print(message) # Hello, John!
Parameters and Arguments:
# Default parameter value
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("John")) # Hello, John!
print(greet("John", "Hi")) # Hi, John!
# Keyword arguments
print(greet(greeting="Hey", name="John")) # Hey, John!
# Variable number of arguments
def sum_all(*numbers):
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3, 4)) # 10
# Variable number of keyword arguments
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="John", age=30, city="New York")
Return Statement: Functions can return values using the return statement:
def add(a, b):
return a + b
def operations(a, b):
return a + b, a - b, a * b, a / b # Returns a tuple
sum_result = add(5, 3) # 8
add_result, sub_result, mul_result, div_result = operations(10, 5)
Lambda Functions: Small anonymous functions defined with the lambda keyword:
# Regular function
def square(x):
return x ** 2
# Equivalent lambda function
square_lambda = lambda x: x ** 2
print(square(5)) # 25
print(square_lambda(5)) # 25
# Lambda with multiple parameters
multiply = lambda x, y: x * y
print(multiply(3, 4)) # 12
# Lambda with filter, map, and reduce
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
squared_numbers = list(map(lambda x: x ** 2, numbers))
Scope of Variables:
Local variables: Defined inside a function and accessible only within that function
Global variables: Defined outside any function and accessible throughout the code
Nonlocal variables: Used in nested functions to refer to variables in the outer (enclosing) function
# Global and local variables
x = 10 # Global variable
def func():
y = 5 # Local variable
print(x) # Accessing global variable
# Modifying global variable
global x
x = 20
# Nonlocal variables
def outer():
x = "outer"
def inner():
nonlocal x
x = "inner"
inner()
print(x) # "inner"
outer()
Data Structures
Lists: Ordered, mutable collections of items:
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
# Accessing elements
print(fruits[0]) # "apple" (first element)
print(fruits[-1]) # "cherry" (last element)
print(fruits[1:3]) # ["banana", "cherry"] (slicing)
# Common operations
fruits.append("orange") # Add to the end
fruits.insert(1, "strawberry") # Insert at index 1
fruits.remove("banana") # Remove by value
popped = fruits.pop() # Remove and return the last item
fruits.sort() # Sort the list in-place
sorted_fruits = sorted(fruits) # Return sorted copy
fruits.reverse() # Reverse the list in-place
# List comprehensions
squared = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
Tuples: Ordered, immutable collections:
# Creating tuples
coordinates = (10, 20)
person = ("John", 30, "New York")
single_item = (1,) # Note the comma
# Accessing elements (similar to lists)
print(coordinates[0]) # 10
print(person[1:]) # (30, "New York")
# Tuple unpacking
name, age, city = person
x, y = coordinates
# Cannot modify tuples
# coordinates[0] = 15 # This would raise TypeError
Dictionaries: Unordered collections of key-value pairs:
# Creating dictionaries
person = {
"name": "John",
"age": 30,
"city": "New York"
}
# Accessing values
print(person["name"]) # "John"
print(person.get("age")) # 30
print(person.get("job", "Not specified")) # Default if key doesn't exist
# Modifying dictionaries
person["email"] = "john@example.com" # Add new key-value pair
person["age"] = 31 # Update existing value
del person["city"] # Remove key-value pair
popped = person.pop("email") # Remove and return value
# Dictionary methods
keys = person.keys() # Dict view object of keys
values = person.values() # Dict view object of values
items = person.items() # Dict view object of (key, value) tuples
# Dictionary comprehensions
squares = {x: x**2 for x in range(6)}
Sets: Unordered collections of unique items:
# Creating sets
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 2, 3, 4, 4]) # Creates {1, 2, 3, 4}
# Set operations
fruits.add("orange") # Add an element
fruits.remove("banana") # Remove an element (raises error if not found)
fruits.discard("banana") # Remove if present (no error if not found)
popped = fruits.pop() # Remove and return an arbitrary element
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
union = a | b # or a.union(b) # {1, 2, 3, 4, 5, 6}
intersection = a & b # or a.intersection(b) # {3, 4}
difference = a - b # or a.difference(b) # {1, 2}
sym_diff = a ^ b # or a.symmetric_difference(b) # {1, 2, 5, 6}
# Set comprehensions
even_squares = {x**2 for x in range(10) if x % 2 == 0}
String Manipulation: Strings are immutable sequences of characters:
# String creation
s1 = "Hello"
s2 = 'World'
multiline = """This is a
multiline string"""
# String operations
greeting = s1 + " " + s2 # Concatenation
repeated = s1 * 3 # Repetition
length = len(greeting) # Length
# Accessing characters
first = greeting[0] # 'H'
last = greeting[-1] # 'd'
substring = greeting[0:5] # 'Hello'
# String methods
upper_case = greeting.upper() # "HELLO WORLD"
lower_case = greeting.lower() # "hello world"
capitalized = greeting.capitalize() # "Hello world"
replaced = greeting.replace("World", "Python") # "Hello Python"
split_words = greeting.split() # ["Hello", "World"]
joined = "-".join(split_words) # "Hello-World"
stripped = " Hello ".strip() # "Hello"
# String checking
starts_with = greeting.startswith("Hello") # True
ends_with = greeting.endswith("World") # True
contains = "llo" in greeting # True
# String formatting
name = "John"
age = 30
# Old style formatting
message1 = "Name: %s, Age: %d" % (name, age)
# str.format()
message2 = "Name: {}, Age: {}".format(name, age)
message3 = "Name: {0}, Age: {1}".format(name, age)
message4 = "Name: {name}, Age: {age}".format(name=name, age=age)
# f-strings (Python 3.6+)
message5 = f"Name: {name}, Age: {age}"
calculation = f"5 + 10 = {5 + 10}"
Visualization: Python Data Types Hierarchy
Python Data Types
│
├── Numeric Types
│ ├── int (integers)
│ ├── float (floating-point)
│ └── complex (complex numbers)
│
├── Sequence Types
│ ├── str (strings)
│ ├── list (mutable sequences)
│ └── tuple (immutable sequences)
│
├── Mapping Types
│ └── dict (dictionaries)
│
├── Set Types
│ ├── set (mutable sets)
│ └── frozenset (immutable sets)
│
├── Boolean Type
│ └── bool (True or False)
│
└── None Type
└── None (represents absence of value)
Practice MCQs
1. What will be the output of the following code?
x = 5
y = 2
print(x // y)
A. 2.5
B. 2
C. 3
D. 2.0
2. Which of the following is NOT a valid way to create an empty list in Python?
A. []
B. list()
C. [None]
D. list([])
3. What is the result of 3 * 'abc'?
A. 9
B. '3abc'
C. 'abcabcabc'
D. Error
4. Which of the following is a mutable data type in Python?
A. tuple
B. string
C. list
D. frozenset
5. What does the following code print?
d = {'a': 1, 'b': 2}
print('c' in d)
A. True
B. False
C. Error
D. None
6. What will be the output of the following code?
def func(x=[]):
x.append(1)
return x
print(func())
print(func())
A. [1] and [1]
B. [1] and [1, 1]
C. [1] and []
D. Error
7. Which of the following is NOT a valid way to iterate through a list in Python?
A. for item in my_list:
B. for i in range(len(my_list)):
C. for index, value in enumerate(my_list):
D. for item from my_list:
8. What is the output of the following code?
a = [1, 2, 3]
b = a
b.append(4)
print(a)
A. [1, 2, 3]
B. [1, 2, 3, 4]
C. [4, 1, 2, 3]
D. Error
9. What will be the value of x after executing the following code?
x = 10
def func():
x = 20
func()
A. 10
B. 20
C. None
D. Error
10. Which of the following is the correct way to create a set with values 1, 2, and 3?
A. {1, 2, 3}
B. set(1, 2, 3)
C. [1, 2, 3].toSet()
D. Both A and B
11. What does 5 & 3 evaluate to in Python?
A. 8
B. 2
C. 1
D. False
12. What is the result of len("Python"[1:4])?
A. 3
B. 4
C. 5
D. 6
13. What will be the output of the following code?
print(bool(""), bool(0), bool([]))
A. False False False
B. True True True
C. False True False
D. True False True
14. What is the correct way to import a specific function from a module?
A. import module.function
B. from module import function
C. import function from module
D. function import module
15. What does the following list comprehension produce?
[x for x in range(10) if x % 2 == 0]
A. [0, 2, 4, 6, 8]
B. [1, 3, 5, 7, 9]
C. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
D. []
Single Correct Questions - Level II
Python MCQ Question Bank
Module 1: Variables, Data Types, and Expressions
Questions
Q1. What will be the type of variable x = 10?
a. str
b. float
c. int
d. bool
Q2. Which of the following is an immutable data type?
a. list
b. dict
c. tuple
d. set
Q3. What is the output of: type(3.5)?
a. <class 'float'>
b. <class 'int'>
c. <class 'str'>
d. <class 'complex'>
Q4. Which of these conversions is valid?
a. int("3.14")
b. int("5")
c. str(5.3.1)
d. float("abc")
Q5. What will be the result of: print("2" + 2)?
a. 4
b. 22
c. Error
d. None
Q6. Which one of these is a mutable data type in Python?
a. tuple
b. string
c. list
d. int
Q7. What is the result of: 10 // 3?
a. 3.33
b. 3
c. 4
d. 1
Module 2: Conditionals and Boolean Logic
Questions
Q1. What is the output of the following code?
x = 10
if x > 5:
print("A")
else:
print("B")
a) A
b) B
c) Error
d) Nothing
Q2. What does not True return?
a) True
b) False
c) 1
d) 0
Q3. Which one is falsy in Python?
a) "hello"
b) [1, 2, 3]
c) None
d) True
Q4. What is the result of: 5 > 2 and 3 < 1?
a) True
b) False
c) Error
d) None
Q5. Choose the correct syntax for an if-else statement in Python:
a) if x > 3 then:
b) if (x > 3)
c) if x > 3:
d) if x > 3 {
Q6. Given x = 0, what will if x: do?
a) Run the block
b) Skip the block
c) Raise error
d) None
Answer Key
Module 1:
Q1. c) int
Q2. c) tuple
Q3. a) <class 'float'>
Q4. b) int("5")
Q5. c) Error
Q6. c) list
Q7. b) 3
Module 2:
Q1. a) A
Q2. b) False
Q3. c) None
Q4. b) False
Q5. c) if x > 3:
Q6. b) Skip the block
## Debugging Exercises
### Exercise 1: Fix the Function
The following function is intended to count the occurrences of each character in a string, but it has errors. Debug it:
```python
def count_characters(s):
char_count = {}
for c in s
if c in char_count
char_count[c] += 1
else:
char_count[c] = 1
return char_count
print(count_characters("hello"))
Exercise 2: Fix the Loop
This code is supposed to print the numbers 1 to 5, but it's not working correctly. Debug it:
for i in range(1, 5):
print(i)
else:
print(5)
Exercise 3: Fix the List Operation
This code is supposed to remove duplicates from a list while preserving order, but it has errors. Debug it:
def remove_duplicates(items):
unique_items = []
for item in items:
if not item in unique_items:
unique_items.append(items)
return unique_items
print(remove_duplicates([1, 2, 2, 3, 4, 3, 5]))
Exercise 4: Fix the Dictionary Access
This code should add all values in a dictionary, but it has errors. Debug it:
def sum_values(d):
total = 0
for key in d:
total += d
return total
print(sum_values({"a": 10, "b": 20, "c": 30}))
Exercise 5: Fix the String Operation
This code is supposed to check if a string is a palindrome, but it doesn't work correctly. Debug it:
def is_palindrome(s):
s = s.lower()
return s == s.reverse()
print(is_palindrome("racecar"))
print(is_palindrome("hello"))
MCQ Answers
1.
B. 2
2.
C. [None] (This creates a list with one element, not an empty list)
3.
C. 'abcabcabc'
4.
C. list
5.
B. False
6.
B. [1] and [1, 1] (Default parameter is evaluated only once)
7.
D. for item from my_list: (Incorrect syntax)
8.
B. [1, 2, 3, 4] (Lists are mutable and a and b reference the same object)
9.
A. 10 (Local variable doesn't affect the global variable)
10.
A. {1, 2, 3} (set(1, 2, 3) would raise an error)
11.
B. 1 (Bitwise AND of 5 (101) and 3 (011) gives 1 (001))
12.
A. 3 (Characters at indices 1, 2, and 3)
13.
A. False False False (Empty collections and zero evaluate to False)
14.
B. from module import function
15.
A. [0, 2, 4, 6, 8] (Even numbers from 0 to 9)
Quick Revision
Sure, Arnav! Here's a clean pointer-style fact sheet that covers all the key ideas needed to answer Python fact-based MCQs like the ones above. You can
memorize this like a cheat sheet.
Python Fact-Based MCQ Revision
Pointers
About Python
Creator: Guido van Rossum
First Released: 1991
Type: High-level, interpreted, dynamically typed language
Philosophy: Zen of Python (import this)
File Extension: .py
Execution & Typing
Dynamically typed: No need to declare types.
Interpreted: Executes line-by-line at runtime.
Everything is an object (including functions, classes, data types).
Variables can change types during execution.
Syntax & Structure
Blocks are defined using indentation, not {} or keywords.
Python enforces indentation strictly (4 spaces is common).
Identifiers:
Can include letters, digits, underscores
Cannot start with a digit
Case-sensitive (Data ≠ data)
Keywords & Built-in Functions
Examples of keywords: if, else, elif, def, class, return, pass, assert, lambda, global, nonlocal
Examples of built-in functions: print(), len(), type(), id(), input(), eval() ⚠ eval() is a built-in function, not a keyword
Data Types and Mutability
Type Example Mutable?
int 10 Immutable
float 3.14
str "hello"
bool True
list [1, 2, 3] Mutable
tuple (1, 2) Immutable
dict {"a": 1}
set {1, 2, 3}
frozenset frozenset() Immutable
NoneType None
Scope & Identity
global keyword: Used to modify global variables inside a function.
nonlocal keyword: Used to modify variables from an enclosing scope in nested functions.
id(): Returns the identity (memory location) of an object.
type(): Returns the data type of an object.
Boolean & Truthiness
Falsy values: 0, None, '', [], {}, set()
Truthy: Everything else (non-empty, non-zero)
Control Flow
if, elif, else used for conditions.
You can use any number of elif blocks.
Python has ternary conditional expressions:
result = "Yes" if condition else "No"
Common Errors
Mixing strings and numbers in operations: "2" + 2 → TypeError
Improper indentation → IndentationError
Invalid identifiers like 2abc → SyntaxError
Miscellaneous
Multiple Inheritance is supported in Python.
Function arguments can be default, keyword-based, *args, or **kwargs.
Immutable types cannot be changed after creation; mutable types can be.
Would you like this turned into a 1-page PDF-style memory booster sheet for daily review?
Debugging Solutions
Exercise 1 Solution
def count_characters(s):
char_count = {}
for c in s: # Missing colon
if c in char_count: # Missing colon
char_count[c] += 1
else:
char_count[c] = 1
return char_count
print(count_characters("hello"))
Exercise 2 Solution
for i in range(1, 6): # Change range to include 5
print(i)
Alternative solution:
for i in range(1, 5):
print(i)
print(5) # Removed else clause which is not needed
Exercise 3 Solution
def remove_duplicates(items):
unique_items = []
for item in items:
if item not in unique_items: # Changed condition
unique_items.append(item) # Append item, not items
return unique_items
print(remove_duplicates([1, 2, 2, 3, 4, 3, 5]))
Exercise 4 Solution
def sum_values(d):
total = 0
for key in d:
total += d[key] # Access value using key
return total
print(sum_values({"a": 10, "b": 20, "c": 30}))
Exercise 5 Solution
def is_palindrome(s):
s = s.lower()
return s == s[::-1] # Strings don't have reverse() method, use slicing
print(is_palindrome("racecar"))
print(is_palindrome("hello"))