Chapter 6Computer Science

Chapter 6

Read official chapter content, important formulas, and quick notes below.

Chapter 6

Chapter Overview

This chapter serves as a comprehensive introduction to the foundational principles of computer programming, algorithm design, and computational problem-solving, structured around the Class 11 Computer Science (NCERT/CBSE) curriculum using Python 3. It lays the theoretical and practical bedrock required to understand how software applications are conceptualized, structured, executed, and optimized.

At its core, programming is the process of transforming human logic into an unambiguous sequence of instructions that a computer's Central Processing Unit (CPU) can execute. The chapter focuses on the basic building blocks of programming languages:

  1. Variables and Memory Allocation: How values are stored, tagged, and referenced in RAM.
  2. Data Types and Mutability: Categorization of data, dynamic typing, and memory mutability rules.
  3. Operators and Precedence: The mathematical and logical machinery used to evaluate expressions.
  4. Control Structures (Flow of Control): Directing program execution sequentially, conditionally, or iteratively.
  5. Functions and Modularization: Decomposing complex software into reusable, encapsulated code units.
  6. Algorithmic Thinking: Designing language-independent, step-by-step procedures characterized by correctness, efficiency, and finiteness.

By mastering these fundamental pillars, students transition from passive users of technology to active creators capable of translating complex real-world requirements into robust code.


Learning Objectives

By thoroughly engaging with this chapter, students will be able to:

  • Analyze Variable Execution Models: Explain how variables act as dynamic references to objects in memory rather than fixed storage containers (in Python), using memory address inspection functions like id().
  • Classify and Manipulate Data Types: Differentiate between fundamental primitive data types (int, float, complex, bool, NoneType) and container/sequence types (str, list, tuple, dict, set), along with their explicit and implicit type conversions (coercion).
  • Construct Complex Expressions: Compute expressions utilizing arithmetic, relational, logical, bitwise, assignment, identity (is), and membership (in) operators while applying proper operator precedence rules.
  • Implement Flow Control Mechanisms: Architect conditional branches (if, if-else, if-elif-else) and iterative loops (for, while) including loop control statements (break, continue, pass) to solve non-linear computational problems.
  • Formulate Modular Functions: Write user-defined functions utilizing parameter passing, return values, default arguments, and understand local vs. global scope resolution (LEGB rule).
  • Design and Express Algorithms: Formulate clear algorithms using pseudocode, structural flowcharts, and trace tables to evaluate program logic prior to implementation.
  • Master Python Syntax Standards: Apply standardized PEP 8 syntax rules, proper indentation blocks, code commenting standards, and robust debugging techniques.

Detailed Concept Breakdown

1. Variables, Data Types, and Memory Mechanics

Variables and Memory References

In low-level programming paradigms (e.g., C/C++), a variable is a named memory location reserved to hold a specific value of a predetermined type. In modern high-level dynamic languages like Python, a variable is a dynamic symbol or reference (a pointer) attached to an object created in heap memory.

# C/C++ concept (Variable as container):
# int x = 10; (x is a memory box holding 10)

# Python concept (Variable as reference/tag):
x = 10  # Creates an integer object 10 in memory; 'x' points to its memory address

When you execute x = 10, Python allocates an object of type int with the value 10 in heap memory and binds the name x to that object. You can inspect the unique integer identifier (memory address) using id(x).

Dynamic Typing vs. Static Typing

Python is dynamically typed, meaning variable data types are determined at runtime, not at compile-time. A single variable name can be re-bound to objects of different types during execution:

var = 100        # 'var' points to an 'int' object
print(type(var)) # Output: <class 'int'>

var = "Hello"    # 'var' now points to a 'str' object; previous int 100 is garbage collected if unreferenced
print(type(var)) # Output: <class 'str'>

Classification of Python Data Types

Data Type CategorySpecific TypeImmutable / MutableDescription & Example
NumericintImmutableWhole numbers of arbitrary precision: x = 42, y = -1005
floatImmutableDouble-precision IEEE 754 floating-point numbers: pi = 3.14159
complexImmutableNumbers with real and imaginary parts: z = 3 + 4j
BooleanboolImmutableTruth values: True or False (subclass of int, where True == 1, False == 0)
SequencestrImmutableOrdered sequence of Unicode characters: name = "Computer Science"
tupleImmutableOrdered, immutable collection of arbitrary objects: point = (10, 20)
listMutableOrdered, mutable collection of arbitrary objects: marks = [95, 88, 92]
MappingdictMutableKey-Value key-indexed collection: student = {"roll": 101, "name": "Aman"}
Set TypessetMutableUnordered collection of unique hashable elements: unique_ids = {1, 2, 3}
Null TypeNoneTypeImmutableRepresents the absence of a value or null signal: data = None

2. Operators and Evaluation Mechanics

Operators are symbolic tokens that direct the interpreter to perform specific mathematical, logical, or relational manipulations on operands.

Deep-Dive Operator Taxonomy

  1. Arithmetic Operators:

    • Addition (+), Subtraction (-), Multiplication (*)
    • Division (/): Always returns a float (e.g., 7 / 2 yields 3.5).
    • Floor Division (//): Rounds down to the nearest whole integer (e.g., 7 // 2 yields 3; -7 // 2 yields -4).
    • Modulus (%): Computes the remainder of division (e.g., 7 % 2 yields 1).
    • Exponentiation (**): Raises left operand to the power of right operand (e.g., 2 ** 3 yields 8).
  2. Relational (Comparison) Operators:

    • Compare two values and evaluate to a Boolean (True or False).
    • == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to).
    • Example: 'apple' < 'banana' evaluates to True based on lexicographical (ASCII/Unicode) ordering.
  3. Logical Operators & Short-Circuit Evaluation:

    • and: Returns True if both operands evaluate to true.
    • or: Returns True if at least one operand evaluates to true.
    • not: Inverts the truth value (not True becomes False).
    • Short-Circuit Mechanics:
      • In A and B, if A is False, Python immediately returns A without evaluating B.
      • In A or B, if A is True, Python immediately returns A without evaluating B.
# Short-circuit demonstration
def check_flag():
    print("Function Executed!")
    return True

# check_flag() is NEVER executed because False and Anything is False
result = False and check_flag()  # Output: (Nothing printed)
  1. Identity and Membership Operators:
    • Identity (is, is not): Evaluates whether two variable identifiers point to the exact same memory location (i.e., id(a) == id(b)).
    • Membership (in, not in): Evaluates whether a target value exists within a sequence (string, list, tuple, set, dictionary).
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b) # True (Values are identical)
print(a is b) # False (Different memory addresses)
print(a is c) # True (Points to identical object)

3. Flow of Control (Control Structures)

Execution flow within a program can follow three structural patterns: Sequential execution, Selective branching (Conditionals), and Iterative repetition (Loops).

                  [ Control Structures Flowchart ]
                                  |
         +------------------------+------------------------+
         |                        |                        |
   [ Sequential ]           [ Selection ]            [ Iteration ]
   Instruction 1                  |                        |
         |                 /------------- \         /-------------\
   Instruction 2          < Is Condition >         < Is Condition >
         |                 \-------------/          \-------------/
   Instruction 3            /           \            /           \
                       (True)         (False)    (True)         (False)
                         |               |          |              |
                      Branch A        Branch B   Loop Body     Exit Loop
                                                    |
                                                    +---> (Repeat)

A. Conditional Structures

Conditionals direct execution down different logic paths based on dynamic Boolean evaluation.

score = 85

if score >= 90:
    grade = 'A+'
elif score >= 80:
    grade = 'A'
elif score >= 70:
    grade = 'B'
else:
    grade = 'C'

print(f"Grade: {grade}") # Output: Grade: A

B. Iterative Structures

Iterative structures repeat execution blocks based on conditions or sequence lengths.

  • while loop: Executes a body of statements as long as an entry condition remains True (used when iterations are indefinite).
  • for loop: Iterates over members of a sequence or iterable object using the range(start, stop, step) function (used when iteration count is predetermined).
# Indefinite loop example
count = 3
while count > 0:
    print(f"Countdown: {count}")
    count -= 1

# Definite loop example using range(start, stop, step)
for i in range(1, 6, 2):  # Starts at 1, stops before 6, increments by 2
    print(f"Odd number: {i}")

C. Loop Control Statements

  • break: Terminates the innermost active loop entirely and resumes execution at the next statement outside the loop.
  • continue: Skips the remainder of the current iteration's body and jumps straight to the next loop evaluation.
  • pass: A null operation/placeholder used when statement syntax requires execution block presence, but logic is not yet written.

4. Functions and Modularization

Functions are named, reusable code blocks created to perform distinct sub-tasks. Modularization enhances readability, minimizes redundant code, and facilitates targeted unit testing.

                    +-----------------------------+
                    |      Function Call          |
                    |   result = calculate(10, 20)|
                    +--------------+--------------+
                                   |
              Pass Arguments (10,20)| Return Value
                                   v
                    +-----------------------------+
                    |  def calculate(a, b):       |
                    |      sum_val = a + b        |
                    |      return sum_val         |
                    +-----------------------------+
def calculate_area(length: float, width: float = 10.0) -> float:
    """
    Computes the area of a rectangle given length and width.
    Width defaults to 10.0 if not provided.
    """
    area = length * width  # Local variable area
    return area

# Function Call with positional and default arguments
rect1 = calculate_area(5.0)       # length=5.0, width=10.0 (default) -> 50.0
rect2 = calculate_area(5.0, 4.0)  # length=5.0, width=4.0 -> 20.0

Variable Scope Resolution (LEGB Rule)

When a variable name is referenced inside a function, Python searches for it in four sequential namespaces:

  1. L (Local): Names assigned inside the executing function.
  2. E (Enclosing): Names in local scope of enclosing/nesting functions (if any).
  3. G (Global): Names declared at the top level of the module file.
  4. B (Built-in): Pre-assigned names built into the Python language environment (e.g., print, range, ValueError).

5. Algorithmic Thinking and Flowcharting

An algorithm is an unambiguous, step-by-step, finite operational procedure designed to transform input data into a desired output.

Key Properties of a Valid Algorithm

  1. Input: Accepts zero or more clearly defined inputs.
  2. Output: Produces at least one deterministic output.
  3. Definiteness: Every step must be clear, precise, and unambiguous.
  4. Finiteness: Must terminate after a finite number of operations.
  5. Effectiveness: Operations must be basic enough to be performed accurately in finite time.

Flowchart Standard Symbols

Symbol ShapeNameOperational Function
Oval / StadiumTerminal BoxMarks the explicit Start or End of program execution logic.
ParallelogramInput / Output BoxRepresents data entry (input()) or display output (print()).
RectangleProcessing BoxRepresents calculation steps, variable updates, or data manipulation.
DiamondDecision BoxDenotes conditional checks returning True/False branch pathways.
Flow Lines / ArrowsArrowsConnect symbols to signify exact logical sequence and execution vector.

Key Definitions & Theoretical Foundations

  • Variable: A named identifier that points to a specific object stored in dynamic memory (RAM).
  • Data Type: An administrative attribute that informs the execution system how to interpret dynamic data values, what mathematical operations are valid, and how bits are allocated.
  • Operator: A operational symbol that instructs the interpreter to carry out mathematical, comparison, or logical transformations on operands.
  • Control Structure: A language construct that specifies execution direction, selecting pathways or repeating blocks based on Boolean conditions.
  • Function: A modular block of organized, reusable logic invoked by a name, accepting input parameters and optionally yielding return values.
  • Algorithm: A step-by-step, finite mathematical procedure written to resolve a specified computational problem.
  • Type Coercion (Implicit Conversion): Automatic data type conversion performed by the interpreter during expression evaluation to prevent data loss (e.g., adding int and float results in float).
  • Type Casting (Explicit Conversion): Explicitly converting a data structure from one data type to another using built-in conversion constructors (e.g., int(), str(), float()).
  • Short-Circuit Logic: An optimization technique where logical expression evaluation halts as soon as the outcome is fully determined without evaluating remaining terms.
  • Recursion: A computational technique where a defined function calls itself repeatedly until reaching a terminating base condition.

Important Terms & Syntax Mapping Table

TermOperational Syntax (Python 3)Purpose / Meaning
Variable Declarationx = 10Binds identifier x to integer object 10.
Type Checkingtype(obj)Returns data class/type associated with the referenced object.
Memory ID Inspectionid(obj)Returns unique integer representing object's memory location.
Type Conversionfloat("12.34")Explicitly converts valid numeric string "12.34" to floating-point 12.34.
Operator Precedence(a + b) * cExplicit grouping overrides standard operator precedence hierarchies.
Conditional Statementif condition:Initiates conditional execution block based on truth evaluation.
Iterative Rangerange(start, stop, step)Generates immutable sequence of integers across defined boundaries.
Function Definitiondef my_func(arg1):Defines reusable procedural block bearing designated parameter signatures.
Global Keywordglobal var_namePermits direct modification of module-level global variables inside functions.

Mathematical Formulas & Operator Precedence Matrix

Operator Precedence Hierarchy (Highest to Lowest)

When evaluating compound mathematical expressions, Python evaluates operations in the strict order detailed below:

PEMDAS / Operator Hierarchy Table\text{PEMDAS / Operator Hierarchy Table}

Priority LevelOperator CategorySymbols / SyntaxAssociativity
1 (Highest)Parentheses / Grouping()Left-to-Right
2Exponentiation**Right-to-Left
3Unary Operators+x, -x, ~xRight-to-Left
4Multiplicative Operators*, /, //, %Left-to-Right
5Additive Operators+, -Left-to-Right
6Bitwise Shifts<<, >>Left-to-Right
7Bitwise AND&Left-to-Right
8Bitwise XOR / OR^, |Left-to-Right
9Relational / Comparisons<, <=, >, >=, ==, !=Left-to-Right
10Identity & Membershipis, is not, in, not inLeft-to-Right
11Logical NOTnotRight-to-Left
12Logical ANDandLeft-to-Right
13 (Lowest)Logical ORorLeft-to-Right

Mathematical Evaluation Example

To evaluate E=5+2×32(8//3)E = 5 + 2 \times 3^2 - (8 // 3):

  1. Evaluate Parentheses: (8//3)=2(8 // 3) = 2
  2. Evaluate Exponentiation: 32=93^2 = 9
  3. Evaluate Multiplication: 2×9=182 \times 9 = 18
  4. Addition/Subtraction Left-to-Right: 5+182=215 + 18 - 2 = 21

Conceptual Diagrams & Architecture (Textual Descriptions)

Memory Reference Architecture (Python Object Reference Model)

Imagine dynamic memory as a grid with addressable cells. When executing a = 5 and b = a, Python allocates object 5 at memory location 0x10A. Identifiers a and b both store address 0x10A.

If a = a + 1 is later executed:

  1. Python evaluates 5 + 1 = 6.
  2. Creates new object 6 at address 0x10B.
  3. Variable a is updated to point to 0x10B.
  4. Variable b continues pointing to original address 0x10A (5).
Initial State (a = 5; b = a):
   [ Variable 'a' ] -------\
                            +----> [ Memory Address 0x10A : Int Object (5) ]
   [ Variable 'b' ] -------/

After Mutation (a = a + 1):
   [ Variable 'a' ] -------------> [ Memory Address 0x10B : Int Object (6) ]
   [ Variable 'b' ] -------------> [ Memory Address 0x10A : Int Object (5) ]

Deep-Dive Case Studies & Real-World Applications

Case Study 1: Financial Banking Transaction Processing Engine

In automated online banking, computational control structures process debit requests while enforcing business rules: ledger validation, overdraft limits, transaction limits, and multi-factor authorization.

def process_withdrawal(account_balance: float, withdrawal_amount: float, daily_limit: float, spent_today: float) -> tuple:
    """
    Simulates automated withdrawal execution logic with edge-case checks.
    """
    # Check 1: Positive value validation
    if withdrawal_amount <= 0:
        return False, "Invalid withdrawal amount requested."
    
    # Check 2: Account Balance limit validation
    if withdrawal_amount > account_balance:
        return False, "Transaction Declined: Insufficient account funds."
    
    # Check 3: Daily spending cap limits
    if (spent_today + withdrawal_amount) > daily_limit:
        return False, "Transaction Declined: Daily withdrawal limit exceeded."
    
    # Execution: Deduct balance
    new_balance = account_balance - withdrawal_amount
    new_spent_today = spent_today + withdrawal_amount
    
    return True, {"new_balance": new_balance, "spent_today": new_spent_today, "status": "APPROVED"}

# Test Run
balance, limit, spent = 25000.00, 10000.00, 4000.00
success, response = process_withdrawal(balance, 7000.00, limit, spent)
print(f"Transaction Success: {success} | Details: {response}")

Step-by-Step Problem Solving Strategies & Algorithm Design

Problem: Determine if an Integer is a Prime Number

A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself.

Algorithm Formulation Strategy (Trial Division Optimized to N\sqrt{N})

  1. Input: Read integer NN.
  2. Validation: If N1N \le 1, return False (1 and negative integers are not prime).
  3. Corner Cases: If N{2,3}N \in \{2, 3\}, return True. If NN is even or divisible by 3, return False.
  4. Loop Strategy: Loop variable ii from 5 up to N\lfloor\sqrt{N}\rfloor, incrementing by 6 (i,i+2i, i+2).
  5. Divisibility Check: If N%i==0N \% i == 0 or N%(i+2)==0N \% (i + 2) == 0, return False.
  6. Completion: If loop completes without finding factors, return True.

Python Implementation

import math

def is_prime(n: int) -> bool:
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    
    # Check potential factors up to sqrt(n)
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

# Test Execution
test_num = 29
print(f"Is {test_num} prime? Answer: {is_prime(test_num)}")

Higher-Order Thinking Skills (HOTS) Questions with Solutions

Q1. Predict the exact terminal output of the following script and detail the scope resolution mechanics at each step.

x = 50

def outer_scope():
    x = 20
    def inner_scope():
        global x
        x = 10
    print("Pre-inner x:", x)
    inner_scope()
    print("Post-inner x:", x)

print("Initial Global x:", x)
outer_scope()
print("Final Global x:", x)

Solution:

  1. x = 50: Initializes module global variable x with integer value 50.
  2. First print statement outputs: Initial Global x: 50.
  3. Calls outer_scope(): Creates local scope for outer_scope where local x = 20.
  4. Evaluates print("Pre-inner x:", x): Locates x in local scope (outer_scope). Outputs: Pre-inner x: 20.
  5. Calls inner_scope(): Declares global x, meaning references to x inside inner_scope modify the top-level global variable x, NOT outer_scope's local x.
  6. x = 10 overwrites global x from 50 to 10.
  7. inner_scope() exits. Evaluates print("Post-inner x:", x) inside outer_scope(): Locates x in outer_scope local scope, which remains 20. Outputs: Post-inner x: 20.
  8. outer_scope() exits. Evaluates print("Final Global x:", x): Reads updated global x. Outputs: Final Global x: 10.

Terminal Output:

Initial Global x: 50
Pre-inner x: 20
Post-inner x: 20
Final Global x: 10

Q2. Analyze the expression below and calculate its boolean result manually step-by-step applying Python's short-circuit rules.

res = (5 + 3 * 2 > 10) or (10 // 0 == 0) and not (4 % 2 == 0)

Solution:

  1. Breakdown Left Hand Side (LHS) of or: (5 + 3 * 2 > 10)
    • Multiplication first: 3 * 2 = 6
    • Addition next: 5 + 6 = 11
    • Relational operator: 11 > 10 \rightarrow True.
  2. Expression now simplifies to: True or (10 // 0 == 0) and not (4 % 2 == 0).
  3. Applying Short-Circuit Evaluation Rules: For logical or, if LHS is True, the entire expression evaluates to True without evaluating RHS.
  4. Notice that 10 // 0 would cause a ZeroDivisionError if evaluated. However, due to short-circuiting, RHS is skipped, avoiding runtime exception.
  5. Final value assigned to res is True.

Common Mistakes, Debugging Tips & Pitfalls

                          [ Common Python Bugs ]
                                     |
         +---------------------------+---------------------------+
         |                           |                           |
  [ Syntax Error ]           [ Runtime Exception ]        [ Logic Bug ]
  - IndentationError         - ZeroDivisionError          - Off-by-one error
  - Using '=' instead        - TypeError (str + int)      - Variable shadowing
    of '==' in 'if'          - NameError (Unbound)        - Loop infinite lock
  1. Confusing Assignment (=) with Equality Comparison (==):

    • Incorrect: if x = 10: (Triggers SyntaxError: invalid syntax).
    • Correct: if x == 10:
  2. Indentation Errors (IndentationError):

    • Python relies on consistent block indentation (standard: 4 spaces) rather than curly braces ({}). Mixing tabs and spaces leads to execution failure.
  3. String Concatenation with Non-String Types (TypeError):

    • Incorrect: print("Age is " + 18) (Triggers TypeError: can only concatenate str (not "int") to str).
    • Correct: print("Age is " + str(18)) or using f-strings print(f"Age is {18}").
  4. Off-By-One Errors in Loops:

    • range(1, 10) generates numbers from 1 to 9 (upper bound is non-inclusive). To include 10, write range(1, 11).
  5. Modifying Mutables while Iterating:

    • Removing items from a list while iterating directly over it alters loop index positions dynamically, leading to skipped elements. Iterate over a copy instead (for item in my_list[:]:).

Quick Revision

  • Variables are dynamic pointers referencing memory objects (id()).
  • Python data types split broadly into Mutable (list, dict, set) and Immutable (int, float, str, tuple, bool).
  • // denotes floor division; / produces float outcomes unconditionally.
  • Short-circuiting skips evaluating operands when logical outcome is already determined.
  • if-elif-else constructs evaluate sequentially; execution branches into the first True condition block only.
  • Iterative statement control: break exits entire loop; continue skips to next iteration.
  • Function variable resolution follows strict LEGB ordering: Local \rightarrow Enclosing \rightarrow Global \rightarrow Built-in.
  • Algorithms must satisfy 5 properties: Inputs, Outputs, Definiteness, Finiteness, and Effectiveness.

Chapter Summary

This chapter established the computational foundations required to write executable logic in Python. We explored how memory manages data dynamically via variables and reference tagging. We categorized built-in primitive and sequence data types while distinguishing immutable structures from mutable containers.

We systematically broke down mathematical and logical operator precedence alongside evaluate mechanics like short-circuiting. The chapter analyzed flow of control mechanisms—conditional branching structures and iterative loop architectures—along with loop break controls. We investigated functions, parameter mechanisms, scope resolution rules, and modular program structure. Finally, we learned how to design language-independent algorithms using structural flowcharts and pseudocode to establish systematic software development practices.


Previous Year Questions (PYQs) with Step-by-Step Solutions

Question 1 (CBSE 2020)

Evaluate the following Python expression and state the final result:

x = 12 + 4 ** 2 // 5 - 8

Solution:

  1. Identify Operator Hierarchy: Exponentiation (**), then Floor Division (//), then Addition (+) and Subtraction (-) left-to-right.
  2. Step 1: 4 ** 2 = 16
    • Expression: 12 + 16 // 5 - 8
  3. Step 2: Floor Division 16 // 5 = 3
    • Expression: 12 + 3 - 8
  4. Step 3: Addition 12 + 3 = 15
    • Expression: 15 - 8
  5. Step 4: Subtraction 15 - 8 = 7 Final Answer: 7

Question 2 (CBSE 2022)

Differentiate between is operator and == operator using a clean code example.

Solution:

  • == Operator (Value Equality): Compares whether the values/contents held by two objects are identical.
  • is Operator (Identity Verification): Compares whether two variable identifiers point to the identical memory address location (id(a) == id(b)).
# Code Demonstration
list1 = [10, 20, 30]
list2 = [10, 20, 30]

print(list1 == list2) # Outputs: True (Contents are equal)
print(list1 is list2) # Outputs: False (Reside in different RAM addresses)

Question 3 (CBSE 2023)

Rewrite the following code snippet using a while loop instead of a for loop, ensuring identical execution output:

total = 0
for k in range(5, 25, 4):
    total += k
print("Total:", total)

Solution:

total = 0
k = 5  # Initializer matching range start
while k < 25:  # Condition matching range stop boundary
    total += k
    k += 4  # Increment matching range step

print("Total:", total)

NCERT Textbook Questions & Detailed Answers

Q1. What is the difference between interactive mode and script mode in Python?

Answer:

  • Interactive Mode: Allows typing commands directly at the Python prompt (>>>). Execution occurs line-by-line instantly upon pressing Enter. Useful for rapid debugging and testing short expressions. Code written in interactive mode is not saved permanently.
  • Script Mode: Allows writing complete programs in a text editor, saving them with a .py extension, and executing the entire file together. Used for complex software development where logic needs to be stored, reused, and run repeatedly.

Q2. What are data types? How are they broadly classified in Python?

Answer: A data type defines the classification of a data value stored in memory. It informs the interpreter what valid operations can be performed on the data and how memory space should be allocated.

In Python, data types are classified as follows:

  1. Numbers: int, float, complex
  2. Boolean: bool (True or False)
  3. Sequences: str (String), list, tuple
  4. Mappings: dict (Dictionary)
  5. Sets: set
  6. Null Type: NoneType (None)

Q3. Explain the difference between mutable and immutable data types with suitable examples.

Answer:

  • Immutable Data Types: Data types whose values cannot be modified in-place after object creation. Any attempt to update an immutable variable creates a brand-new object at a different memory location.
    • Examples: int, float, str, tuple, bool.
    s = "hello"
    # s[0] = 'H'  # Raises TypeError: 'str' object does not support item assignment
    s = "Hello"   # Rebinds variable 's' to a new string object
    
  • Mutable Data Types: Data types whose values can be modified in-place without altering the underlying memory address of the object.
    • Examples: list, dict, set.
    lst = [10, 20, 30]
    lst[0] = 99   # Allowed! Updates first element in-place
    print(lst)    # Outputs: [99, 20, 30]
    

Q4. Write a Python program to calculate and display the factorial of a given positive integer NN.

Answer:

# Program to calculate Factorial of a Number

def calculate_factorial(n: int) -> int:
    if n < 0:
        return -1  # Indicates invalid negative input
    
    factorial = 1
    for i in range(1, n + 1):
        factorial *= i
    return factorial

# Driver Code
num = int(input("Enter a positive integer: "))

if num < 0:
    print("Factorial is not defined for negative numbers.")
else:
    result = calculate_factorial(num)
    print(f"The factorial of {num} is: {result}")

Q5. What is an algorithm? List the basic symbols used in a flowchart along with their functions.

Answer: An algorithm is a well-defined, step-by-step procedure designed to solve a specific problem in a finite number of execution steps.

Flowchart Symbols and Functions:

  1. Oval (Terminal): Marks the Start and End points of a program's logic flow.
  2. Parallelogram (Input/Output): Denotes data entry operations (input) or display outputs (print).
  3. Rectangle (Process): Represents mathematical operations, value assignments, and data manipulations.
  4. Diamond (Decision): Represents conditional branches where control splits based on a True/False evaluation.
  5. Flow Lines (Arrows): Connect symbols to show execution order.

Q6. Trace the output of the following Python code snippet for N=12N = 12:

n = int(input("Enter number: "))
a = 0
b = 1
while b < n:
    print(b, end=" ")
    a, b = b, a + b

Answer: This program generates and prints Fibonacci series terms that are strictly less than NN.

Trace Table for N=12N = 12:

IterationInitial aInitial bCondition b < 12Printed OutputNew a (b)New b (a + b)
1011 < 12 (True)1 10+1=10 + 1 = 1
2111 < 12 (True)1 11+1=21 + 1 = 2
3122 < 12 (True)2 21+2=31 + 2 = 3
4233 < 12 (True)3 32+3=52 + 3 = 5
5355 < 12 (True)5 53+5=83 + 5 = 8
6588 < 12 (True)8 85+8=135 + 8 = 13
781313 < 12 (False)Loop Exits--

Final Terminal Output:

1 1 2 3 5 8 

Pro Tip for this Chapter

Ensure you practice the in-text questions provided in the official NCERT PDF. If you find any topic difficult, review the formulas and concepts highlighted above. For advanced doubts, join our classroom coaching in Begusarai.