Docsity

Comprehensive Python Programming Guide: Master Concepts, MCQs & Exam Strategies, Lecture notes of Computer Science

Toggle sidebar
bg1
Python Programming โ€“ MCQs and Exam Practice
Comprehensive Study Notes for School, College &
Competitive Exams
SECTION 1: PYTHON CONCEPT NOTES (EXAM-ORIENTED)
1. Python Basics and Features
Python is an interpreted, high-level, object-oriented programming language created
by Guido van Rossum. It's known for its simple syntax and readability.
Key Features Exam Often Tests:
โ— Interpreted Language: Code executes line-by-line, making debugging easier
โ— Dynamically Typed: No need to declare variable types (type is determined at
runtime)
โ— Platform Independent: Write once, run anywhere (with Python interpreter)
โ— Extensive Libraries: Rich collection of built-in modules
โ— Indentation Matters: Uses whitespace instead of curly braces for blocks
Common Exam Trap: Students often confuse "interpreted" with "compiled."
Remember: Python code is ๏ฌrst compiled to bytecode (.pyc ๏ฌles), then interpreted by
PVM.
2. Variables and Data Types
Variables are memory locations that store data. No declaration needed - just assign.
Fundamental Data Types:
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Comprehensive Python Programming Guide: Master Concepts, MCQs & Exam Strategies and more Lecture notes Computer Science in PDF only on Docsity!

Python Programming โ€“ MCQs and Exam Practice

Comprehensive Study Notes for School, College &

Competitive Exams

SECTION 1: PYTHON CONCEPT NOTES (EXAM-ORIENTED)

1. Python Basics and Features

Python is an interpreted, high-level, object-oriented programming language created

by Guido van Rossum. It's known for its simple syntax and readability.

Key Features Exam Often Tests:

โ— Interpreted Language: Code executes line-by-line, making debugging easier โ— Dynamically Typed: No need to declare variable types (type is determined at runtime) โ— Platform Independent: Write once, run anywhere (with Python interpreter) โ— Extensive Libraries: Rich collection of built-in modules โ— Indentation Matters: Uses whitespace instead of curly braces for blocks

Common Exam Trap: Students often confuse "interpreted" with "compiled."

Remember: Python code is first compiled to bytecode (.pyc files), then interpreted by

PVM.

2. Variables and Data Types

Variables are memory locations that store data. No declaration needed - just assign.

Fundamental Data Types:

  1. Numeric Types: โ—‹ int: Whole numbers (no size limit in Python 3) โ—‹ float: Decimal numbers โ—‹ complex: Numbers with real and imaginary parts
  2. Sequence Types: โ—‹ str: Text data (immutable) โ—‹ list: Ordered, mutable collection โ—‹ tuple: Ordered, immutable collection
  3. Mapping Type: โ—‹ dict: Key-value pairs, unordered
  4. Set Types: โ—‹ set: Unordered, unique elements, mutable โ—‹ frozenset: Unordered, unique elements, immutable
  5. Boolean Type: โ—‹ bool: True or False

Important Note: type() function returns the data type. id() returns memory

address.

Common Mistake: Assuming int has a maximum value like in other languages.

Python integers have unlimited precision.

3. Input and Output Statements

Input: input() always returns a string. Need type conversion for numbers.

python

num = int(input("Enter a number: ")) # Must convert

Output: print() function with parameters:

โ— sep: Separator (default: space) โ— end: Ending character (default: newline) โ— file: Output destination

Exam Focus: print() formatting using f-strings, format() method, or % operator.

4. Operators

Defining: def function_name(parameters):

Calling: function_name(arguments)

Return: return statement (optional, returns None if omitted)

Types of Arguments:

โ— Positional arguments โ— Keyword arguments โ— Default arguments โ— Variable-length arguments (*args, **kwargs)

Scope: Local vs Global variables. Use global keyword to modify global variable

inside function.

8. Strings

Immutable sequences of characters.

Important Methods: split(), join(), find(), replace(), strip(), lower(), upper()

Slicing: string[start:stop:step] (creates new string)

Exam Favorite: String slicing with negative indices and steps.

9. Lists, Tuples, Sets, Dictionaries

List: [], mutable, ordered, allows duplicates

Tuple: (), immutable, ordered, allows duplicates

Set: {}, mutable, unordered, unique elements

Dictionary: {key:value}, mutable, unordered, unique keys

Key Operations:

โ— Lists: append(), extend(), insert(), remove(), pop() โ— Dictionaries: keys(), values(), items(), get(), update()

Memory Trick: Lists are like notebooks (add/remove pages), tuples are printed books

(can't change), sets are unique item collections, dictionaries are phonebooks

(key-value pairs).

10. File Handling Basics

Modes: 'r' (read), 'w' (write), 'a' (append), 'r+' (read and write)

Essential Methods: open(), read(), readline(), readlines(), write(),

writelines(), close()

Always Use: with statement for automatic resource management

python

with open('file.txt', 'r') as f:

content = f.read()

11. Exception Handling

python

try: # risky code except ExceptionType: # handle error else: # executes if no exception finally:

# always executes

Common Exceptions: ValueError, TypeError, IndexError, KeyError,

ZeroDivisionError, FileNotFoundError

12. OOPs Fundamentals

python

numbers = [ 1 , 2 , 3 , 4 , 5 ] for num in numbers: if num % 2 == 0 : numbers.remove(num)

print(numbers)

Output:

text

[1, 3, 5]

Explanation: Modifying list while iterating can cause unexpected behavior, but here it

works because we're checking conditions properly.

Example 3: Dictionary Reference

python

dict1 = {'a': 1 , 'b': 2 } dict2 = dict dict2['c'] = 3

print(dict1)

Output:

text

{'a': 1, 'b': 2, 'c': 3}

Explanation: dict2 = dict1 creates reference, not copy. Both point to same

dictionary.

Example 4: String Immutability

python

s = "hello"

s[ 0 ] = 'H' # This will cause error

print(s)

Error:

text

TypeError: 'str' object does not support item assignment

Explanation: Strings are immutable. Use s = 'H' + s[1:] instead.

Example 5: Mutable Default Arguments

python

def add_item(item, my_list=[]): my_list.append(item) return my_list

print(add_item( 1 ))

print(add_item( 2 ))

Output:

text

[1]

[1, 2]

Explanation: Default argument is evaluated only once when function is defined.

Same list is reused in subsequent calls.

SECTION 3: MULTIPLE CHOICE QUESTIONS (MCQs)

Conceptual MCQs

Answer: B) 18

Explanation: Exponent has higher precedence than multiplication: 3*2 = 9 , then 2

= 18.

Q4. What is the output?

python

x = [ 1 , 2 , 3 ] y = x y.append( 4 )

print(x)

A) [1, 2, 3]

B) [1, 2, 3, 4]

C) [4, 3, 2, 1]

D) Error

Answer: B) [1, 2, 3, 4]

Explanation: y = x creates a reference, not a copy. Both point to same list.

Assertion-Reason MCQs

Q5. Assertion: In Python, tuples are faster than lists.

Reason: Tuples are immutable, allowing Python to make optimizations.

A) Both Assertion and Reason are true, and Reason is correct explanation

B) Both are true but Reason is NOT correct explanation

C) Assertion is true but Reason is false

D) Assertion is false but Reason is true

Answer: A) Both Assertion and Reason are true, and Reason is correct explanation

Explanation: Tuples are indeed faster for iteration due to immutability optimizations.

Error-Spotting MCQs

Q6. Which line will cause an error?

python

  1. dict = { 1 : 'one', 2 : 'two'}
  2. dict[ 3 ] = 'three'
  3. dict.keys().append( 4 )
  4. print(dict)

A) Line 1

B) Line 2

C) Line 3

D) No error

Answer: C) Line 3

Explanation: dict.keys() returns a view object, not a list. It doesn't have append()

method.

(Continuing with 24 more MCQs in similar pattern)

Q30. What is the output?

python

def func(x, lst=[]): lst.append(x) return lst

print(func( 1 )) print(func( 2 , []))

print(func( 3 ))

A) [1] [2] [3]

B) [1] [2] [1, 3]

  1. What are lambda functions? Give an example. Answer: Anonymous inline functions using lambda keyword. Example: square = lambda x: x**
  2. Explain list comprehension with example. Answer: Concise way to create lists: [x**2 for x in range(5)] creates [0, 1, 4, 9, 16].
  3. Differentiate between read(), readline() and readlines() methods. Answer: read() reads entire file as string, readline() reads one line, readlines() reads all lines as list.
  4. **What are *args and kwargs in function definitions? Answer: *args accepts variable positional arguments as tuple, **kwargs accepts variable keyword arguments as dictionary.
  5. Explain the use of else clause with loops. Answer: else executes when loop completes normally (not by break). Useful for search operations.
  6. How does Python handle multiple inheritance? Explain with example. Answer: Python supports multiple inheritance. Example: class C(A, B): Method resolution follows MRO (Method Resolution Order).
  7. What are Python modules and packages? Answer: Module is a .py file containing Python code. Package is directory containing init.py file and modules.
  8. Explain shallow copy vs deep copy with examples. Answer: Shallow copy creates new object but references nested objects. Deep copy creates completely independent copy.
  9. What are decorators in Python? Give a simple example. Answer: Functions that modify other functions. Example: @staticmethod decorator makes method static.

SECTION 6: LONG ANSWER QUESTIONS

  1. Explain Python's memory management and garbage collection mechanism. Answer: Python uses reference counting and cyclic garbage collector. Objects are created on heap. Reference count tracks references. When count reaches zero, memory is freed. Cyclic collector handles reference cycles.
  2. Write a Python program to handle a student database using dictionaries and files. Include functions to add, search, update and delete records. Answer: (Program with file handling, dictionary operations, error handling)
  1. Compare and contrast lists, tuples, sets and dictionaries with respect to mutability, ordering, indexing and typical use cases. Answer: Detailed comparison table with examples for each data structure.
  2. Explain exception handling hierarchy in Python with examples. Write a program that demonstrates multiple except blocks and finally block. Answer: BaseException โ† Exception โ† StandardError, etc. Program with try-except-else-finally.
  3. What are generators in Python? How are they different from normal functions? Write a generator function for Fibonacci series. Answer: Generators use yield instead of return, maintain state between calls, memory efficient. Example generator code.
  4. Explain OOP concepts with Python examples: encapsulation, inheritance, polymorphism, abstraction. Answer: Detailed explanation with class examples for each concept.
  5. Write a Python program to read a CSV file, process the data (calculate averages, find maximum), and write results to a new file. Answer: Complete program using file handling and data processing.
  6. What are Python decorators? How to create custom decorators? Write a decorator to measure function execution time. Answer: Explanation of decorator pattern with @ syntax. Timer decorator example.
  7. Explain Python's with statement and context managers. Create a custom context manager class. Answer: with ensures proper resource cleanup. Context managers implement enter() and exit() methods.
  8. Compare Python 2 and Python 3 key differences. Why was Python 3 created? Answer: Print function, integer division, Unicode, xrangeโ†’range, etc. Backward incompatibility reasons.

SECTION 7: PRACTICE EXERCISE (WITHOUT SOLUTIONS)

Mixed MCQs for Revision

  1. What is the output of print(type(10/2))?
  2. Which method is used to remove last element from list?
  3. What does "hello".upper().lower() return?
  4. How to create an empty dictionary?
  5. What is the result of bool("False")?

content = file.read() print(content)

return

  1. Fix the class definition:

python

class Student def init(self, name): name = self.name

def display():

print("Name:", name)

EXAM PREPARATION TIPS FROM YOUR TEACHER

  1. Practice Output Prediction: Manually trace code execution
  2. Memorize Common Errors: TypeError, ValueError, IndexError patterns
  3. Understand Concept Depth: Don't just memorize syntax
  4. Time Management: Practice with timer for MCQ sections
  5. Write Neat Code: Proper indentation matters in practical exams
  6. Test Edge Cases: Empty lists, zero, negative numbers, None values
  7. Review Common Pitfalls: Mutable default arguments, reference vs copy
  8. Use Comments: Explain logic in written answers
  9. Diagram Complex Logic: For recursion, nested loops, OOP relationships
  10. Stay Calm: Read questions twice before answering

Remember: Python is about readability and simplicity. If your code looks

complicated, there's probably a simpler way. Focus on understanding concepts

rather than memorizing syntax. Good luck with your exams!

These notes have been prepared keeping in mind common exam patterns and student

difficulties. Regular practice is key to mastering Python programming.