C11U2_CT&P-1_45

 

CBSE Class 11 Computer Science (083)

Unit 2: Computational Thinking and Programming – I

Complete Easy Notes with Examples, Programs, Flowcharts and Exam Revision


1. Introduction to Computational Thinking

Computational Thinking is a systematic way of solving problems by breaking a problem into smaller and manageable parts and developing clear steps that can be followed by a computer.

It is not simply "thinking like a computer". It is a problem-solving approach.

Main Ideas of Computational Thinking

                 COMPUTATIONAL THINKING
                          │
          ┌───────────────┼────────────────┐
          ↓               ↓                ↓
     Decomposition    Pattern          Abstraction
                      Recognition
          │               │                │
          └───────────────┼────────────────┘
                          ↓
                     Algorithm
                          ↓
                       Program

Important Concepts

  1. Decomposition – breaking a large problem into smaller parts.

  2. Pattern Recognition – identifying similarities or repeated patterns.

  3. Abstraction – concentrating on important information and ignoring unnecessary details.

  4. Algorithmic Thinking – developing a step-by-step solution.


2. Problem-Solving

Problem-solving means finding a logical and systematic method to solve a given problem.

A computer program should not normally be written immediately after reading a problem. First, the problem should be understood and a solution should be planned.

Basic Steps of Problem-Solving

       START
         │
         ↓
 Analyze the Problem
         │
         ↓
 Develop Algorithm
         │
         ↓
 Flowchart / Pseudocode
         │
         ↓
      Coding
         │
         ↓
      Testing
         │
         ↓
     Debugging
         │
         ↓
       Solution

Main Steps

  1. Analyse the problem.

  2. Identify input and output.

  3. Develop an algorithm.

  4. Represent the solution using a flowchart/pseudocode.

  5. Write the program.

  6. Test the program.

  7. Find and correct errors.

  8. Finalise the solution.


3. Analysing a Problem

Before writing a program, identify:

Input

What information is required?

Processing

What calculations or operations are required?

Output

What result should be produced?

Example

Problem:

Find the area of a rectangle.

ComponentDescription
InputLength and breadth
ProcessingArea = length × breadth
OutputArea

4. Decomposition

Decomposition means dividing a large problem into smaller sub-problems.

Example

Problem:

Develop a student result program.

It can be divided into:

Student Result
      │
      ├── Input student details
      ├── Input marks
      ├── Calculate total
      ├── Calculate percentage
      ├── Determine result
      └── Display result

Each smaller task becomes easier to understand and implement.

Advantages

  • Makes complex problems easier.

  • Makes coding easier.

  • Makes testing easier.

  • Helps locate errors.

  • Allows different parts to be developed separately.


5. Algorithm

An algorithm is a finite sequence of clear and unambiguous steps used to solve a problem.

Characteristics of a Good Algorithm

  • Clear

  • Unambiguous

  • Finite

  • Logical

  • Has defined input

  • Produces the required output

Example: Algorithm to Add Two Numbers

Step 1: Start
Step 2: Input A
Step 3: Input B
Step 4: Calculate S = A + B
Step 5: Display S
Step 6: Stop

6. Flowchart

A flowchart is a graphical representation of an algorithm.

It uses standard symbols to represent different operations.

Common Flowchart Symbols

SymbolMeaning
OvalStart/Stop
RectangleProcess
ParallelogramInput/Output
DiamondDecision
ArrowFlow direction

Basic Flowchart

       ┌───────────┐
       │   START   │
       └─────┬─────┘
             ↓
       ╱───────────╲
      ╱  Input A,B  ╲
      ╲             ╱
       ╲───────────╱
             ↓
       ┌─────────────┐
       │ S = A + B   │
       └──────┬──────┘
              ↓
       ╱─────────────╲
      ╱  Display S    ╲
      ╲               ╱
       ╲─────────────╱
              ↓
       ┌───────────┐
       │   STOP    │
       └───────────┘

7. Pseudocode

Pseudocode is an informal, programming-like description of an algorithm.

It is easier to understand than actual programming code.

Example

Problem: Find the larger of two numbers.

START
INPUT A, B
IF A > B THEN
    DISPLAY A
ELSE
    DISPLAY B
END IF
STOP

Algorithm vs Pseudocode vs Flowchart

AlgorithmPseudocodeFlowchart
Step-by-step textual solutionProgramming-like solutionGraphical solution
Uses simple languageUses structured statementsUses symbols
Easy to writeClose to actual codeEasy to visualise

8. Introduction to Python

Python is a high-level, general-purpose programming language known for its readable syntax and wide range of applications.

Python was created by Guido van Rossum and first released in the early 1990s.

Python is used in:

  • Education

  • Web development

  • Data analysis

  • Artificial intelligence

  • Automation

  • Scientific computing

  • Software development


9. Features of Python

Important features include:

1. Easy to Learn

Python has simple and readable syntax.

2. High-Level Language

Programmers can write instructions without dealing directly with low-level machine details.

3. Interpreted Execution

Python programs are commonly executed through an interpreter/virtual machine environment.

4. Portable

Python programs can generally run on different operating systems when a compatible Python environment is available.

5. Dynamically Typed

The programmer generally does not need to declare a variable's data type separately.

6. Object-Oriented

Python supports object-oriented programming.

7. Open Source

Python is developed as open-source software.

8. Large Library Support

Python provides a large standard library and a large ecosystem of third-party packages.

9. Case Sensitive

Python treats uppercase and lowercase letters as different.

For example:

name
Name
NAME

are different identifiers.


10. First Python Program

print("Hello World")

Output

Hello World

Explanation

print() is a built-in Python function used to display output.


11. Python Execution Modes

Python can be used mainly in two modes:

  1. Interactive Mode

  2. Script Mode


12. Interactive Mode

In interactive mode, Python commands are entered one at a time and executed immediately.

Example:

>>> 10 + 20
30

Another example:

>>> print("Hello")
Hello

Advantages

  • Quick testing.

  • Good for beginners.

  • Useful for experimenting with small expressions.


13. Script Mode

In script mode, Python instructions are saved in a file, usually with the extension:

.py

Example:

a = 10
b = 20
print(a + b)

Save as:

addition.py

Then execute the complete script.

Interactive vs Script Mode

InteractiveScript
Commands entered one by oneProgram saved in a file
Immediate resultComplete program can be executed
Good for experimentationGood for larger programs
Usually not saved automaticallySource code can be saved

14. Python Character Set

The Python character set includes the characters that can be used in Python programs.

It includes:

  • Letters: A–Z, a–z

  • Digits: 0–9

  • Special symbols

  • Whitespace characters

  • Operators

  • Punctuation characters

Examples:

A B C
a b c
0 1 2 3
+ - * / %
( ) [ ] { }
_ = , : ;

Python source code is Unicode-based, so it can represent many characters, although identifiers should follow Python's identifier rules.


15. Python Tokens

A token is the smallest meaningful unit of a Python program.

Important token categories include:

  1. Keywords

  2. Identifiers

  3. Literals

  4. Operators

  5. Punctuators


16. Keywords

Keywords are reserved words that have special meanings in Python.

Examples:

if
else
elif
for
while
break
continue
in
is
and
or
not
True
False
None
import
from
as
def
return
class

Important Rule

A keyword cannot normally be used as an identifier.

Incorrect:

class = 10

17. Identifiers

An identifier is a name given to a program element such as a variable, function or class.

Examples:

age = 17
student_name = "Rahul"
total_marks = 450

Here:

  • age

  • student_name

  • total_marks

are identifiers.

Rules for Identifiers

  1. Can contain letters.

  2. Can contain digits.

  3. Can contain underscore _.

  4. Cannot start with a digit.

  5. Cannot contain spaces.

  6. Cannot be a keyword.

  7. Python identifiers are case-sensitive.

Valid

name
student1
total_marks
_marks

Invalid

1student
student name
total-marks
class

18. Literals

A literal is a fixed value written directly in a program.

Examples:

25
3.14
"Hello"
True
False
None

Types of Literals

  • Numeric literals

  • String literals

  • Boolean literals

  • Special literal None


19. Operators

Operators are symbols or keywords used to perform operations.

Examples:

+
-
*
/
>
<
==
and
or
in
is

Operators are discussed in detail later.


20. Punctuators

Punctuators are symbols used to structure Python code.

Examples:

( )
[ ]
{ }
:
,
.
;

Examples:

print("Hello")
numbers = [10, 20, 30]

21. Variables

A variable is a name that refers to a value/object in a program.

Example:

age = 16

Here:

  • age = variable name

  • 16 = value

Another example:

name = "Amit"

22. Dynamic Typing

Python variables do not require a separate type declaration.

Example:

x = 10
print(x)

x = "Hello"
print(x)

The same variable name can refer to objects of different types at different times.


23. L-Value and R-Value

Consider:

x = 25

The variable x appears on the left side of the assignment.

It is the l-value because it identifies the destination/target of the assignment.

25 is the r-value because it provides the value being assigned.

l-value        r-value
   ↓              ↓
   x       =      25

Another Example

total = price + tax

total → l-value
price + tax → r-value/expression value


24. Comments

Comments are explanatory notes in a program that are ignored by Python during normal execution.

Single-Line Comment

Use #.

# This program calculates area
area = 10 * 5
print(area)

Multi-Line Documentation/String

Python does not have a separate multiline comment syntax. Triple-quoted strings can be used as multiline string literals and are commonly used for documentation, especially as docstrings.

"""
This is a multiline string.
It can document a program or function.
"""

Why Use Comments?

  • Improve readability.

  • Explain logic.

  • Help maintenance.

  • Make programs easier to understand.


25. Python Data Types

A data type specifies the kind of value represented by an object.

Important Class XI data types:

Data Types
│
├── Number
│   ├── int
│   ├── float
│   └── complex
│
├── Boolean
│
├── Sequence
│   ├── str
│   ├── list
│   └── tuple
│
├── None
│
└── Mapping
    └── dict

26. Integer – int

Integers are whole numbers without a decimal part.

Examples:

10
-25
0
500

Example:

age = 17

27. Floating-Point – float

Floating-point numbers contain a decimal point or represent real numbers using floating-point notation.

Examples:

3.14
10.5
-2.75

Example:

temperature = 36.5

28. Complex Numbers

A complex number contains a real part and an imaginary part.

Python uses j for the imaginary part.

Example:

z = 3 + 4j

Here:

  • Real part = 3

  • Imaginary part = 4

Access them using:

z.real
z.imag

29. Boolean Data Type

Boolean values represent truth values:

True
False

Example:

passed = True

Boolean values are commonly produced by comparisons.

10 > 5

Output:

True

30. String – str

A string is a sequence of characters enclosed in quotes.

Examples:

"Hello"
'Python'
"123"

Important:

"123"

is a string, whereas:

123

is an integer.


31. List

A list is an ordered, mutable collection.

Example:

marks = [85, 90, 78, 92]

Lists can contain different data types:

data = [10, "Hello", 3.5, True]

32. Tuple

A tuple is an ordered, immutable collection.

Example:

numbers = (10, 20, 30)

Unlike lists, tuple elements cannot normally be changed after creation.


33. Dictionary

A dictionary stores data in key-value pairs.

Example:

student = {
    "name": "Amit",
    "age": 17,
    "marks": 88
}

Here:

"name"  → key
"Amit"  → value

34. None

None represents the absence of a value.

Example:

result = None

It is different from:

0
""
False

35. Mutable and Immutable Data Types

Mutable

A mutable object can be changed after it is created.

Examples:

  • list

  • dictionary

Immutable

An immutable object cannot be changed after it is created.

Common examples:

  • int

  • float

  • complex

  • bool

  • str

  • tuple

Example

numbers = [10, 20, 30]
numbers[0] = 100

The list changes.

But:

text = "Hello"

Individual characters of the string cannot be changed directly.

Comparison

MutableImmutable
Can be modified after creationCannot be modified after creation
listint
dictionaryfloat

string

tuple

bool

36. Operators in Python

Important operator categories:

  1. Arithmetic

  2. Relational

  3. Logical

  4. Assignment

  5. Augmented assignment

  6. Identity

  7. Membership


37. Arithmetic Operators

OperatorMeaningExample
+Addition10 + 3
-Subtraction10 - 3
*Multiplication10 * 3
/True division10 / 3
//Floor division10 // 3
%Modulus/remainder10 % 3
**Exponentiation2 ** 3

Example

a = 10
b = 3

print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)

38. Relational Operators

Relational/comparison operators compare values.

OperatorMeaning
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal
==Equal to
!=Not equal to

Example:

a = 10
b = 20

print(a < b)

Output:

True

39. Logical Operators

Python has three main logical operators:

  • and

  • or

  • not

AND

True only when both conditions are true.

age >= 18 and citizen == True

OR

True when at least one condition is true.

maths > 80 or science > 80

NOT

Reverses a Boolean value.

not True

Output:

False

40. Assignment Operators

The basic assignment operator is:

=

Example:

x = 10

Other assignment operators include:

= 
+=
-=
*=
/=
%=
**=
//=

41. Augmented Assignment Operators

Augmented assignment combines an operation with assignment.

Instead of:

x = x + 5

we can write:

x += 5

Similarly:

x -= 2
x *= 3
x /= 4
x %= 5
x **= 2
x //= 2

Example

x = 10
x += 5
print(x)

Output:

15

42. Identity Operators

Identity operators are:

is
is not

They test whether two references refer to the same object.

Example:

a = [1, 2]
b = a

print(a is b)

Output:

True

Important

is should not normally be used to compare ordinary values for equality.

Use:

==

for value comparison.

Use:

is

for object identity.


43. Membership Operators

Membership operators are:

in
not in

They test whether an item occurs in a sequence or collection.

Example:

numbers = [10, 20, 30]

print(20 in numbers)

Output:

True

Example:

print(50 not in numbers)

Output:

True

44. Expressions

An expression is a combination of values, variables, operators and function calls that produces a value.

Examples:

10 + 20
a * b + 5
marks >= 40

45. Statements

A statement is an instruction that performs an action.

Examples:

x = 10
print(x)
if x > 5:
    print("Large")

Expression vs Statement

An expression produces a value.

A statement performs an action.


46. Operator Precedence

When an expression contains multiple operators, Python follows precedence rules.

A simplified order is:

1. Parentheses                 ()
2. Exponentiation              **
3. Unary +, -                  +x, -x
4. *, /, //, %
5. +, -
6. Comparisons                 < > <= >= == !=
7. not
8. and
9. or

Example

result = 10 + 5 * 2

Multiplication is performed first:

5 × 2 = 10
10 + 10 = 20

Answer:

20

Using Parentheses

result = (10 + 5) * 2

Output:

30

Golden Rule

When in doubt, use parentheses to make the intended order clear.


47. Type Conversion

Type conversion means converting a value from one data type to another.

There are two important types:

  1. Implicit conversion

  2. Explicit conversion


48. Implicit Type Conversion

Python may automatically convert a value to a compatible type during an operation.

Example:

a = 10
b = 2.5

c = a + b
print(c)
print(type(c))

Output:

12.5
<class 'float'>

The integer participates in the operation as a floating-point value.


49. Explicit Type Conversion

The programmer explicitly converts a value.

Common conversion functions:

int()
float()
str()
bool()
list()
tuple()
dict()

Example:

x = "25"
y = int(x)

print(y + 5)

Output:

30

50. Input from Console

The input() function accepts input from the user.

Example:

name = input("Enter your name: ")
print("Hello", name)

Important Rule

input() normally returns a string.

Therefore, for numeric input, conversion is often required.

age = int(input("Enter age: "))

51. Output

The print() function displays output.

Example:

name = "Amit"
age = 17

print(name)
print(age)

Multiple values:

print("Name:", name, "Age:", age)

52. A Complete Input/Output Program

name = input("Enter your name: ")
marks = float(input("Enter marks: "))

print("Student:", name)
print("Marks:", marks)

Sample Output

Enter your name: Rahul
Enter marks: 87.5
Student: Rahul
Marks: 87.5

53. Errors in Python

An error is a problem that prevents a program from producing the intended result or from executing successfully.

Important types:

  1. Syntax error

  2. Runtime error

  3. Logical error


54. Syntax Error

A syntax error occurs when Python code violates the language's grammar rules.

Example:

if x > 10
    print(x)

The colon : is missing.

Correct:

if x > 10:
    print(x)

55. Runtime Error

A runtime error occurs while the program is running.

Example:

a = 10
b = 0
print(a / b)

This causes:

ZeroDivisionError

Another example:

number = int("abc")

This can cause:

ValueError

56. Logical Error

A logical error occurs when the program runs but produces the wrong result because the logic is incorrect.

Example:

length = 10
breadth = 5

area = length + breadth

The program runs, but the correct formula is:

area = length * breadth

Error Comparison

ErrorProgram Runs?Main Problem
SyntaxUsually noInvalid Python syntax
RuntimeStarts but fails during executionProblem occurs while running
LogicalYesWrong logic/result

57. Flow of Control

The flow of control describes the order in which program statements are executed.

Three basic forms are:

  1. Sequential

  2. Conditional

  3. Iterative

             FLOW OF CONTROL
                    │
       ┌────────────┼─────────────┐
       ↓            ↓             ↓
   Sequential   Conditional    Iterative
                    │
                 if/else

58. Indentation in Python

Python uses indentation to define blocks of code.

Example:

if age >= 18:
    print("Adult")

The indented statement belongs to the if block.

Important

Do not mix tabs and spaces carelessly.

Use consistent indentation.


59. Sequential Flow

In sequential flow, statements execute from top to bottom.

Example:

a = 10
b = 20
c = a + b
print(c)

Execution:

Statement 1
    ↓
Statement 2
    ↓
Statement 3
    ↓
Statement 4

60. Conditional Flow

Conditional statements allow a program to make decisions.

Python provides:

  1. if

  2. if-else

  3. if-elif-else


61. if Statement

Syntax:

if condition:
    statement

Example:

age = 20

if age >= 18:
    print("Eligible")

Flowchart

          ┌─────────┐
          │  Start  │
          └────┬────┘
               ↓
        ┌─────────────┐
        │ Read age    │
        └──────┬──────┘
               ↓
          ┌──────────┐
          │ age >=18?│
          └────┬─────┘
             Yes│
                ↓
        ┌─────────────┐
        │ Print Adult  │
        └──────┬──────┘
               ↓
             Stop

62. if-else Statement

Syntax:

if condition:
    statement1
else:
    statement2

Example:

number = int(input("Enter number: "))

if number % 2 == 0:
    print("Even")
else:
    print("Odd")

63. if-elif-else

Used when multiple conditions need to be checked.

Syntax:

if condition1:
    statement1
elif condition2:
    statement2
else:
    statement3

Example:

marks = int(input("Enter marks: "))

if marks >= 90:
    print("A")
elif marks >= 75:
    print("B")
elif marks >= 60:
    print("C")
else:
    print("D")

64. Program: Absolute Value

The absolute value of a number is its non-negative magnitude.

n = float(input("Enter a number: "))

if n < 0:
    n = -n

print("Absolute value =", n)

Example

Input:

-25

Output:

Absolute value = 25

65. Program: Sort Three Numbers

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a > b:
    a, b = b, a

if b > c:
    b, c = c, b

if a > b:
    a, b = b, a

print("Ascending order:", a, b, c)

Sample Output

Enter first number: 30
Enter second number: 10
Enter third number: 20
Ascending order: 10 20 30

66. Program: Divisibility

Check whether a number is divisible by 5.

n = int(input("Enter a number: "))

if n % 5 == 0:
    print("Divisible by 5")
else:
    print("Not divisible by 5")

67. Iterative Statements

An iterative statement repeats a block of code.

Python mainly uses:

  • for

  • while


68. for Loop

A for loop is used to iterate over items of an iterable such as a string, list, tuple or range.

Example:

for i in range(1, 6):
    print(i)

Output:

1
2
3
4
5

69. range() Function

range() generates a sequence of numbers.

Forms

range(stop)
range(start, stop)
range(start, stop, step)

Example 1

range(5)

Produces:

0 1 2 3 4

Example 2

range(2, 6)

Produces:

2 3 4 5

Example 3

range(2, 10, 2)

Produces:

2 4 6 8

Important Rule

The stop value is not included.


70. while Loop

A while loop repeats as long as its condition remains true.

Syntax:

while condition:
    statements

Example:

i = 1

while i <= 5:
    print(i)
    i += 1

Output:

1
2
3
4
5

Flow

        ┌───────────┐
        │   Start   │
        └─────┬─────┘
              ↓
        ┌───────────┐
        │ condition │
        └─────┬─────┘
           Yes│
              ↓
        ┌───────────┐
        │   Body    │
        └─────┬─────┘
              │
              └───────→ Condition
                  
           No ↓
        ┌───────────┐
        │   Stop    │
        └───────────┘

71. for vs while

forwhile
Commonly used when iterating over a known iterable/rangeCommonly used when repetition depends on a condition
Works naturally with sequencesWorks with a condition
Often used for countingOften used for condition-controlled repetition

72. break Statement

break immediately terminates the nearest enclosing loop.

Example:

for i in range(1, 10):
    if i == 5:
        break
    print(i)

Output:

1
2
3
4

73. continue Statement

continue skips the remaining statements of the current iteration and proceeds to the next iteration.

Example:

for i in range(1, 6):
    if i == 3:
        continue
    print(i)

Output:

1
2
4
5

74. Nested Loops

A loop inside another loop is called a nested loop.

Example:

for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)

Structure

Outer Loop
│
├── Inner Loop
├── Inner Loop
└── Inner Loop

75. Program: Star Pattern

for i in range(1, 6):
    print("*" * i)

Output:

*
**
***
****
*****

76. Program: Sum of First N Natural Numbers

n = int(input("Enter n: "))

total = 0

for i in range(1, n + 1):
    total += i

print("Sum =", total)

For n = 5:

Sum = 15

77. Program: Factorial

Factorial of n:

n! = n × (n-1) × ... × 2 × 1

Example:

5! = 5 × 4 × 3 × 2 × 1
   = 120

Program

n = int(input("Enter a positive integer: "))

fact = 1

for i in range(1, n + 1):
    fact *= i

print("Factorial =", fact)

78. Strings

A string is an ordered sequence of characters.

Examples:

name = "Rajesh"
city = 'Lucknow'

Strings can be indexed and sliced.


79. String Indexing

Consider:

text = "PYTHON"

Indexes:

 P   Y   T   H   O   N
 0   1   2   3   4   5

Negative indexes:

 P    Y    T    H    O    N
-6   -5   -4   -3   -2   -1

Example:

print(text[0])

Output:

P

80. String Slicing

Syntax:

string[start:stop:step]

Example:

text = "PYTHON"

print(text[1:4])

Output:

YTH

The stop index is excluded.

More Examples

text[:3]

Output:

PYT
text[2:]

Output:

THON
text[::-1]

Output:

NOHTYP

81. String Concatenation

Joining strings using + is called concatenation.

first = "Good"
second = "Morning"

print(first + " " + second)

Output:

Good Morning

82. String Repetition

Use *.

print("Hi " * 3)

Output:

Hi Hi Hi

83. String Membership

Use:

in
not in

Example:

text = "computer"

print("put" in text)

Output:

True

84. Traversing a String

Traversing means visiting characters one by one.

text = "Python"

for ch in text:
    print(ch)

Output:

P
y
t
h
o
n

85. Important String Functions and Methods

len()

Returns the number of characters.

text = "Python"
print(len(text))

Output:

6

capitalize()

Converts the first character to uppercase and the remaining characters to lowercase.

"python programming".capitalize()

Output:

Python programming

title()

Converts the first character of each word to uppercase.

"python programming".title()

Output:

Python Programming

lower()

Converts letters to lowercase.

"PYTHON".lower()

Output:

python

upper()

Converts letters to uppercase.

"python".upper()

Output:

PYTHON

count()

Counts occurrences.

"banana".count("a")

Output:

3

find()

Returns the lowest index where the substring is found; returns -1 if not found.

"computer".find("put")

Output:

3

index()

Returns the index of the first occurrence.

"computer".index("put")

Output:

3

Unlike find(), index() raises an exception if the substring is not found.


endswith()

Checks whether a string ends with a specified suffix.

"hello.py".endswith(".py")

Output:

True

startswith()

Checks whether a string starts with a specified prefix.

"Python".startswith("Py")

Output:

True

isalnum()

Returns True if all characters are alphanumeric and the string is not empty.

"Python123".isalnum()

Output:

True

isalpha()

Checks whether all characters are alphabetic.

"Python".isalpha()

Output:

True

isdigit()

Checks whether all characters are digits.

"12345".isdigit()

Output:

True

islower()

Checks whether all cased characters are lowercase.

"hello".islower()

Output:

True

isupper()

Checks whether all cased characters are uppercase.

"HELLO".isupper()

Output:

True

isspace()

Checks whether the string contains only whitespace characters and is not empty.

"   ".isspace()

Output:

True

lstrip()

Removes leading whitespace by default.

"   Hello".lstrip()

Output:

Hello

rstrip()

Removes trailing whitespace by default.

"Hello   ".rstrip()

Output:

Hello

strip()

Removes leading and trailing whitespace by default.

"   Hello   ".strip()

Output:

Hello

replace()

Replaces occurrences of one substring with another.

text = "I like Java"
print(text.replace("Java", "Python"))

Output:

I like Python

join()

Joins strings using a separator.

words = ["I", "love", "Python"]

print(" ".join(words))

Output:

I love Python

partition()

Splits a string into a 3-part tuple:

(before separator, separator, after separator)

Example:

text = "name=Rajesh"

print(text.partition("="))

Output:

('name', '=', 'Rajesh')

split()

Splits a string into a list.

text = "Python is easy"

print(text.split())

Output:

['Python', 'is', 'easy']

86. String Methods Quick Table

MethodPurpose
len()Length
capitalize()Capitalise first character
title()Capitalise each word
lower()Lowercase
upper()Uppercase
count()Count occurrences
find()Find position; -1 if absent
index()Find position; raises error if absent
endswith()Check ending
startswith()Check beginning
isalnum()Check alphanumeric
isalpha()Check alphabetic
isdigit()Check digits
islower()Check lowercase
isupper()Check uppercase
isspace()Check whitespace
lstrip()Remove leading whitespace
rstrip()Remove trailing whitespace
strip()Remove leading/trailing whitespace
replace()Replace text
join()Join strings
partition()Split around first separator into 3 parts
split()Split into list

87. Lists

A list is an ordered, mutable collection.

Example:

marks = [80, 75, 92, 88]

A list can contain mixed data:

data = [10, "Python", 3.5, True]

88. List Indexing

numbers = [10, 20, 30, 40]
Value:  10   20   30   40
Index:   0    1    2    3

Negative indexes:

Index:  -4   -3   -2   -1
Value:  10   20   30   40

89. List Slicing

numbers = [10, 20, 30, 40, 50]

print(numbers[1:4])

Output:

[20, 30, 40]

90. List Concatenation

a = [1, 2]
b = [3, 4]

print(a + b)

Output:

[1, 2, 3, 4]

91. List Repetition

print([1, 2] * 3)

Output:

[1, 2, 1, 2, 1, 2]

92. List Membership

numbers = [10, 20, 30]

print(20 in numbers)

Output:

True

93. Traversing a List

numbers = [10, 20, 30]

for n in numbers:
    print(n)

94. List Functions and Methods

len()

len([10, 20, 30])

Output:

3

list()

Creates a list from an iterable.

list("ABC")

Output:

['A', 'B', 'C']

append()

Adds one item at the end.

numbers = [10, 20]
numbers.append(30)
print(numbers)

Output:

[10, 20, 30]

extend()

Adds multiple items from an iterable.

numbers = [10, 20]
numbers.extend([30, 40])

Result:

[10, 20, 30, 40]

insert()

Inserts an item at a specified position.

numbers = [10, 30]
numbers.insert(1, 20)

Result:

[10, 20, 30]

count()

Counts occurrences.

[10, 20, 10, 30].count(10)

Output:

2

index()

Returns the first position of an item.

[10, 20, 30].index(20)

Output:

1

remove()

Removes the first matching value.

numbers = [10, 20, 30]
numbers.remove(20)

Result:

[10, 30]

pop()

Removes and returns an item.

numbers = [10, 20, 30]
x = numbers.pop()

Now:

x = 30
numbers = [10, 20]

reverse()

Reverses the list in place.

numbers = [1, 2, 3]
numbers.reverse()

Result:

[3, 2, 1]

sort()

Sorts a list in place.

numbers = [30, 10, 20]
numbers.sort()

Result:

[10, 20, 30]

sorted()

Returns a new sorted list.

numbers = [30, 10, 20]
new_list = sorted(numbers)

Original:

[30, 10, 20]

New list:

[10, 20, 30]

min()

Returns the smallest item.

min([10, 5, 20])

Output:

5

max()

Returns the largest item.

max([10, 5, 20])

Output:

20

sum()

Returns the sum of numeric items.

sum([10, 20, 30])

Output:

60

95. Important List Difference

append() vs extend()

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

Result:

[1, 2, [3, 4]]

But:

a = [1, 2]
a.extend([3, 4])

Result:

[1, 2, 3, 4]

96. Nested Lists

A list containing another list is called a nested list.

Example:

matrix = [
    [1, 2],
    [3, 4]
]

Access:

print(matrix[0][1])

Output:

2

97. Program: Maximum, Minimum and Mean of a List

numbers = [10, 20, 30, 40, 50]

print("Maximum =", max(numbers))
print("Minimum =", min(numbers))
print("Mean =", sum(numbers) / len(numbers))

Output:

Maximum = 50
Minimum = 10
Mean = 30.0

98. Program: Linear Search in a List

numbers = [10, 20, 30, 40, 50]

key = int(input("Enter number to search: "))

found = False

for n in numbers:
    if n == key:
        found = True
        break

if found:
    print("Element found")
else:
    print("Element not found")

99. Program: Frequency of Elements in a List

numbers = [10, 20, 10, 30, 20, 10]

for item in numbers:
    if numbers.index(item) == numbers.index(item):
        print(item, "=", numbers.count(item))

The above may print duplicate frequency lines. A cleaner beginner-friendly solution is:

numbers = [10, 20, 10, 30, 20, 10]

frequency = {}

for item in numbers:
    frequency[item] = frequency.get(item, 0) + 1

print(frequency)

Output:

{10: 3, 20: 2, 30: 1}

100. Tuples

A tuple is an ordered and immutable collection.

Example:

numbers = (10, 20, 30)

A single-item tuple requires a comma:

x = (10,)

Without the comma:

x = (10)

x is simply an integer expression, not a tuple.


101. Tuple Indexing

numbers = (10, 20, 30, 40)
10   20   30   40
0    1    2    3

102. Tuple Slicing

numbers = (10, 20, 30, 40, 50)

print(numbers[1:4])

Output:

(20, 30, 40)

103. Tuple Operations

Concatenation

(1, 2) + (3, 4)

Result:

(1, 2, 3, 4)

Repetition

(1, 2) * 2

Result:

(1, 2, 1, 2)

Membership

20 in (10, 20, 30)

Result:

True

104. Tuple Functions/Methods

Function/MethodPurpose
len()Number of elements
tuple()Creates tuple
count()Counts an item
index()Finds position
sorted()Returns sorted list
min()Minimum
max()Maximum
sum()Sum

Important

sorted(tuple) returns a list, not a tuple.

Example:

t = (30, 10, 20)
print(sorted(t))

Output:

[10, 20, 30]

105. Tuple Assignment

Python allows multiple assignment.

a, b = 10, 20

Swapping:

a, b = b, a

Example:

x = 10
y = 20

x, y = y, x

print(x, y)

Output:

20 10

106. Nested Tuple

A tuple can contain another tuple.

data = ((1, 2), (3, 4))

Access:

print(data[1][0])

Output:

3

107. Program: Tuple Maximum, Minimum and Mean

numbers = (10, 20, 30, 40, 50)

print("Maximum =", max(numbers))
print("Minimum =", min(numbers))
print("Mean =", sum(numbers) / len(numbers))

108. Linear Search in a Tuple

numbers = (10, 20, 30, 40, 50)

key = int(input("Enter number: "))

if key in numbers:
    print("Found")
else:
    print("Not Found")

109. Dictionary

A dictionary is a mutable mapping that stores data as key-value pairs.

Example:

student = {
    "name": "Amit",
    "class": 11,
    "marks": 90
}

Structure:

Key        Value
 │           │
"name"  →  "Amit"
"class" →  11
"marks" →  90

110. Accessing Dictionary Items

Use the key.

student = {
    "name": "Amit",
    "marks": 90
}

print(student["name"])

Output:

Amit

Using get()

print(student.get("name"))

111. Difference Between [] and get()

student["age"]

If "age" does not exist, a KeyError occurs.

But:

student.get("age")

returns None by default if the key is absent.

You can provide a default:

student.get("age", 0)

112. Adding a New Dictionary Item

student = {
    "name": "Amit",
    "marks": 90
}

student["age"] = 17

Now:

{
"name": "Amit",
"marks": 90,
"age": 17
}

113. Modifying a Dictionary Item

student["marks"] = 95

The existing value is replaced.


114. Traversing a Dictionary

Keys

for key in student:
    print(key)

Values

for value in student.values():
    print(value)

Key and Value

for key, value in student.items():
    print(key, value)

115. Dictionary Functions and Methods

len()

Returns the number of key-value pairs.

len({"a": 1, "b": 2})

Output:

2

dict()

Creates a dictionary.

d = dict()

keys()

Returns a view of dictionary keys.

student.keys()

values()

Returns a view of dictionary values.

student.values()

items()

Returns key-value pairs.

student.items()

get()

Returns the value associated with a key.

student.get("name")

update()

Adds or changes key-value pairs.

student.update({"marks": 95})

del

Deletes an item.

del student["marks"]

clear()

Removes all items.

student.clear()

fromkeys()

Creates a dictionary from given keys.

keys = ["a", "b", "c"]

d = dict.fromkeys(keys, 0)

print(d)

Output:

{'a': 0, 'b': 0, 'c': 0}

copy()

Creates a shallow copy.

d2 = student.copy()

pop()

Removes and returns the value for a specified key.

student.pop("age")

popitem()

Removes and returns the last inserted key-value pair in modern Python.

student.popitem()

setdefault()

Returns the value of a key. If the key does not exist, it inserts the key with the supplied default value.

student.setdefault("city", "Lucknow")

max()

Returns the maximum key/value depending on how it is used.

For a dictionary:

max(student)

normally compares keys.


min()

Returns the minimum key.


sorted()

Returns a sorted list of dictionary keys by default.

sorted(student)

116. Program: Character Frequency Using Dictionary

Problem:

Count how many times each character occurs in a string.

text = input("Enter a string: ")

frequency = {}

for ch in text:
    frequency[ch] = frequency.get(ch, 0) + 1

print(frequency)

Sample Input

banana

Output

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

117. Program: Employee Dictionary

employees = {
    "Amit": 45000,
    "Ravi": 52000,
    "Neha": 48000
}

name = input("Enter employee name: ")

if name in employees:
    print("Salary =", employees[name])
else:
    print("Employee not found")

118. String vs List vs Tuple vs Dictionary

FeatureStringListTupleDictionary
OrderedYesYesYesInsertion order is preserved in modern Python
MutableNoYesNoYes
AccessIndexIndexIndexKey
Duplicate valuesYesYesYesKeys must be unique
Example"Python"[1,2,3](1,2,3){"a":1}

119. Introduction to Python Modules

A module is a Python file containing definitions and code that can be imported and reused.

Python provides many standard-library modules.

Examples:

  • math

  • random

  • statistics


120. Importing a Module

Syntax:

import module_name

Example:

import math

print(math.sqrt(25))

Output:

5.0

121. Importing Specific Names Using from

Syntax:

from module import name

Example:

from math import sqrt

print(sqrt(25))

Output:

5.0

Multiple names:

from math import pi, sqrt

Difference

import math

requires:

math.sqrt(25)

Whereas:

from math import sqrt

allows:

sqrt(25)

122. Math Module

The math module provides mathematical functions and constants.

Important syllabus functions/constants:

  • pi

  • e

  • sqrt()

  • ceil()

  • floor()

  • pow()

  • fabs()

  • sin()

  • cos()

  • tan()


123. math.pi

Represents the mathematical constant π.

import math

print(math.pi)

124. math.e

Represents Euler's number.

import math

print(math.e)

125. sqrt()

Returns the square root.

import math

print(math.sqrt(49))

Output:

7.0

126. ceil()

Returns the smallest integer greater than or equal to the given number.

import math

print(math.ceil(4.2))

Output:

5

127. floor()

Returns the largest integer less than or equal to the given number.

import math

print(math.floor(4.8))

Output:

4

128. pow()

Returns a number raised to a power.

import math

print(math.pow(2, 3))

Output:

8.0

129. fabs()

Returns the absolute value as a floating-point number.

import math

print(math.fabs(-25))

Output:

25.0

130. sin(), cos(), tan()

These trigonometric functions use radians.

Example:

import math

print(math.sin(math.pi / 2))
print(math.cos(0))
print(math.tan(0))

Output is approximately:

1.0
1.0
0.0

131. Random Module

The random module provides functions for generating pseudo-random values.

Important functions:

  • random()

  • randint()

  • randrange()


132. random()

Returns a floating-point number in the range:

0.0 <= value < 1.0

Example:

import random

print(random.random())

Possible output:

0.583241

The exact value changes from run to run.


133. randint()

Returns a random integer between the specified endpoints, including both endpoints.

import random

print(random.randint(1, 10))

Possible output:

7

134. randrange()

Returns a randomly selected value from a range.

Example:

import random

print(random.randrange(1, 10))

Possible values:

1 to 9

The stop value 10 is excluded.

With a step:

random.randrange(2, 11, 2)

Possible values:

2, 4, 6, 8, 10

135. Statistics Module

The statistics module provides common statistical functions.

Important functions:

  • mean()

  • median()

  • mode()


136. mean()

Mean is the arithmetic average.

from statistics import mean

data = [10, 20, 30]

print(mean(data))

Output:

20

137. median()

The median is the middle value when data is arranged in order.

from statistics import median

data = [10, 20, 30, 40, 50]

print(median(data))

Output:

30

For an even number of values, the median is the average of the two middle values.


138. mode()

Mode is the most frequently occurring value.

from statistics import mode

data = [10, 20, 20, 30, 20]

print(mode(data))

Output:

20

139. Complete Module Example

import math
import random
from statistics import mean, median, mode

numbers = [10, 20, 20, 30, 40]

print("Square root:", math.sqrt(25))
print("Random number:", random.randint(1, 10))
print("Mean:", mean(numbers))
print("Median:", median(numbers))
print("Mode:", mode(numbers))

140. Common Python Mistakes

Mistake 1: Forgetting Colon

Wrong:

if x > 10

Correct:

if x > 10:

Mistake 2: Wrong Indentation

Wrong:

if x > 10:
print(x)

Correct:

if x > 10:
    print(x)

Mistake 3: Forgetting Conversion

Wrong:

a = input("Enter number: ")
b = input("Enter number: ")

print(a + b)

If inputs are 10 and 20, result may be:

1020

Correct:

a = int(input("Enter number: "))
b = int(input("Enter number: "))

print(a + b)

Output:

30

Mistake 4: Confusing = and ==

=   → Assignment
==  → Comparison

Example:

x = 10

But:

x == 10

checks equality.


Mistake 5: Using is for Normal Value Comparison

Prefer:

x == 10

for value comparison.

is checks object identity.


141. Important Programs for Class XI

Students should practise at least the following:

  1. Hello World

  2. Addition of two numbers

  3. Area of rectangle

  4. Simple interest

  5. Absolute value

  6. Largest of two numbers

  7. Largest of three numbers

  8. Sorting three numbers

  9. Checking divisibility

  10. Even/odd

  11. Positive/negative

  12. Sum of natural numbers

  13. Factorial

  14. Multiplication table

  15. Star patterns

  16. Reverse a string

  17. Count characters

  18. Search an element in a list

  19. Maximum/minimum of a list

  20. Mean of list values

  21. Character frequency using dictionary

  22. Employee salary dictionary

  23. Tuple search

  24. Tuple maximum/minimum

  25. Programs using math module

  26. Programs using random module

  27. Programs using statistics module


142. Practice Program: Even Numbers

for i in range(2, 21, 2):
    print(i)

Output:

2
4
6
8
10
12
14
16
18
20

143. Practice Program: Multiplication Table

n = int(input("Enter number: "))

for i in range(1, 11):
    print(n, "x", i, "=", n * i)

144. Practice Program: Reverse a String

text = input("Enter a string: ")

print("Reverse =", text[::-1])

145. Practice Program: Count Vowels

text = input("Enter a string: ")

count = 0

for ch in text.lower():
    if ch in "aeiou":
        count += 1

print("Number of vowels =", count)

146. Practice Program: Maximum in a List Without max()

numbers = [25, 10, 50, 30, 40]

largest = numbers[0]

for n in numbers:
    if n > largest:
        largest = n

print("Maximum =", largest)

147. Practice Program: Minimum in a List Without min()

numbers = [25, 10, 50, 30, 40]

smallest = numbers[0]

for n in numbers:
    if n < smallest:
        smallest = n

print("Minimum =", smallest)

148. Practice Program: Linear Search

numbers = [10, 20, 30, 40, 50]

key = int(input("Enter search value: "))

position = -1

for i in range(len(numbers)):
    if numbers[i] == key:
        position = i
        break

if position != -1:
    print("Found at index", position)
else:
    print("Not found")

149. Practice Program: Frequency of Elements

numbers = [1, 2, 2, 3, 1, 2, 4]

frequency = {}

for n in numbers:
    frequency[n] = frequency.get(n, 0) + 1

for key, value in frequency.items():
    print(key, ":", value)

Possible output:

1 : 2
2 : 3
3 : 1
4 : 1

150. Practice Program: Mean Using statistics

from statistics import mean

numbers = [10, 20, 30, 40, 50]

print("Mean =", mean(numbers))

151. Important Comparison Table

String vs List

StringList
ImmutableMutable
CharactersAny objects
Written in quotesWritten in square brackets
"Python"[1, 2, 3]

List vs Tuple

ListTuple
MutableImmutable
[]()
More suitable when data changesSuitable for fixed collections

List vs Dictionary

ListDictionary
Access by indexAccess by key
Ordered sequenceMapping of keys to values
[10,20,30]{"a":10}

152. Important Exam Questions

Very Short Answer

  1. What is an algorithm?

  2. What is decomposition?

  3. What is a flowchart?

  4. What is pseudocode?

  5. What is Python?

  6. What is an identifier?

  7. What is a keyword?

  8. What is a literal?

  9. What is a variable?

  10. What is an l-value?

  11. What is an r-value?

  12. What is a comment?

  13. What is a mutable data type?

  14. What is an immutable data type?

  15. What is an expression?

  16. What is a statement?

  17. What is type conversion?

  18. What is indentation?

  19. What is a loop?

  20. What is a Python module?


153. Short Answer Questions

Q1. What is decomposition?

Answer: Decomposition is the process of breaking a complex problem into smaller and manageable sub-problems.

Q2. What is the difference between interactive and script mode?

Answer: Interactive mode executes commands one at a time, while script mode stores Python instructions in a .py file that can be executed as a program.

Q3. What is the difference between list and tuple?

Answer: A list is mutable and is written using square brackets, whereas a tuple is immutable and is generally written using parentheses.

Q4. What is the difference between == and is?

Answer: == compares values for equality, while is checks whether two references refer to the same object.

Q5. What is the purpose of break?

Answer: break terminates the nearest enclosing loop immediately.

Q6. What is the purpose of continue?

Answer: continue skips the remaining statements of the current loop iteration and proceeds to the next iteration.

Q7. What does input() return?

Answer: input() returns the user's input as a string. Conversion is required when a numeric type is needed.


154. MCQs

1. Which of the following is a mutable data type?

A. String
B. Tuple
C. List
D. Integer

Answer: C. List

2. Which symbol is used for a comment?

A. //
B. #
C. /* */
D. --

Answer: B. #

3. Which operator checks object identity?

A. ==
B. =
C. is
D. in

Answer: C. is

4. Which operator checks membership?

A. is
B. in
C. ==
D. !=

Answer: B. in

5. Which function accepts input from the console?

A. print()
B. input()
C. read()
D. scan()

Answer: B. input()

6. What is the output of:

print(10 // 3)

A. 3
B. 3.33
C. 1
D. 30

Answer: A. 3

7. What does % return?

A. Quotient
B. Remainder
C. Power
D. Average

Answer: B. Remainder

8. Which loop is commonly used to iterate over a range?

A. if
B. for
C. try
D. switch

Answer: B. for

9. Which statement stops a loop?

A. continue
B. stop
C. break
D. exitloop

Answer: C. break

10. Which statement skips the current iteration?

A. break
B. continue
C. skiploop
D. passloop

Answer: B. continue

11. Which method adds one item to the end of a list?

A. add()
B. append()
C. insertEnd()
D. push()

Answer: B. append()

12. Which method removes and returns a list item?

A. pop()
B. delete()
C. removeall()
D. erase()

Answer: A. pop()

13. Which data structure stores key-value pairs?

A. List
B. Tuple
C. Dictionary
D. String

Answer: C. Dictionary

14. Which module contains sqrt()?

A. random
B. math
C. statistics
D. number

Answer: B. math

15. Which function returns a random integer including both endpoints?

A. random()
B. randint()
C. randrange()
D. randomint()

Answer: B. randint()


155. Fill in the Blanks

  1. A step-by-step solution to a problem is called an algorithm.

  2. A graphical representation of an algorithm is called a flowchart.

  3. Python source files normally use the extension .py.

  4. The symbol used for a single-line comment is #.

  5. A list is a mutable data type.

  6. A tuple is an immutable data type.

  7. A dictionary stores key-value pairs.

  8. The input() function normally returns a string.

  9. The break statement terminates a loop.

  10. The continue statement skips the current iteration.

  11. math.sqrt() calculates the square root.

  12. random.randint() returns a random integer.

  13. statistics.mean() calculates the arithmetic mean.


156. True or False

  1. Python is case-sensitive.
    True

  2. A list is immutable.
    False

  3. A tuple is immutable.
    True

  4. input() normally returns a string.
    True

  5. == is the assignment operator.
    False

  6. = is used for assignment.
    True

  7. break skips only the current iteration.
    False

  8. continue skips the current iteration.
    True

  9. Dictionary data is accessed using keys.
    True

  10. range(5) includes 5.
    False

  11. randint(1, 10) can return 10.
    True

  12. sorted() returns a new sorted list.
    True


157. Match the Following

Column AColumn B
1. append()a. Square root
2. sqrt()b. Add item to list
3. breakc. Remove/return list item
4. pop()d. Stop loop
5. mean()e. Arithmetic average

Answers

1 – b
2 – a
3 – d
4 – c
5 – e


158. Quick Revision Chart

                 PYTHON PROGRAMMING
                        │
        ┌───────────────┼────────────────┐
        ↓               ↓                ↓
   Problem Solving   Python Basics    Data Types
        │               │                │
 Algorithm          Tokens           Number
 Flowchart          Variables        Boolean
 Pseudocode         Comments         String
 Decomposition      I/O              List
                                      Tuple
                                      Dictionary
                        │
                        ↓
                    Operators
                        │
        ┌───────────────┼──────────────────┐
        ↓               ↓                  ↓
    Arithmetic      Relational          Logical
        ↓
 Assignment → Augmented → Identity → Membership
                        │
                        ↓
                 Flow of Control
                        │
           ┌────────────┼────────────┐
           ↓            ↓            ↓
       Sequential   Conditional   Iterative
                         │            │
                      if/else       for/while
                                     │
                               break/continue
                        │
                        ↓
                    Collections
               ┌────────┼────────┐
               ↓        ↓        ↓
             String    List     Tuple
                                  ↓
                             Dictionary
                        │
                        ↓
                      Modules
               ┌────────┼────────┐
               ↓        ↓        ↓
             math     random  statistics

159. Python Operator Quick Revision

ARITHMETIC
+  -  *  /  //  %  **

RELATIONAL
>  <  >=  <=  ==  !=

LOGICAL
and  or  not

ASSIGNMENT
=

AUGMENTED
+=  -=  *=  /=  //=  %=  **=

IDENTITY
is  is not

MEMBERSHIP
in  not in

160. Collection Quick Revision

STRING
"Python"
Immutable
Index based

LIST
[10, 20, 30]
Mutable
Index based

TUPLE
(10, 20, 30)
Immutable
Index based

DICTIONARY
{"name": "Amit", "age": 17}
Mutable
Key based

161. Most Important Python Methods

String

capitalize()
title()
lower()
upper()
count()
find()
index()
endswith()
startswith()
isalnum()
isalpha()
isdigit()
islower()
isupper()
isspace()
lstrip()
rstrip()
strip()
replace()
join()
partition()
split()

List

append()
extend()
insert()
count()
index()
remove()
pop()
reverse()
sort()

Tuple

count()
index()

Dictionary

keys()
values()
items()
get()
update()
del
clear()
fromkeys()
copy()
pop()
popitem()
setdefault()

162. Important Built-in Functions

Students should remember:

len()
list()
tuple()
dict()
min()
max()
sum()
sorted()

163. Important Modules

math
│
├── pi
├── e
├── sqrt()
├── ceil()
├── floor()
├── pow()
├── fabs()
├── sin()
├── cos()
└── tan()

random
│
├── random()
├── randint()
└── randrange()

statistics
│
├── mean()
├── median()
└── mode()

164. Golden Rules for Class XI

Problem Solving

Analyse → Algorithm → Flowchart/Pseudocode → Code → Test → Debug

Python

Python is case-sensitive.

Input

input() → string

Comparison

== → value equality

is → object identity

Loops

break → terminate loop

continue → skip current iteration

Range

stop value is excluded

List

Mutable

Tuple

Immutable

Dictionary

Key → Value

String

Immutable sequence of characters

Modules

import → use module


165. Final Exam Revision

Before the examination, make sure you can:

✓ Write algorithms and pseudocode.
✓ Draw basic flowcharts.
✓ Explain decomposition.
✓ Write Python programs in interactive and script mode.
✓ Identify Python tokens.
✓ Follow identifier rules.
✓ Explain l-value and r-value.
✓ Identify Python data types.
✓ Distinguish mutable and immutable types.
✓ Use all major operators.
✓ Solve expressions using precedence.
✓ Perform explicit type conversion.
✓ Accept and display data.
✓ Identify syntax, runtime and logical errors.
✓ Use if, if-else and if-elif-else.
✓ Use for, range() and while.
✓ Use break and continue.
✓ Create nested loops and patterns.
✓ Perform string indexing and slicing.
✓ Use important string methods.
✓ Create and manipulate lists.
✓ Search and calculate statistics from lists.
✓ Create and manipulate tuples.
✓ Search and calculate statistics from tuples.
✓ Create and traverse dictionaries.
✓ Count character frequency using a dictionary.
✓ Create an employee dictionary.
✓ Import and use math.
✓ Import and use random.
✓ Import and use statistics.

One-Line Master Revision

Understand the problem → break it into smaller parts → design the algorithm → represent it → code it → test it → debug it → and finally verify the result.

एक टिप्पणी भेजें

0 टिप्पणियाँ
* Please Don't Spam Here. All the Comments are Reviewed by Admin.