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:
- Variables and Memory Allocation: How values are stored, tagged, and referenced in RAM.
- Data Types and Mutability: Categorization of data, dynamic typing, and memory mutability rules.
- Operators and Precedence: The mathematical and logical machinery used to evaluate expressions.
- Control Structures (Flow of Control): Directing program execution sequentially, conditionally, or iteratively.
- Functions and Modularization: Decomposing complex software into reusable, encapsulated code units.
- 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 Category | Specific Type | Immutable / Mutable | Description & Example |
|---|---|---|---|
| Numeric | int | Immutable | Whole numbers of arbitrary precision: x = 42, y = -1005 |
float | Immutable | Double-precision IEEE 754 floating-point numbers: pi = 3.14159 | |
complex | Immutable | Numbers with real and imaginary parts: z = 3 + 4j | |
| Boolean | bool | Immutable | Truth values: True or False (subclass of int, where True == 1, False == 0) |
| Sequence | str | Immutable | Ordered sequence of Unicode characters: name = "Computer Science" |
tuple | Immutable | Ordered, immutable collection of arbitrary objects: point = (10, 20) | |
list | Mutable | Ordered, mutable collection of arbitrary objects: marks = [95, 88, 92] | |
| Mapping | dict | Mutable | Key-Value key-indexed collection: student = {"roll": 101, "name": "Aman"} |
| Set Types | set | Mutable | Unordered collection of unique hashable elements: unique_ids = {1, 2, 3} |
| Null Type | NoneType | Immutable | Represents 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
-
Arithmetic Operators:
- Addition (
+), Subtraction (-), Multiplication (*) - Division (
/): Always returns afloat(e.g.,7 / 2yields3.5). - Floor Division (
//): Rounds down to the nearest whole integer (e.g.,7 // 2yields3;-7 // 2yields-4). - Modulus (
%): Computes the remainder of division (e.g.,7 % 2yields1). - Exponentiation (
**): Raises left operand to the power of right operand (e.g.,2 ** 3yields8).
- Addition (
-
Relational (Comparison) Operators:
- Compare two values and evaluate to a Boolean (
TrueorFalse). ==(equal to),!=(not equal to),>(greater than),<(less than),>=(greater than or equal to),<=(less than or equal to).- Example:
'apple' < 'banana'evaluates toTruebased on lexicographical (ASCII/Unicode) ordering.
- Compare two values and evaluate to a Boolean (
-
Logical Operators & Short-Circuit Evaluation:
and: ReturnsTrueif both operands evaluate to true.or: ReturnsTrueif at least one operand evaluates to true.not: Inverts the truth value (not TruebecomesFalse).- Short-Circuit Mechanics:
- In
A and B, ifAisFalse, Python immediately returnsAwithout evaluatingB. - In
A or B, ifAisTrue, Python immediately returnsAwithout evaluatingB.
- In
# 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)
- 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).
- Identity (
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.
whileloop: Executes a body of statements as long as an entry condition remainsTrue(used when iterations are indefinite).forloop: Iterates over members of a sequence or iterable object using therange(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:
- L (Local): Names assigned inside the executing function.
- E (Enclosing): Names in local scope of enclosing/nesting functions (if any).
- G (Global): Names declared at the top level of the module file.
- 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
- Input: Accepts zero or more clearly defined inputs.
- Output: Produces at least one deterministic output.
- Definiteness: Every step must be clear, precise, and unambiguous.
- Finiteness: Must terminate after a finite number of operations.
- Effectiveness: Operations must be basic enough to be performed accurately in finite time.
Flowchart Standard Symbols
| Symbol Shape | Name | Operational Function |
|---|---|---|
| Oval / Stadium | Terminal Box | Marks the explicit Start or End of program execution logic. |
| Parallelogram | Input / Output Box | Represents data entry (input()) or display output (print()). |
| Rectangle | Processing Box | Represents calculation steps, variable updates, or data manipulation. |
| Diamond | Decision Box | Denotes conditional checks returning True/False branch pathways. |
| Flow Lines / Arrows | Arrows | Connect 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
intandfloatresults infloat). - 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
| Term | Operational Syntax (Python 3) | Purpose / Meaning |
|---|---|---|
| Variable Declaration | x = 10 | Binds identifier x to integer object 10. |
| Type Checking | type(obj) | Returns data class/type associated with the referenced object. |
| Memory ID Inspection | id(obj) | Returns unique integer representing object's memory location. |
| Type Conversion | float("12.34") | Explicitly converts valid numeric string "12.34" to floating-point 12.34. |
| Operator Precedence | (a + b) * c | Explicit grouping overrides standard operator precedence hierarchies. |
| Conditional Statement | if condition: | Initiates conditional execution block based on truth evaluation. |
| Iterative Range | range(start, stop, step) | Generates immutable sequence of integers across defined boundaries. |
| Function Definition | def my_func(arg1): | Defines reusable procedural block bearing designated parameter signatures. |
| Global Keyword | global var_name | Permits 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:
| Priority Level | Operator Category | Symbols / Syntax | Associativity |
|---|---|---|---|
| 1 (Highest) | Parentheses / Grouping | () | Left-to-Right |
| 2 | Exponentiation | ** | Right-to-Left |
| 3 | Unary Operators | +x, -x, ~x | Right-to-Left |
| 4 | Multiplicative Operators | *, /, //, % | Left-to-Right |
| 5 | Additive Operators | +, - | Left-to-Right |
| 6 | Bitwise Shifts | <<, >> | Left-to-Right |
| 7 | Bitwise AND | & | Left-to-Right |
| 8 | Bitwise XOR / OR | ^, | | Left-to-Right |
| 9 | Relational / Comparisons | <, <=, >, >=, ==, != | Left-to-Right |
| 10 | Identity & Membership | is, is not, in, not in | Left-to-Right |
| 11 | Logical NOT | not | Right-to-Left |
| 12 | Logical AND | and | Left-to-Right |
| 13 (Lowest) | Logical OR | or | Left-to-Right |
Mathematical Evaluation Example
To evaluate :
- Evaluate Parentheses:
- Evaluate Exponentiation:
- Evaluate Multiplication:
- Addition/Subtraction Left-to-Right:
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:
- Python evaluates
5 + 1 = 6. - Creates new object
6at address0x10B. - Variable
ais updated to point to0x10B. - Variable
bcontinues pointing to original address0x10A(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 )
- Input: Read integer .
- Validation: If , return
False(1 and negative integers are not prime). - Corner Cases: If , return
True. If is even or divisible by 3, returnFalse. - Loop Strategy: Loop variable from 5 up to , incrementing by 6 ().
- Divisibility Check: If or , return
False. - 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:
x = 50: Initializes module global variablexwith integer value50.- First
printstatement outputs:Initial Global x: 50. - Calls
outer_scope(): Creates local scope forouter_scopewhere localx = 20. - Evaluates
print("Pre-inner x:", x): Locatesxin local scope (outer_scope). Outputs:Pre-inner x: 20. - Calls
inner_scope(): Declaresglobal x, meaning references toxinsideinner_scopemodify the top-level global variablex, NOTouter_scope's localx. x = 10overwrites globalxfrom50to10.inner_scope()exits. Evaluatesprint("Post-inner x:", x)insideouter_scope(): Locatesxinouter_scopelocal scope, which remains20. Outputs:Post-inner x: 20.outer_scope()exits. Evaluatesprint("Final Global x:", x): Reads updated globalx. 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:
- Breakdown Left Hand Side (LHS) of
or:(5 + 3 * 2 > 10)- Multiplication first:
3 * 2 = 6 - Addition next:
5 + 6 = 11 - Relational operator:
11 > 10True.
- Multiplication first:
- Expression now simplifies to:
True or (10 // 0 == 0) and not (4 % 2 == 0). - Applying Short-Circuit Evaluation Rules: For logical
or, if LHS isTrue, the entire expression evaluates toTruewithout evaluating RHS. - Notice that
10 // 0would cause aZeroDivisionErrorif evaluated. However, due to short-circuiting, RHS is skipped, avoiding runtime exception. - Final value assigned to
resisTrue.
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
-
Confusing Assignment (
=) with Equality Comparison (==):- Incorrect:
if x = 10:(TriggersSyntaxError: invalid syntax). - Correct:
if x == 10:
- Incorrect:
-
Indentation Errors (
IndentationError):- Python relies on consistent block indentation (standard: 4 spaces) rather than curly braces (
{}). Mixing tabs and spaces leads to execution failure.
- Python relies on consistent block indentation (standard: 4 spaces) rather than curly braces (
-
String Concatenation with Non-String Types (
TypeError):- Incorrect:
print("Age is " + 18)(TriggersTypeError: can only concatenate str (not "int") to str). - Correct:
print("Age is " + str(18))or using f-stringsprint(f"Age is {18}").
- Incorrect:
-
Off-By-One Errors in Loops:
range(1, 10)generates numbers from 1 to 9 (upper bound is non-inclusive). To include 10, writerange(1, 11).
-
Modifying Mutables while Iterating:
- Removing items from a
listwhile iterating directly over it alters loop index positions dynamically, leading to skipped elements. Iterate over a copy instead (for item in my_list[:]:).
- Removing items from a
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-elseconstructs evaluate sequentially; execution branches into the firstTruecondition block only.- Iterative statement control:
breakexits entire loop;continueskips to next iteration. - Function variable resolution follows strict LEGB ordering: Local Enclosing Global 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:
- Identify Operator Hierarchy: Exponentiation (
**), then Floor Division (//), then Addition (+) and Subtraction (-) left-to-right. - Step 1:
4 ** 2 = 16- Expression:
12 + 16 // 5 - 8
- Expression:
- Step 2: Floor Division
16 // 5 = 3- Expression:
12 + 3 - 8
- Expression:
- Step 3: Addition
12 + 3 = 15- Expression:
15 - 8
- Expression:
- Step 4: Subtraction
15 - 8 = 7Final 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.isOperator (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
.pyextension, 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:
- Numbers:
int,float,complex - Boolean:
bool(TrueorFalse) - Sequences:
str(String),list,tuple - Mappings:
dict(Dictionary) - Sets:
set - 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 - Examples:
- 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] - Examples:
Q4. Write a Python program to calculate and display the factorial of a given positive integer .
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:
- Oval (Terminal): Marks the Start and End points of a program's logic flow.
- Parallelogram (Input/Output): Denotes data entry operations (
input) or display outputs (print). - Rectangle (Process): Represents mathematical operations, value assignments, and data manipulations.
- Diamond (Decision): Represents conditional branches where control splits based on a
True/Falseevaluation. - Flow Lines (Arrows): Connect symbols to show execution order.
Q6. Trace the output of the following Python code snippet for :
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 .
Trace Table for :
| Iteration | Initial a | Initial b | Condition b < 12 | Printed Output | New a (b) | New b (a + b) |
|---|---|---|---|---|---|---|
| 1 | 0 | 1 | 1 < 12 (True) | 1 | 1 | |
| 2 | 1 | 1 | 1 < 12 (True) | 1 | 1 | |
| 3 | 1 | 2 | 2 < 12 (True) | 2 | 2 | |
| 4 | 2 | 3 | 3 < 12 (True) | 3 | 3 | |
| 5 | 3 | 5 | 5 < 12 (True) | 5 | 5 | |
| 6 | 5 | 8 | 8 < 12 (True) | 8 | 8 | |
| 7 | 8 | 13 | 13 < 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.