Unit 2: Computational Thinking and Programming
Class 11 Computer Science - CBSE Syllabus
Chapter 4: Introduction to Python
4.1 Python Overview
· Created by: Guido van Rossum (released in 1991)
· Philosophy: "Simple is better than complex"
· Current Version: Python 3.x (CBSE uses Python 3)
4.2 Features of Python
· ✓ Interpreted: Executes line by line
· ✓ High-level: Easy to read and write
· ✓ Dynamically typed: No need to declare variable types
· ✓ Open source: Free to use and distribute
· ✓ Cross-platform: Runs on Windows, Linux, Mac
· ✓ Extensive libraries: Rich collection of modules
4.3 Python Character Set
· Letters: A-Z, a-z
· Digits: 0-9
· Special Symbols: + - * / % = < > ! & | ^ ~ etc.
· Whitespace: Space, tab, newline
· Punctuation: : ; ' " , . ? ( ) [ ] { }
4.4 Writing and Executing Python Programs
Methods of Execution:
1. Interactive Mode: Type commands directly at >>> prompt
2. Script Mode: Write code in file with .py extension and execute
First Python Program:
```python
# Simple Hello World Program
print("Hello, World!")
print("Welcome to Python Programming")
```
---
Chapter 5: Python Fundamentals
5.1 Python Tokens
Tokens are the smallest individual units in a program.
5.1.1 Keywords
Reserved words with special meaning (35 keywords in Python 3.7)
Category Keywords
Flow Control if, else, elif, for, while, break, continue, pass
Logical and, or, not, is, in
Exception try, except, finally, raise, assert
Function def, return, lambda, yield
Class class, self
Import import, from, as
Variable global, nonlocal
Others del, with, None, True, False
5.1.2 Identifiers
Names given to variables, functions, classes, etc.
Rules for Identifiers:
1. Must start with letter (A-Z, a-z) or underscore (_)
2. Can contain letters, digits (0-9), and underscores
3. Cannot be a keyword
4. Case-sensitive (Age ≠ age)
5. No special characters except underscore
Examples:
```python
valid = True # Valid
_name = "John" # Valid
age1 = 20 # Valid
2nd_value = 30 # Invalid (starts with digit)
my-name = "Alex" # Invalid (contains hyphen)
```
5.1.3 Literals
Constant values that appear directly in the code.
Types of Literals:
Type Examples Description
Numeric 15, -3, 0, 3.14, -2.5, 3+4j Integer, float, complex
String "Hello", 'Python', """Multi-line""" Sequence of characters
Boolean True, False Logical values
Special None Represents absence of value
5.1.4 Operators
Symbols that perform operations on operands.
Arithmetic Operators:
```python
a+b # Addition
a-b # Subtraction
a*b # Multiplication
a/b # Division (float result)
a // b # Floor Division (integer result)
a%b # Modulus (remainder)
a ** b # Exponentiation (power)
```
Comparison Operators:
```python
a == b # Equal to
a != b # Not equal to
a<b # Less than
a>b # Greater than
a <= b # Less than or equal to
a >= b # Greater than or equal to
```
Logical Operators:
```python
a and b # Both must be True
a or b # At least one must be True
not a # Reverses Boolean value
```
Assignment Operators:
```python
= # Assign
+= # Add and assign (a += b → a = a + b)
-= # Subtract and assign
*= # Multiply and assign
/= # Divide and assign
//= # Floor divide and assign
%= # Modulus and assign
**= # Exponent and assign
```
5.1.5 Punctuators
Special symbols with syntactic meaning: ( ) [ ] { } , : ; @ = ->
5.2 Variables and Assignments
Variable Declaration and Assignment:
```python
# Single assignment
counter = 10
name = "Alice"
# Multiple assignment
x, y, z = 10, 20, 30
a=b=c=0
# Dynamic typing - same variable can hold different types
var = 10 # Integer
var = 3.14 # Float
var = "Text" # String
```
5.3 Data Types in Python
Data Type Category Mutable Example Description
int Numeric Immutable 5, -10, 0 Whole numbers
float Numeric Immutable 3.14, -0.5, 2.0 Decimal numbers
complex Numeric Immutable 3+4j, -2j Real + imaginary
str Sequence Immutable "Hello", 'Python' Text data
bool Boolean Immutable True, False Logical values
list Sequence Mutable [1, 2, 3], ['a', 'b'] Ordered collection
tuple Sequence Immutable (1, 2, 3), ('x', 'y') Immutable list
dict Mapping Mutable {'a':1, 'b':2} Key-value pairs
set Set Mutable {1, 2, 3} Unordered, unique
5.4 Type Conversion
Implicit Conversion (Automatic):
```python
result = 5 + 2.3 # int + float → float (7.3)
```
Explicit Conversion (Manual):
```python
# Using type conversion functions
int() # Convert to integer
float() # Convert to float
str() # Convert to string
bool() # Convert to boolean
list() # Convert to list
tuple() # Convert to tuple
# Examples
num_str = "123"
num_int = int(num_str) # String to integer → 123
value = 25
value_str = str(value) # Integer to string → "25"
pi = 3.14
pi_int = int(pi) # Float to integer → 3 (truncates)
```
---
Chapter 6: Input and Output Operations
6.1 Input Function
```python
input(prompt) # Always returns string
```
Examples:
```python
# Basic input
name = input("Enter your name: ")
# Input with type conversion
age = int(input("Enter your age: "))
height = float(input("Enter height in meters: "))
# Multiple inputs in one line
x, y = input("Enter two numbers: ").split()
x = int(x)
y = int(y)
```
6.2 Output Function
```python
print(value1, value2, ..., sep=' ', end='\n', file=[Link])
```
Parameters:
· sep: Separator between values (default: space)
· end: What to print at end (default: newline)
· file: Where to send output (default: screen)
Examples:
```python
# Simple print
print("Hello World")
# Multiple values
print("Name:", name, "Age:", age)
# Changing separator
print("Python", "Java", "C++", sep=" | ") # Output: Python | Java | C++
# Changing end character
print("Hello", end=" ")
print("World") # Output: Hello World
# Formatted output
print(f"Result: {x + y}") # f-string (Python 3.6+)
print("Result: {}".format(x + y)) # format method
```
6.3 Formatting Output
Using format() method:
```python
# Positional arguments
print("{} + {} = {}".format(5, 3, 8)) # 5 + 3 = 8
# Named arguments
print("{name} is {age} years old".format(name="Alice", age=20))
# Format specification
pi = 3.14159
print("Value: {:.2f}".format(pi)) # Value: 3.14
```
Using f-strings (Recommended):
```python
name = "Alice"
age = 20
print(f"{name} is {age} years old")
# Expressions in f-strings
a, b = 5, 3
print(f"{a} × {b} = {a * b}")
# Formatting in f-strings
price = 49.99
print(f"Price: ${price:.2f}")
```
---
Chapter 7: Flow Control Statements
7.1 Conditional Statements
7.1.1 Simple if Statement
```python
if condition:
statement1
statement2
# ... more statements
```
Example:
```python
age = 18
if age >= 18:
print("You are eligible to vote")
print("Please register yourself")
```
7.1.2 if-else Statement
```python
if condition:
# Block executed if condition is True
statements
else:
# Block executed if condition is False
statements
```
Example:
```python
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is Even")
else:
print(f"{num} is Odd")
```
7.1.3 if-elif-else Ladder
```python
if condition1:
statements
elif condition2:
statements
elif condition3:
statements
else:
statements
```
Example: Grading System
```python
marks = float(input("Enter marks: "))
if marks >= 90:
grade = 'A'
elif marks >= 80:
grade = 'B'
elif marks >= 70:
grade = 'C'
elif marks >= 60:
grade = 'D'
else:
grade = 'F'
print(f"Grade: {grade}")
```
7.1.4 Nested if Statements
```python
if condition1:
statements
if condition2:
statements
else:
statements
else:
statements
```
Example:
```python
age = int(input("Enter age: "))
if age >= 18:
country = input("Enter country: ")
if [Link]() == "india":
print("You can vote in India")
else:
print("Check your country's voting rules")
else:
print("You cannot vote")
```
7.2 Iterative Statements (Loops)
7.2.1 for Loop
```python
for variable in sequence:
statements
```
Examples:
```python
# Using range() function
for i in range(5): # 0 to 4
print(i)
for i in range(1, 6): # 1 to 5
print(i)
for i in range(1, 11, 2): # 1, 3, 5, 7, 9
print(i)
# Looping through strings
text = "Python"
for char in text:
print(char)
# Looping through lists
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
7.2.2 while Loop
```python
while condition:
statements
```
Examples:
```python
# Print numbers 1 to 5
i=1
while i <= 5:
print(i)
i += 1
# Sum of digits
num = int(input("Enter a number: "))
sum_digits = 0
while num > 0:
digit = num % 10
sum_digits += digit
num = num // 10
print(f"Sum of digits: {sum_digits}")
```
7.3 Loop Control Statements
7.3.1 break Statement
Exits the loop immediately
```python
# Find first multiple of 7
for num in range(1, 50):
if num % 7 == 0:
print(f"First multiple of 7 is {num}")
break
```
7.3.2 continue Statement
Skips current iteration and continues with next
```python
# Print odd numbers only
for num in range(1, 11):
if num % 2 == 0:
continue
print(num) # Prints 1, 3, 5, 7, 9
```
7.3.3 pass Statement
Placeholder for empty block
```python
for num in range(1, 6):
if num % 2 == 0:
pass # Do nothing for even numbers
else:
print(num)
```
7.4 Nested Loops
```python
# Multiplication table
for i in range(1, 6):
for j in range(1, 11):
print(f"{i} × {j} = {i * j}")
print() # Empty line after each table
```
---
Chapter 8: Debugging Programs
8.1 Types of Errors
8.1.1 Syntax Errors
Violation of Python grammar rules
```python
# Missing parenthesis
print("Hello" # Error
# Missing colon
if x > 5 # Error
print(x)
# Incorrect indentation
if True:
print("Hello") # Error
```
8.1.2 Logical Errors
Program runs but produces incorrect results
```python
# Wrong formula for average
a, b = 10, 20
average = a + b / 2 # Should be (a + b) / 2
# Infinite loop
i=1
while i > 0: # Condition always True
print(i)
i += 1
```
8.1.3 Runtime Errors
Occur during program execution
```python
# Division by zero
x = 10 / 0 # ZeroDivisionError
# Type error
num = "abc"
result = num + 5 # TypeError
# Index error
lst = [1, 2, 3]
value = lst[5] # IndexError
# Value error
num = int("abc") # ValueError
```
8.2 Debugging Techniques
8.2.1 Manual Tracing (Dry Run)
Execute code line by line on paper
Example:
```python
sum = 0
for i in range(1, 4):
sum = sum + i
print(sum)
```
Dry Run Table:
i sum before sum after
101
213
336
Output: 6
8.2.2 Using Print Statements
Add print statements to track variable values
```python
def factorial(n):
fact = 1
for i in range(1, n+1):
fact = fact * i
print(f"i={i}, fact={fact}") # Debug print
return fact
```
8.2.3 Common Debugging Strategies
1. Read error messages carefully
2. Check for common mistakes:
· Typos in variable names
· Missing colons
· Incorrect indentation
· Mismatched parentheses/brackets
3. Test with simple inputs first
4. Comment out sections to isolate problems
5. Use Python's built-in debugger (pdb)
---
Chapter 9: Important Programs for Practice
9.1 Number Programs
Program 1: Factorial of a Number
```python
# Using for loop
n = int(input("Enter a number: "))
fact = 1
for i in range(1, n+1):
fact = fact * i
print(f"Factorial of {n} is {fact}")
```
Program 2: Check Prime Number
```python
num = int(input("Enter a number: "))
is_prime = True
if num <= 1:
is_prime = False
else:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
```
Program 3: Fibonacci Series
```python
n = int(input("Enter number of terms: "))
a, b = 0, 1
print("Fibonacci series:")
for i in range(n):
print(a, end=" ")
a, b = b, a + b
```
9.2 Pattern Programs
Program 4: Right Triangle Pattern
```python
n = int(input("Enter number of rows: "))
for i in range(1, n+1):
for j in range(1, i+1):
print("*", end="")
print()
```
Program 5: Number Pyramid
```python
n = int(input("Enter number of rows: "))
for i in range(1, n+1):
# Print spaces
for j in range(n-i):
print(" ", end="")
# Print numbers
for j in range(1, i+1):
print(j, end="")
print()
```
9.3 String Programs
Program 6: Palindrome Check
```python
string = input("Enter a string: ")
string = [Link]()
reversed_string = string[::-1]
if string == reversed_string:
print("The string is a palindrome")
else:
print("The string is not a palindrome")
```
Program 7: Count Vowels and Consonants
```python
text = input("Enter a string: ").lower()
vowels = consonants = 0
for char in text:
if [Link]():
if char in 'aeiou':
vowels += 1
else:
consonants += 1
print(f"Vowels: {vowels}")
print(f"Consonants: {consonants}")
```
9.4 Mathematical Programs
Program 8: Armstrong Number
```python
num = int(input("Enter a number: "))
order = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(f"{num} is an Armstrong number")
else:
print(f"{num} is not an Armstrong number")
```
Program 9: LCM and GCD
```python
# Function to find GCD
def gcd(a, b):
while b:
a, b = b, a % b
return a
# Function to find LCM
def lcm(a, b):
return (a * b) // gcd(a, b)
# Main program
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(f"GCD of {num1} and {num2} is {gcd(num1, num2)}")
print(f"LCM of {num1} and {num2} is {lcm(num1, num2)}")
```
---
Chapter 10: Quick Reference
10.1 Python Operators Precedence
```
1. ** Exponentiation
2. +x, -x, ~x Unary plus/minus, bitwise NOT
3. *, /, //, % Multiplication, division, floor division, modulus
4. +, - Addition, subtraction
5. <<, >> Bitwise shifts
6. & Bitwise AND
7. ^ Bitwise XOR
8. | Bitwise OR
9. ==, !=, <, >, <=, >= Comparisons
10. not Boolean NOT
11. and Boolean AND
12. or Boolean OR
```
10.2 Common Built-in Functions
Function Description Example
len() Returns length of sequence len("Hello") → 5
type() Returns data type type(10) → <class 'int'>
int() Converts to integer int("25") → 25
float() Converts to float float("3.14") → 3.14
str() Converts to string str(100) → "100"
abs() Returns absolute value abs(-5) → 5
round() Rounds a number round(3.14159, 2) → 3.14
max() Returns maximum value max(5, 10, 3) → 10
min() Returns minimum value min(5, 10, 3) → 3
sum() Sum of elements sum([1, 2, 3]) → 6
10.3 Common Error Messages
· SyntaxError: Invalid syntax
· IndentationError: Incorrect indentation
· NameError: Variable not defined
· TypeError: Wrong data type used
· ValueError: Wrong value for operation
· IndexError: Index out of range
· ZeroDivisionError: Division by zero
· KeyboardInterrupt: Ctrl+C pressed
10.4 Important Formulae
```
Factorial: n! = 1 × 2 × 3 × ... × n
Fibonacci: F(n) = F(n-1) + F(n-2), where F(0)=0, F(1)=1
Sum of first n natural numbers: n(n+1)/2
Sum of squares of first n natural numbers: n(n+1)(2n+1)/6
Armstrong number: Sum of digits^number_of_digits = number
Prime number: Divisible only by 1 and itself
```
---
Chapter 11: CBSE Question Pattern
11.1 Types of Questions
Theory Questions (2-3 marks each)
1. Define Computational Thinking and its components
2. Difference between algorithm and flowchart
3. Explain Python tokens with examples
4. Differentiate between = and == operators
5. Explain if-elif-else ladder with example
Programming Questions (3-5 marks each)
1. Write a program to find factorial
2. Program to check palindrome number/string
3. Pattern printing programs
4. Programs using loops (sum of series, tables, etc.)
5. Programs with conditional statements
Output Prediction (2 marks each)
```python
# Example 1
x=5
y=2
print(x // y, x % y) # Output: 2 1
# Example 2
for i in range(3):
for j in range(i+1):
print("*", end="")
print()
# Output:
#*
# **
# ***
```
Error Finding (2 marks each)
```python
# Find errors
x = input("Enter number") # Missing type conversion
if x > 10: # Comparing string with integer
print("Large")
```
11.2 Marking Scheme Guidelines
· Algorithm/Flowchart: 2 marks (steps + correctness)
· Program: 3-5 marks (logic + syntax + output)
· Variable naming: 0.5 marks
· Comments: 0.5 marks
· Correct output: 1 mark
---
Chapter 12: Preparation Tips
12.1 Study Strategy
1. Understand Concepts First: Don't memorize, understand the logic
2. Practice Regularly: Code daily, start with simple programs
3. Trace Programs Manually: Practice dry runs for output prediction
4. Solve Previous Years' Papers: Familiarize with question patterns
5. Create Your Own Notes: Summarize each topic in your own words
12.2 Exam Strategy
1. Read Questions Carefully: Understand what is asked
2. Plan Before Writing: Write algorithm/pseudocode first
3. Write Clean Code: Use meaningful variable names, add comments
4. Check Boundary Cases: Test with extreme values
5. Review Answers: Check for syntax errors, indentation
12.3 Common Mistakes to Avoid
· ❌ Forgetting colons after if/for/while
· ❌ Incorrect indentation (use 4 spaces consistently)
· ❌ Using = instead of == for comparison
· ❌ Not converting input() to required type
· ❌ Infinite loops (missing increment/decrement)
· ❌ Off-by-one errors in range()
---
End of Unit 2 Notes
Best of luck for your exams! Practice is the key to success in programming.