Unit 2: Computational Thinking & Programming
Chapter 1: Introduction to Python and Basics
1. Computational Thinking and Problem Solving
Computational Thinking is a problem-solving methodology that involves decomposing complex problems into smaller, manageable subproblems, recognizing patterns, abstracting unnecessary details, and designing step-by-step algorithms.
+--------------------------------------------------------------+
| Four Pillars of Computational Thinking |
+--------------------------------------------------------------+
| 1. Decomposition | Breaking a complex system into parts |
| 2. Pattern Recog. | Spotting recurring behaviors and trends |
| 3. Abstraction | Filtering out details to focus on core |
| 4. Algorithms | Designing ordered, unambiguous steps |
+--------------------------------------------------------------+
Steps in Program Development
- Problem Definition: Clearly understanding what the program must accept as input and produce as output.
- Algorithm Design: Writing precise, finite, unambiguous instructions in natural language or pseudocode.
- Flowchart Representation: Graphically mapping control flow using standard ANSI symbols (Oval: Start/End; Parallelogram: Input/Output; Rectangle: Process; Diamond: Decision).
- Coding: Translating the logic into executable Python code.
- Testing & Debugging: Isolating and rectifying syntax, logical, and runtime errors.
- Documentation: Commenting code to facilitate long-term maintenance.
2. Overview of Python
Created by Guido van Rossum and first released in 1991, Python is an interpreted, high-level, dynamically-typed, general-purpose programming language.
Key Features of Python
- Simple and Readable: Emphasizes readable syntax close to plain English, minimizing boilerplate code.
- Interpreted Language: Python source code (
.py) is compiled to intermediate bytecode (.pyc) and executed line-by-line by the Python Virtual Machine (PVM). - Cross-Platform / Portable: Runs identically across Windows, macOS, Linux, and embedded microcontrollers without modification.
- Free and Open-Source (FLOSS): Distributed under the OSI-compliant Python Software Foundation License.
- Extensive Standard Library: Built-in batteries-included modules for math, networking, file I/O, web processing, and cryptography.
- Dynamically Typed: Variable types do not need to be explicitly declared; types are resolved dynamically at runtime based on assigned values.
3. Working in Python: Execution Modes
Python programs can be authored and executed in two primary modes:
1. Interactive Mode (Python REPL / Shell)
- Commands are typed directly at the primary prompt (
>>>). - When Enter is pressed, the Python interpreter immediately evaluates the expression and displays the result.
- Best for: Quick experimentation, testing single expressions, and inspecting module functions.
- Limitation: Instructions are not saved to a file; they vanish when the shell window closes.
>>> 15 * 4 + 10
70
>>> name = "CBSE"
>>> print(f"Welcome to {name}")
Welcome to CBSE
2. Script Mode
- Python statements are written in a plain text editor, saved as a file with the
.pyextension, and executed all at once. - Best for: Developing reusable scripts, practical programs, and production projects.
4. Python Lexical Structure: Tokens
A Token is the smallest individual unit in a Python source program recognized by the interpreter.
+--------------------------+
| Python Tokens |
+--------------------------+
/ | | | \
Keywords Identifiers Literals Operators Delimiters
A. Keywords
Reserved words having predefined special meanings to the Python interpreter. They cannot be used as variable names or identifiers. Python 3 has 35+ keywords:
# False, None, True, and, as, assert, async, await, break, class,
# continue, def, del, elif, else, except, finally, for, from, global,
# if, import, in, is, lambda, nonlocal, not, or, pass, raise,
# return, try, while, with, yield
Note: Except for
True,False, andNone, all Python keywords are written entirely in lowercase.
B. Identifiers (Naming Rules)
Identifiers are user-defined names given to variables, functions, classes, and modules:
1. Must begin with an uppercase or lowercase letter (A-Z, a-z) or an underscore (_).
2. Cannot begin with a numerical digit (0-9).
3. Can contain letters, digits, and underscores, but no punctuation marks, spaces, or special characters (@, $, %, -).
4. Identifiers are strictly case-sensitive (roll_no, Roll_No, and ROLL_NO are three completely distinct variables).
5. Must not be a Python keyword.
# Valid Identifiers:
student_age, _total, marks_100, class_xi, MaxScore
# Invalid Identifiers:
1st_rank # Error: starts with a digit
roll-no # Error: contains hyphen (-)
class # Error: 'class' is a reserved keyword
total marks # Error: contains whitespace
C. Literals
Fixed constant data values provided directly in code:
- Integer Literals: 42, -17, 0
- Floating-point Literals: 3.14159, -0.005, 2.5e-3
- String Literals: 'Hello', "Computer Science", '''Multi-line text'''
- Boolean Literals: True and False
- Special Literal None: Represents the absence of a value or a null object.
D. Comments
Explanatory notes ignored by the Python interpreter:
- Single-line Comments: Begin with the hash symbol (#).
- Multi-line Comments / Docstrings: Triple-quoted strings (\'\'\' or \"\"\") placed at the start of a module, class, or function.
5. Input and Output in Python
The print() Function
Used to send formatted output to the console.
print(*objects, sep=' ', end='\n')
sep: String inserted between multiple arguments (defaults to a single space' ').end: String appended at the end of the line (defaults to newline'\n').
# Example: Customizing sep and end
print("Class", "11", "CS", sep="-")
print("CBSE", end=" | ")
print("NCERT")
Output:
Class-11-CS
CBSE | NCERT
The input() Function
Accepts user input from the standard input console.
Important CBSE Point: The
input()function always returns user data as a string (str), regardless of what is typed. Type casting is required to convert it to an integer or float.
# Accepting integer input
roll = int(input("Enter Roll Number: "))
# Accepting floating-point input
marks = float(input("Enter Marks: "))
# Computing result
print("Roll:", roll, "Next Year Roll:", roll + 1)
6. Board Exam Practice Questions & Solutions
Q1. Identify valid and invalid identifiers from the following list with reasons:
_sum, 2ndDay, my_var, class, total$marks
Answer:
- _sum: Valid (begins with underscore).
- 2ndDay: Invalid (cannot begin with a numeric digit).
- my_var: Valid (contains letters and underscore).
- class: Invalid (class is a reserved keyword in Python).
- total$marks: Invalid (contains illegal special character $).
Q2. What will be the output of the following code snippet?
x = "25"
y = "35"
print(x + y)
print(int(x) + int(y))
Answer:
2535
60
Explanation: x + y performs string concatenation because x and y are of type str. int(x) + int(y) performs numerical addition after explicit type conversion.
Q3. State the significance of the sep and end parameters in Python's print() function.
Answer:
- The sep parameter defines the separator string placed between multiple values passed to print(). By default, it is a single space (sep=' ').
- The end parameter defines the character(s) printed at the very end of the print() call. By default, it is a newline (end='\n'), causing subsequent output to appear on the next line. Overriding end=' ' prevents the line break.