Python Notes Class 11 - Computer Science - GeeksforGeeks
Python Notes Class 11 - Computer Science - GeeksforGeeks
Search...
DSA Practice Problems C C++ Java Python JavaScript Data Science Machine Learning Cou
In Python for Class XI, you'll explore the fundamentals of programming with
Python, tailored specifically for Class XI students. This article breaks down
key concepts such as variables, loops, and functions, making it easy for you
to grasp the basics of coding.
Introduction to Python
Features of Python
First off, Python is known for its readable and clean syntax. Imagine writing
code that looks almost like plain English. This means you don’t need to
struggle with confusing syntax just to get things done. For example, a
simple line of Python code might look like this: print("Hello, world!"). It's
easy to understand, even if you're new to programming.
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-python-… 2/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-python-… 3/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
1. Open Your Code Editor: First, you need a place to write your code. You
can use any text editor like Notepad, but it's better to use a code editor
like Visual Studio Code, PyCharm, or even an interactive environment like
Jupyter Notebook.
2. Write the Code: In your editor, type the following line of code:
print("Hello, World!")
This line uses the print() function to display the text "Hello, World!" on
the screen. The print() function is a built-in Python function that outputs
whatever is inside the parentheses to the console.
3. Save Your File: Save your file with a .py extension, for example,
hello_world.py. The .py tells your computer that this file is a Python script.
4. Run the Program: To see your code in action, you need to execute it. If
you’re using a terminal or command prompt, navigate to the directory
where you saved your file and type:
python hello_world.py
Press Enter, and you should see Hello, World! displayed on the screen.
5. See the Magic: When you run the program, Python reads the print()
statement and displays "Hello, World!" on your screen. It’s like a friendly
introduction from Python saying, “Hey, your setup is all good, and I’m
ready to run your code!”
That’s all there is to it! You've just executed your first Python program. It’s a
simple start, but it opens the door to more complex coding adventures. If
you see the "Hello, World!" message, you’re ready to dive deeper into the
world of Python programming.
In Python, you have two main ways to run your code: interactive mode and
script mode. Each mode serves a different purpose and is useful in different
scenarios.
Interactive Mode:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-python-… 4/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
What It Is: Interactive mode allows you to write and execute Python code
one line at a time. It’s like having a conversation with Python where you
type a command and instantly see the result.
How to Use It: To start interactive mode, simply open your terminal or
command prompt and type python or python3. You’ll enter the Python shell,
indicated by the >>> prompt, where you can type Python commands
directly.
When to Use It: Interactive mode is great for experimenting with small
code snippets, testing ideas, or learning how Python functions work. For
example, you can quickly test a function or perform calculations without
having to save and run a script.
Script Mode:
What It Is: Script mode involves writing Python code in a file (usually
with a .py extension) and then running the entire file as a program. This
mode is suited for larger programs or when you want to run the same
code multiple times.
How to Use It: Write your Python code in a text editor and save the file
with a .py extension. To execute the script, open your terminal or
command prompt, navigate to the file’s location, and type python
filename.py (replace filename with your file’s name).
When to Use It: Script mode is ideal for developing and running
complete programs or scripts. It allows you to organize your code into
files, making it easier to manage and reuse.
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-python-… 5/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-python-… 6/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
5. Punctuators: Punctuators are symbols that help define the structure and
syntax of Python code. They include:
Parentheses: (), used for grouping expressions and function calls.
Braces: {}, used for defining dictionaries and sets.
Brackets: [], used for lists and indexing.
Comma: ,, used to separate items in lists or function arguments.
Colon: :, used to define blocks of code, such as in loops and
conditionals.
Variables
In Python, variables are like containers that store data values. You can think
of them as labels for pieces of information that you want to use in your
program. Here's a quick rundown on how variables work and some key
points to know:
age = 16
name = "Alice"
Here, age is assigned the integer 16, and name is assigned the string "Alice".
3. Types of Variables: Python is dynamically typed, which means you don’t
need to specify the type of a variable when you declare it. The type is
determined automatically based on the value assigned. Python can
handle various data types including:
Integers: Whole numbers like 5 or 100
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-python-… 7/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
age = 16
age = 17
Here, the variable age initially holds 16, but after the reassignment, it holds
17.
5. Using Variables: Once you have a variable, you can use it in expressions,
print it, or manipulate it in various ways. For example:
total = age + 5
print("In 5 years, you will be", total)
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-python-… 8/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Illustrative Example:
Key Points:
Use of Comments
Comments in programming are crucial for creating readable, maintainable,
and understandable code. They are notes embedded in the code that are
ignored by the compiler or interpreter during execution but can be incredibly
useful for developers. Here’s a quick guide to using comments effectively:
Purpose of Comments
1. Documentation:
Explanation: Comments help explain what a section of code does,
making it easier for others (and yourself) to understand the logic and
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-python-… 9/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
2. Clarification:
Clarify Code: They can clarify why a particular approach or algorithm
was used, which can be useful for future maintenance or for other
developers reading your code.
Example:
4. Debugging:
Temporary Changes: During debugging, comments can help
temporarily disable parts of the code to isolate issues.
Example:
5. Code Collaboration:
Team Communication: In collaborative projects, comments can be
used to communicate intentions, decisions, or instructions to other
team members.
Example:
1. Single-Line Comments:
Syntax: Use the # symbol to comment on a single line.
Example:
2. Multi-Line Comments:
Syntax: Use triple quotes (''' or """) for multi-line comments, although
technically, these are multi-line strings that are not assigned to a
variable.
Example:
"""
This is a multi-line comment
that spans multiple lines.
"""
print("Hello, World!")
Best Practices
Be Clear and Concise: Write comments that are easy to understand and
directly related to the code.
Avoid Redundancy: Don’t state the obvious. Instead of saying “increment
x by 1,” explain why the increment is necessary.
Keep Comments Up-to-Date: Update comments when the code changes
to avoid misleading information.
1. Integers (int):
Definition: Whole numbers without a decimal point.
Example: 5, 100, -42
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 11/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
3. Strings (str):
Definition: Sequences of characters enclosed in single (') or double
quotes (").
Example: "Hello", 'World', "123"
Usage: Used for text processing, displaying messages, and handling
user input.
4. Booleans (bool):
Definition: Represents truth values, either True or False.
Example: True, False
Usage: Used for conditional statements and logical operations.
Definition: Numbers that have both a real and an imaginary part. The
imaginary part is indicated by the letter j or J.
Format: A complex number is written as real_part + imaginary_part * j.
Example: 3 + 4j, -2 - 5j
Usage: Used in advanced mathematics, physics, and engineering where
calculations involve complex numbers. They are especially useful in fields
like signal processing and quantum computing.
Examples in Python:
1. Integer:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 12/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
number = 10
print(type(number)) # Output: <class 'int'>
2. Floating-Point:
pi = 3.14159
print(type(pi)) # Output: <class 'float'>
3. Complex:
z = 2 + 3j
print(type(z)) # Output: <class 'complex'>
1. Lists (list):
Definition: Ordered, mutable collections of items enclosed in square
brackets ([]). Items can be of different types.
Example: [1, 2, 3, 4], ['apple', 'banana', 'cherry']
2. Tuples (tuple):
Definition: Ordered, immutable collections of items enclosed in
parentheses (()). Items can be of different types.
Example: (1, 2, 3, 4), ('red', 'green', 'blue')
Usage: Used to store multiple items in a fixed order where the data
shouldn’t change.
3. Dictionaries (dict):
Definition: Unordered collections of key-value pairs enclosed in curly
braces ({}). Keys are unique, and values can be of any type.
Example: {'name': 'Alice', 'age': 25, 'city': 'New York'}
4. Sets (set):
Definition: Unordered collections of unique items enclosed in curly
braces ({}).
Example: {1, 2, 3}, {'apple', 'banana'}
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 13/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
1. NoneType (None):
Definition: Represents the absence of a value or a null value.
Example: None
Usage: Used to signify that a variable has no value or to represent
missing or undefined data.
Key Points
Type Conversion: You can convert between data types using functions
like int(), float(), str(), and bool().
age = 25 # int
height = 5.9 # float
name = str(age) # converts int to string
None
In Python, None is a special constant that represents the absence of a value or
a null value. It’s a unique data type, NoneType, and is used in various scenarios
to indicate that something is undefined or missing.
1. Representation of Absence:
Definition: None is used to signify that a variable or function does not
have a value assigned to it. It can be thought of as a placeholder or a
default value when no other value is provided.
Example:
result = None
def no_return():
pass
variable = None
if variable is None:
print("Variable is not assigned.")
4. Function Parameters:
Definition: None is often used as a default value for function parameters
to indicate that no argument was provided. This is useful for optional
parameters.
Example:
def greet(name=None):
if name is None:
print("Hello, World!")
else:
print(f"Hello, {name}!")
5. Comparison:
Definition: None is often compared using is rather than == to check if a
variable is None, as None is a singleton (only one instance exists).
Example:
a = None
b = None
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 15/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Mapping(dictionary)
In Python, a dictionary is a built-in data structure that allows you to store
and manage data in key-value pairs. It’s a type of mapping where each key is
associated with a value, making it easy to look up data based on a unique
identifier.
1. Key-Value Pairs:
Definition: A dictionary stores data in pairs where each key maps to a
specific value. Keys must be unique within a dictionary, but values can
be duplicated.
Example:
student = {
"name": "Alice",
"age": 18,
"courses": ["Math", "Science"]
}
2. Unordered:
Definition: Dictionaries are unordered collections, meaning that the
items have no index. The order of key-value pairs is not guaranteed to
be preserved.
Example:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 16/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
print(student)
# Output: {'name': 'Alice', 'age': 18, 'courses': ['Math',
'Science']}
3. Mutable:
Definition: Dictionaries are mutable, meaning you can change their
content after creation. You can add, remove, or modify key-value pairs.
Example:
4. Accessing Values:
Definition: Values in a dictionary are accessed using their associated
keys. If the key does not exist, it will raise a KeyError.
Example:
5. Methods:
Definition: Dictionaries come with several useful methods for handling
data.
.get(key, default): Returns the value for a key if it exists,
otherwise returns a default value.
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 17/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
6. Deleting Items:
Definition: You can remove items using methods like del or the .pop()
method.
Example:
Example Usage:
# Creating a dictionary
car = {
"make": "Toyota",
"model": "Corolla",
"year": 2021
}
# Accessing a value
print(car["make"]) # Output: Toyota
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 18/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
In Python, data types are categorized into mutable and immutable based on
whether their content can be changed after they are created. Understanding
the difference between these two categories is essential for effective
programming and memory management.
Mutable data types are those whose values can be changed after they are
created. This means that you can modify, add, or remove elements from
these objects without creating a new object.
1. Lists (list):
Definition: Ordered collections of items that can be changed after
creation.
Operations: You can modify individual elements, add new elements, or
remove elements.
Example:
2. Dictionaries (dict):
Definition: Collections of key-value pairs where the data can be
modified after creation.
Operations: You can add, update, or remove key-value pairs.
Example:
3. Sets (set):
Definition: Unordered collections of unique elements that can be
modified.
Operations: You can add or remove elements from a set.
Example:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 19/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
numbers = {1, 2, 3}
numbers.add(4) # Adds a new element
numbers.remove(2) # Removes an element
Immutable data types are those whose values cannot be changed after they
are created. Any operation that seems to modify the object actually creates a
new object.
1. Integers (int):
Definition: Whole numbers without decimal points.
Operations: Any arithmetic operation creates a new integer object.
Example:
a = 5
a += 2 # Creates a new integer object, 7
pi = 3.14
pi += 0.01 # Creates a new float object
3. Strings (str):
Definition: Sequences of characters.
Operations: Concatenation or slicing creates new string objects.
Example:
message = "Hello"
message = message + " World" # Creates a new string object
4. Tuples (tuple):
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 20/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Key Differences:
Operators
Arithmetic Operators
result = 5 + 3 # Output: 8
text = "Hello" + " World" # Output: "Hello World"
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 21/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
result = 10 - 4 # Output: 6
result = 7 * 2 # Output: 14
text = "Hi! " * 3 # Output: "Hi! Hi! Hi! "
Floor Division (//): Divides one number by another, returning the largest
integer less than or equal to the result.
Example:
result = 10 // 3 # Output: 3
result = 10 % 3 # Output: 1
result = 2 ** 3 # Output: 8
Relational Operators
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 22/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Example:
Greater than (>): Checks if the value on the left is greater than the value
on the right.
Example:
Less than (<): Checks if the value on the left is less than the value on the
right.
Example:
Greater than or equal to (>=): Checks if the value on the left is greater
than or equal to the value on the right.
Example:
Less than or equal to (<=): Checks if the value on the left is less than or
equal to the value on the right.
Example:
Logical Operators
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 23/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Not (not): Reverses the logical state of its operand. Returns True if the
statement is false, and False if the statement is true.
Example:
Assignment Operators
1. Addition Assignment (+=): Adds a value to the variable and assigns the
result back to the variable.
Example:
x = 10
x += 5 # Equivalent to x = x + 5; x now equals 15
Example:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 24/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
y = 20
y -= 7 # Equivalent to y = y - 7; y now equals 13
Example:
z = 4
z *= 3 # Equivalent to z = z * 3; z now equals 12
4. Division Assignment (/=): Divides the variable by a value and assigns the
result back to the variable. Note that this will always result in a float.
Example:
a = 8
a /= 2 # Equivalent to a = a / 2; a now equals 4.0
Example:
b = 7
b //= 2 # Equivalent to b = b // 2; b now equals 3
Example:
c = 10
c %= 3 # Equivalent to c = c % 3; c now equals 1
Example:
d = 2
d **= 3 # Equivalent to d = d ** 3; d now equals 8
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 25/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Identity Operators
Identity operators are used to compare the memory locations of two objects,
determining whether they are the same object.
a = [1, 2, 3]
b = a
c = [1, 2, 3]
is not: Checks if two variables do not point to the same object in memory.
Example:
x = "hello"
y = "world"
Membership Operators
numbers = [1, 2, 3, 4, 5]
print(3 in numbers) # Output: True, because 3 is in the
list
print("hello" in "hello world") # Output: True, because
the substring "hello" is present in the string
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 26/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
These operators are useful for performing comparisons and checking the
presence of elements in data structures, which helps in controlling the flow
of a program based on certain conditions.
Precedence of Operators
Example:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 27/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Evaluation of an Expression
Example:
Type Conversion
Type conversion allows you to change the data type of a value. This can be
done implicitly by Python or explicitly by the programmer.
Explicit Conversion: Done using functions like int(), float(), and str() to
convert between types.
Example:
num_str = "123"
num_int = int(num_str) # Converts the string "123" to the
integer 123
Understanding these concepts helps you write more effective and error-free
code by ensuring expressions are evaluated correctly and data types are
managed properly.
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 28/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
To get input from the user, use the input() function. This function reads a line
of text entered by the user and returns it as a string. If you need to handle
different types of input, like integers or floats, you'll need to convert the
input explicitly.
name = input("Enter your name: ") # Prompt the user and store the
entered name as a string
print(f"Hello, {name}!") # Display the entered name
To display output, use the print() function. This function can take multiple
arguments and will display them separated by spaces.
name = "Alice"
age = 17
print(f"{name} is {age} years old.") # Using f-strings for
formatted output
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 29/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
You can combine both input and output operations in a single program to
create interactive scripts.
You can also handle multiple inputs at once by splitting the input string.
Using input() and print() functions allows you to create interactive Python
programs that can take user input and display output dynamically.
Syntax Errors
Syntax errors occur when the code does not follow the correct syntax or
structure of the Python language. These errors are caught by the Python
interpreter before the code is executed. They are often due to typos or
incorrect use of language features.
Example:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 30/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Error Message:
Fix:
Logical Errors
Logical errors occur when the code runs without crashing but produces
incorrect results. These errors are often due to incorrect logic or algorithm
mistakes. Unlike syntax errors, logical errors are not detected by the
interpreter and require careful debugging and testing to identify.
Example:
def calculate_area(radius):
return radius * radius # Incorrect formula for area of a
circle
Fix:
import math
def calculate_area(radius):
return math.pi * radius * radius # Correct formula
Runtime Errors
Runtime errors occur while the program is running and often cause the
program to crash or terminate unexpectedly. These errors can be due to
various issues such as invalid operations, file not found, or division by zero.
Example:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 31/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
x = 10
y = 0
print(x / y) # Division by zero error
Error Message:
Fix:
x = 10
y = 1
print(x / y) # Correct division
The flow of control refers to the order in which the individual statements,
instructions, or function calls are executed or evaluated in a programming
language. In Python, this flow is managed using different constructs like
sequences, conditions, and loops.
Use of Indentation
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 32/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Example:
if True:
print("This is inside the if block") # Indented block
print("This is outside the if block") # Not indented
Sequential Flow
Example:
print("Start")
print("Middle")
print("End")
In this example, the program prints "Start", then "Middle", and finally
"End", in that order.
Conditional Flow
Conditional flow allows the program to make decisions and execute different
blocks of code based on certain conditions. This is typically managed using
if, elif, and else statements.
Example:
age = 20
if age < 18:
print("Minor")
elif age < 65:
print("Adult")
else:
print("Senior")
Here, the program checks the value of age and prints different messages
depending on the condition met.
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 33/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Iterative Flow
for i in range(5):
print(i) # Prints numbers from 0 to 4
This loop iterates over a range of numbers and prints each one.
Example (while loop):
count = 0
while count < 5:
print(count)
count += 1 # Increments count each iteration
Conditional Statements
temperature = 30
if temperature > 25:
print("It's a hot day!")
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 34/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
temperature = 20
if temperature > 25:
print("It's a hot day!")
else:
print("It's a cool day!")
temperature = 10
if temperature > 30:
print("It's a very hot day!")
elif temperature > 20:
print("It's a warm day!")
elif temperature > 10:
print("It's a cool day!")
else:
print("It's a cold day!")
Flowcharts
1. Start
2. Check Temperature (Decision)
If Temperature > 25: Print "Hot Day"
Else: Print "Cool Day"
3. End
Simple Programs
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 35/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
1. Absolute Value: To find the absolute value of a number, you can use
conditional statements to handle negative values.
Example:
number = -7
if number < 0:
absolute_value = -number
else:
absolute_value = number
print("Absolute value:", absolute_value)
a = 5
b = 2
c = 9
if a > b:
a, b = b, a
if a > c:
a, c = c, a
if b > c:
b, c = c, b
print("Sorted numbers:", a, b, c)
number = 15
divisor = 3
if number % divisor == 0:
print(f"{number} is divisible by {divisor}")
else:
print(f"{number} is not divisible by {divisor}")
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 36/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
1. for Loop
The for loop iterates over a sequence (like a list, tuple, or string) or a range
of numbers. It’s useful when you know in advance how many times you want
to repeat a block of code.
Example:
for i in range(5):
print(i) # Prints numbers from 0 to 4
2. range() Function
Example:
3. while Loop
The while loop executes as long as its condition remains true. It’s useful
when you don’t know beforehand how many times you’ll need to repeat the
code.
Example:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 37/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
count = 0
while count < 5:
print(count)
count += 1 # Increment count
4. Flowcharts
Flowcharts can be used to visualize the control flow of loops. They help in
understanding how the iteration progresses and where decisions are made.
1. Start
2. Initialize Counter (Process)
3. Check Condition (Decision)
If True: Execute Loop Body (Process)
Update Counter (Process)
Back to Check Condition
If False: End Loop
4. End
for i in range(10):
if i == 5:
break # Exits the loop when i is 5
print(i)
continue: Skips the current iteration and continues with the next iteration
of the loop.
Example:
for i in range(10):
if i % 2 == 0:
continue # Skips even numbers
print(i) # Prints only odd numbers
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 38/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
6. Nested Loops
Nested loops involve placing one loop inside another. They are useful for
working with multi-dimensional data or generating patterns.
Example:
for i in range(3):
for j in range(3):
print(f"({i}, {j})", end=" ")
print() # New line after inner loop
Generating Patterns:
Example: Generate a square pattern of stars.
size = 5
for i in range(size):
for j in range(size):
print('*', end=' ')
print() # New line after each row
Summation of Series:
Example: Calculate the sum of the first 10 natural numbers.
total = 0
for i in range(1, 11):
total += i
print("Sum of series:", total)
number = 5
factorial = 1
for i in range(1, number + 1):
factorial *= i
print("Factorial:", factorial)
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 39/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Strings in Python
Introduction to Strings
Example:
String Operations
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 40/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
4. Slicing: Slicing extracts a part of the string. You use indexing to specify
the start and end positions. The syntax is string[start:end].
Example:
The for loop is straightforward and ideal for traversing a string because it
directly iterates over each character in the string.
Example:
text = "Python"
for char in text:
print(char)
Explanation:
text is the string you want to traverse.
The for loop iterates over each character (char) in the string text.
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 41/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
You can also use a while loop to traverse a string by managing the index
manually.
Example:
text = "Python"
index = 0
while index < len(text):
print(text[index])
index += 1
Explanation:
text is the string you want to traverse.
index starts at 0 and increments with each iteration.
text[index] accesses the character at the current index.
The loop continues until index is equal to the length of the string
(len(text)).
If you need both the character and its index, you can use enumerate() with a
for loop.
Example:
text = "Python"
for index, char in enumerate(text):
print(f"Index {index}: {char}")
Explanation:
enumerate(text) returns both the index and the character.
index is the position of the character in the string.
char is the character at that position.
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 42/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Example:
Explanation:
vowels is a string containing all vowel characters.
For each character in text, check if it is in the vowels string.
Increment count if a vowel is found.
len()
text = "Hello"
print(len(text)) # Output: 5
capitalize()
Usage: Capitalizes the first character of the string and makes all
other characters lowercase.
Example:
title()
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 43/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Example:
lower()
text = "HELLO"
print(text.lower()) # Output: hello
upper()
text = "hello"
print(text.upper()) # Output: HELLO
count()
find()
index()
endswith()
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 44/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
startswith()
isalnum()
text = "hello123"
print(text.isalnum()) # Output: True
isalpha()
text = "hello"
print(text.isalpha()) # Output: True
isdigit()
text = "12345"
print(text.isdigit()) # Output: True
islower()
text = "hello"
print(text.islower()) # Output: True
isupper()
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 45/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
text = "HELLO"
print(text.isupper()) # Output: True
isspace()
lstrip()
rstrip()
strip()
replace()
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 46/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
join()
partition()
Usage: Splits the string into a 3-tuple containing the part before
the separator, the separator itself, and the part after.
Example:
split()
These methods and functions are essential for text processing and
manipulation in Python, making it easier to work with strings in a variety of
scenarios.
In Python, a list is a versatile and powerful data structure that can hold an
ordered collection of items, which can be of different types—integers,
strings, objects, or even other lists. Lists are mutable, meaning you can
change their content after they are created. They are defined using square
brackets [], with items separated by commas.
Example:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 47/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Indexing
Example:
List Operations
1. Concatenation
Concatenation is the operation of combining two lists into a single list. You
use the + operator to concatenate lists.
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list) # Output: [1, 2, 3, 4, 5, 6]
2. Repetition
Repetition allows you to create a list with repeated copies of its elements
using the * operator.
Example:
my_list = [1, 2, 3]
repeated_list = my_list * 3
print(repeated_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
3. Membership
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 48/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Example:
4. Slicing
where start is the index of the first element included in the slice, and stop is
the index of the first element excluded from the slice.
Example:
my_list = [0, 1, 2, 3, 4, 5]
sliced_list = my_list[1:4]
print(sliced_list) # Output: [1, 2, 3]
You can also omit the start or stop to slice from the beginning or to the end
of the list.
Example:
The for loop is the most straightforward way to traverse a list. It iterates
over each element of the list, allowing you to perform operations with the
item.
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 49/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Example:
Output:
10
20
30
40
50
In this example, item represents each element in my_list, and the loop prints
each element in turn.
You can also traverse a list using a while loop by manually managing the
index. This approach gives you more control but requires you to handle the
indexing and loop conditions yourself.
Example:
Output:
10
20
30
40
50
Here, index starts at 0 and increases by 1 after each iteration, accessing each
element by its index.
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 50/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
For a more concise way to process each item in a list, you can use list
comprehensions. This is a compact way of generating lists based on existing
ones and can also be used for simple operations.
Example:
Output:
Using enumerate()
If you need both the index and the value of each element while traversing,
enumerate() is a handy built-in function. It returns both the index and the item
in each iteration.
Example:
Output:
Index 0: apple
Index 1: banana
Index 2: cherry
Using these techniques, you can efficiently traverse and process lists in
Python, adapting your approach based on your specific needs and the task at
hand.
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 51/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
1. len()
2. list()
my_string = "hello"
my_list = list(my_string)
print(my_list) # Output: ['h', 'e', 'l', 'l', 'o']
3. append()
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
4. extend()
Purpose: Adds elements from an iterable (like a list) to the end of the list.
Example:
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
5. insert()
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 52/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list) # Output: [1, 4, 2, 3]
6. count()
my_list = [1, 2, 2, 3, 2]
print(my_list.count(2)) # Output: 3
7. index()
my_list = [1, 2, 3, 2]
print(my_list.index(2)) # Output: 1
8. remove()
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]
9. pop()
Purpose: Removes and returns the element at the specified position (or
the last element if no position is specified).
Example:
my_list = [1, 2, 3]
item = my_list.pop()
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 53/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
print(item) # Output: 3
print(my_list) # Output: [1, 2]
10. reverse()
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]
11. sort()
Purpose: Sorts the elements of the list in place (modifies the original list).
Example:
my_list = [3, 1, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3]
12. sorted()
Purpose: Returns a new list that is sorted (does not modify the original
list).
Example:
my_list = [3, 1, 2]
sorted_list = sorted(my_list)
print(sorted_list) # Output: [1, 2, 3]
print(my_list) # Output: [3, 1, 2]
13. min()
my_list = [4, 1, 7, 3]
print(min(my_list)) # Output: 1
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 54/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
14. max()
my_list = [4, 1, 7, 3]
print(max(my_list)) # Output: 7
15. sum()
Purpose: Returns the sum of all elements in the list (only works with
numeric lists).
Example:
my_list = [1, 2, 3]
print(sum(my_list)) # Output: 6
Nested Lists
Nested lists in Python are simply lists that contain other lists as their
elements. They can be thought of as a matrix or a table, where each cell or
row is a list itself. This structure allows you to represent more complex data
arrangements and perform operations on multi-dimensional data.
Basic Example
nested_list = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
In this example, nested_list contains three lists, each with three integers.
Accessing Elements
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 55/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
To access elements in a nested list, you need to specify the index of both the
outer list and the inner list. For example:
Modifying Elements
You can modify elements in a nested list just like you would with a regular
list:
nested_list[0][1] = 20
print(nested_list) # Output: [[1, 20, 3], [4, 5, 6], [7, 8,
9]]
You can use nested loops to iterate over each element in a nested list. Here’s
how you can print every item:
Output:
1 20 3
4 5 6
7 8 9
Nested lists are commonly used to represent matrices (2D arrays) in Python.
For instance, if you're working with a grid or table of data, a nested list can
help you store and manipulate this data effectively.
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 56/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
matrix1 = [
[1, 2, 3],
[4, 5, 6]
]
matrix2 = [
[7, 8, 9],
[10, 11, 12]
]
Summary
Suggested Programs
Here are some suggested programs to work with lists in Python, focusing on
finding maximum, minimum, mean values, performing linear search, and
counting the frequency of elements:
Program:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 57/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
min_value = min(numbers)
print(f"Minimum value: {min_value}")
Explanation:
Program:
Explanation:
The linear_search() function iterates through the list and checks if each
element matches the target value. It returns the index if found or -1 if not.
Program:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 58/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Explanation:
The Counter class from the collections module helps count the occurrences
of each element in the list. It returns a dictionary-like object where keys
are list elements and values are their counts.
Summary
These programs provide practical ways to work with lists in Python. Finding
maximum, minimum, and mean values helps analyze numeric data. Linear
search is a basic searching technique to locate elements, while counting
frequencies can be useful for understanding the distribution of values. These
exercises build foundational skills for handling and processing list data in
various programming scenarios.
Dictionary
Introduction to Dictionaries
Example of a Dictionary:
# Creating a dictionary
student = {
"name": "John Doe",
"age": 16,
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 59/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
"grade": "11th",
"subjects": ["Math", "Science", "English"]
}
In this dictionary:
To access the values stored in a dictionary, you use the keys. Here’s how you
can do it:
Example:
Explanation:
student["name"] retrieves the value associated with the key "name", which is
"John Doe".
Similarly, student["age"] gets the age, and student["subjects"] returns the
list of subjects.
If you try to access a key that doesn't exist in the dictionary, Python will raise
a KeyError. To avoid this, you can use the .get() method, which allows you to
specify a default value if the key is not found.
Example:
In this example:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 60/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Summary
Dictionaries are a powerful tool in Python for storing and managing data in
key-value pairs. Accessing items is straightforward using the keys, and
handling potential errors is easy with methods like .get(). This flexibility
makes dictionaries ideal for various applications, from simple data storage to
complex data manipulation tasks.
Mutability of a Dictionary
Dictionaries in Python are mutable, which means you can change their
contents after they have been created. This mutability allows you to add
new key-value pairs, modify existing ones, and even delete items as needed.
Adding a New Item
You can add new key-value pairs to a dictionary by simply assigning a value
to a new key. If the key doesn't already exist, it will be created.
Example:
print(student)
# Output: {'name': 'John Doe', 'age': 16, 'grade': '11th', 'subjects':
['Math', 'Science', 'English']}
In this example, the key "subjects" is added to the dictionary with its
associated value ["Math", "Science", "English"].
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 61/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
To change the value associated with an existing key, simply assign a new
value to that key.
Example:
print(student)
# Output: {'name': 'John Doe', 'age': 17, 'grade': '11th', 'subjects':
['Math', 'Science', 'English']}
Traversing a Dictionary
Example:
# Define a dictionary
student = {
"name": "John Doe",
"age": 16,
"grade": "11th",
"subjects": ["Math", "Science", "English"]
}
# Traversing keys
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 62/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
In this example, the loop iterates through each key in the student dictionary
and prints it.
2. Traversing Values
If you only need to access the values, you can loop through the dictionary’s
values.
Example:
# Traversing values
for value in student.values():
print(f"Value: {value}")
Example:
In this example, each tuple returned by .items() is unpacked into key and
value, which are then printed.
4. Using Dictionary Comprehensions
For more advanced operations, you can use dictionary comprehensions to
create or modify dictionaries based on traversal.
Example:
print(uppercased_dict)
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 63/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Python dictionaries come with a set of built-in functions and methods that
make it easy to work with key-value pairs. Here’s a rundown of the most
commonly used ones:
1. len()
Returns the number of items (key-value pairs) in the dictionary.
Example:
2. dict()
Creates a new dictionary. It can take keyword arguments or a list of key-
value pairs.
Example:
3. keys()
Returns a view object that displays a list of all the keys in the dictionary.
Example:
keys = student.keys()
print(keys) # Output: dict_keys(['name', 'age'])
4. values()
Returns a view object that displays a list of all the values in the dictionary.
Example:
values = student.values()
print(values) # Output: dict_values(['John', 16])
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 64/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
5. items()
Returns a view object that displays a list of tuples, each containing a key-
value pair.
Example:
items = student.items()
print(items) # Output: dict_items([('name', 'John'), ('age', 16)])
6. get()
Returns the value for the specified key if the key is in the dictionary.
Otherwise, it returns None or a default value if provided.
Example:
7. update()
Updates the dictionary with key-value pairs from another dictionary or from
an iterable of key-value pairs.
Example:
8. del
Deletes a specific key-value pair from the dictionary.
Example:
del student["age"]
print(student) # Output: {'name': 'John', 'grade': '11th', 'school':
'High School'}
9. clear()
Removes all items from the dictionary.
Example:
student.clear()
print(student) # Output: {}
10. fromkeys()
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 65/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Example:
11. copy()
Returns a shallow copy of the dictionary.
Example:
copy_dict = student.copy()
print(copy_dict) # Output: {'name': 'John', 'grade': '11th',
'school': 'High School'}
12. pop()
Removes a specified key and returns its value. If the key is not found, it
raises a KeyError unless a default value is provided.
Example:
name = student.pop("name")
print(name) # Output: John
print(student) # Output: {'grade': '11th', 'school': 'High School'}
13. popitem()
Removes and returns the last key-value pair from the dictionary as a tuple.
Example:
item = student.popitem()
print(item) # Output: ('school', 'High School')
print(student) # Output: {'grade': '11th'}
14. setdefault()
Returns the value of a key if it is in the dictionary. If not, it inserts the key
with a specified default value and returns that value.
Example:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 66/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
15. max()
Returns the maximum key from the dictionary based on lexicographical
order.
Example:
16. min()
Returns the minimum key from the dictionary based on lexicographical
order.
Example:
17. sorted()
Returns a sorted list of the dictionary’s keys.
Example:
sorted_keys = sorted(student)
print(sorted_keys) # Output: ['grade']
Summary
Suggested Programs
Here are two simple programs using dictionaries to tackle common tasks:
counting characters and managing employee data.
1. Count the Number of Times a Character Appears in a Given String Using a
Dictionary
This program counts how often each character appears in a string and stores
the counts in a dictionary.
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 67/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Example Program:
def count_characters(input_string):
# Create an empty dictionary to store character counts
char_count = {}
return char_count
Explanation:
The program uses a dictionary char_count to track how many times each
character appears.
It loops through the input_string, updating the count in the dictionary for
each character.
2. Create a Dictionary with Names of Employees, Their Salaries, and Access Them
This program creates a dictionary to store employee names and their
salaries, and then accesses this data.
Example Program:
Explanation:
import math
In this example:
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 69/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
If you only need specific functions or variables from a module, you can use
the from <module> import <item> syntax. This approach makes your code
cleaner and more efficient by importing only what you need.
In this example:
from math import sqrt, pi imports only the sqrt function and pi constant
from the math module.
You can then use sqrt() and pi directly without prefixing them with math.
and mathematical functions like sqrt(), ceil(), and sin(). Here’s a quick guide
on how to use these features:
Importing the Math Module
First, you need to import the math module:
import math
Using Constants
math.pi: The mathematical constant π (pi), approximately equal to
3.14159.
math.e: The mathematical constant e, approximately equal to 2.71828.
Example:
import math
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 70/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Using Functions
math.sqrt(x): Returns the square root of x.
import math
Summary
The math module is a powerful toolkit for performing mathematical
operations in Python. By importing it, you can utilize constants like pi and e,
and functions for arithmetic, trigonometric, and other calculations. Whether
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 71/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Random Module
import random
import random
import random
Statistics Module
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 72/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
import statistics
import statistics
data = [1, 3, 5, 7, 9]
print("Median of data:", statistics.median(data))
# Output: Median of data: 5
import statistics
data = [1, 1, 2, 3, 4]
print("Mode of data:", statistics.mode(data))
# Output: Mode of data: 1
Summary
The random and statistics modules are invaluable tools in Python for dealing
with random number generation and statistical calculations. The random
module helps you generate random numbers for simulations and games,
while the statistics module lets you easily compute common statistical
measures like the mean, median, and mode. Whether you're doing data
analysis or just adding some randomness to your programs, these modules
provide a straightforward approach to handle these tasks.
Conclusion
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 73/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
With this knowledge, you're not only prepared for your exams but also
ready to take on more advanced coding challenges. Keep practicing, and
you'll continue to grow as a confident and capable programmer.
Similar Reads
Class 12 Computer Science Notes
CBSE Class 12th Computer Science Unit 1 Notes: Computational Thinking and
Programming
CBSE Class 12th Unit 1: Computational Thinking and Programming is a crucial part of the curriculum for
Class 12th students, as outlined in the latest CBSE 2024-25 syllabus. This unit is designed to provide a…
15+ min read
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 74/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 75/77
7/13/25, 8:39 AM Python Notes Class 11 - Computer Science - GeeksforGeeks
Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida, Gautam
Buddh Nagar, Uttar Pradesh, 201305
Advertise with us
Company Languages
About Us Python
Legal Java
Privacy Policy C++
In Media PHP
Contact Us GoLang
Advertise with us SQL
GFG Corporate Solution R Language
Placement Training Program Android Tutorial
Tutorials Archive
https://www.geeksforgeeks.org/computer-science-fundamentals/cbse-class-11-computational-thinking-and-programming/#introduction-to-pytho… 77/77