Monday, April 7, 2025

7.15 Uses of Library functions : String Functions , Numeric and mathematical | Grade 9 New Curriculum Computer Science 2082

 


7.15 Uses of Library functions : String Functions (center, upper, lower, Len), Numeric and mathematical (sum, pow, round, abs, sqrt, Int)

 

Function

A function is a block of reusable code that performs a specific task.

 

Library function

Library functions are part of Python's standard library or third-party libraries that come with a set of predefined functions.

 

 

String Function

·       A string function is a built-in function that is used to manipulate or process string data.

·       These functions perform various operations like changing the case of letters, finding the length of a string, concatenating strings, and more.

 

center(width, fillchar): Centers the string within the given width, padding it with a specified character (default is a space).

Example:

text = "Hello"

print(text.center(10, "*"))  # Output: '**Hello***'

 

upper( ): Converts all characters in the string to uppercase.

Example:

text = "hello"

print(text.upper( ))  # Output: 'HELLO'

 

lower( ): Converts all characters in the string to lowercase.

Example:

text = "hello"

print(text.lower( ))  # Output: 'hello'

 

len(): Returns the length of the string (i.e., the number of characters).

Example:

text = "Hello"

print(len(text))  # Output: 5

 

Numeric Functions

These functions are part of Python's built-in capabilities or from the math module to manipulate numeric values.

 

sum(iterable): Returns the sum of all elements in an iterable (e.g., a list).

Example:

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

print(sum(numbers))  # Output: 15

 

abs(x): Returns the absolute value of a number.

Example:

print(abs(-5))  # Output: 5

print(abs(3.5))  # Output: 3.5

 

round(x, n): Rounds a number x to n decimal places (default is 0).

Example:

print(round(3.14159, 2))  # Output: 3.14

print(round(3.5))  # Output: 4

 

pow(x, y): Returns x raised to the power of y (i.e., x^y).

Example:

print(pow(2, 3))  # Output: 8 (2^3)

 

int(x): Converts a number or string to an integer.

Example:

print(int(3.7))  # Output: 3

print(int("42"))  # Output: 42

 

min( ) and max( )Function: Returns the smallest (minimum) or largest(maximum) value from the given iterable or from multiple values passed as arguments.

Example:

numbers = [3, 1, 4, 1, 5, 9, 2, 6]

print(min(numbers))  # Output: 1

 

Mathematical Functions (from math module)

These functions are provided by the math module and perform more advanced mathematical operations.

 

math.sqrt(x): Returns the square root of x.

Example:

import math

print(math.sqrt(16))  # Output: 4.0

 

math.factorial(x) : Returns the factorial of a number x (i.e., x! = x * (x - 1) * (x - 2) * ... * 1).

Example:

import math

print(math.factorial(5))  # Output: 120 (5! = 5 * 4 * 3 * 2 * 1)

 

math.pi : Provides the mathematical constant π (approximately 3.14159).

Example:

import math

print(math.pi)  # Output: 3.141592653589793

 

math.sin(x) and math.cos(x): Return the sine and cosine of x (where x is in radians).

Example:

import math

print(math.sin(math.radians(30)))  # Output: 0.5

print(math.cos(math.radians(60)))  # Output: 0.5

 

math.log(x, base): Returns the logarithm of x to the given base. If the base is not specified, it returns the natural logarithm (base e).

Example:

import math

print(math.log(10))  # Output: 2.302585092994046 (natural log of 10)

print(math.log(100, 10))  # Output: 2.0 (logarithm base 10 of 100)

7.14 Lists and Dictionary | Grade 9 New Curriculum Computer Science 2082

 


7.14 Lists and Dictionary

 

Python list

·       A list in Python is an ordered collection of items, which can be of different types like integers, strings, floats, Booleans etc.

·       It is a built-in data types which stores multiple data in a single variable.

·       It is one of the most commonly used data structures in Python, and they are very flexible because they are mutable (we can change their content after creation).

 

Creating a List : A list is created by placing items inside square brackets [ ], separated by commas.

 

Syntax:

A list is created by placing items inside square brackets [ ], separated by commas.

 

Examples:

# A list of integers

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

 

# A list of strings

fruits = ["apple", "banana", "cherry"]

 

# A mixed list (different types of elements)

mixed_list = [1, "apple", 3.14, True]

 

# An empty list

empty_list = [ ]

 

 Accessing Elements: We can access elements of a list using their index. Indexing in Python starts from 0 for the first element.

 

Syntax:

my_list[index]

 

Examples:

# Accessing the first element (index 0)

print(numbers[0])  # Output: 1

 

# Accessing the second element (index 1)

print(fruits[1])  # Output: banana

 

# Accessing the last element (negative index)

print(mixed_list[-1])  # Output: True

 

 

 

Modifying a List: Since lists are mutable, we can modify, add, or remove elements after the list is created.

 

Examples:

# Changing an element by index

numbers[0] = 10

print(numbers)  # Output: [10, 2, 3, 4, 5]

 

# Adding an element at the end of the list (append)

fruits.append("orange")

print(fruits)  # Output: ["apple", "banana", "cherry", "orange"]

 

# Inserting an element at a specific index (insert)

fruits.insert(1, "grape")  # Adds "grape" at index 1

print(fruits)  # Output: ["apple", "grape", "banana", "cherry", "orange"]

 

# Removing an element by value (remove)

fruits.remove("banana")

print(fruits)  # Output: ["apple", "grape", "cherry", "orange"]

 

# Removing an element by index (pop)

removed_item = fruits.pop(2)  # Removes "cherry" at index 2

print(fruits)  # Output: ["apple", "grape", "orange"]

print("Removed:", removed_item)  # Output: Removed: cherry

 

List Length: We can find the number of elements in a list using the len( ) function.

 

Syntax:

len(my_list)

 

Example:

print(len(fruits))  # Output: 4

 

Looping through list: We can loop through the list elements using the for loop to print all the elements one by one.

 

Example:

# List of fruits

fruits = ["apple", "banana", "cherry", "orange"]

 

# Looping through the list

for fruit in fruits:

        print(fruit)

 

 

 

List Slicing: We can access a sub list or slice from a list by specifying a start and end index.

 Syntax:

my_list[start:end]

·       start: The index to start from (inclusive).

·       end: The index to end at (exclusive).

Examples:

# A list of strings

fruits = [“apple”, “grape”, “cherry”, “orange”]

 

# Slicing from index 1 to 3 (does not include index 3)

print(fruits[1:3])  # Output: ['grape', 'cherry']

 

# Slicing from the beginning to index 2

print(fruits[:2])  # Output: ['apple', 'grape']

 

# Slicing from index 2 to the end

print(fruits[2:])  # Output: ['cherry', 'orange']

 

# Slicing the entire list (same as making a copy)

print(fruits[:])  # Output: ['apple', 'grape', 'cherry', 'orange']

 

List Concatenation and Repetition : We can concatenate (join) lists using the + operator and repeat a list using the * operator.

Examples:

# Concatenating two lists

list1 = [1, 2, 3]

list2 = [4, 5, 6]

combined = list1 + list2

print(combined)  # Output: [1, 2, 3, 4, 5, 6]

 

# Repeating a list

repeated = list1 * 2

print(repeated)  # Output: [1, 2, 3, 1, 2, 3]

 

List Comprehension: It is a concise way to create lists by applying an expression to each item in an iterable.

Syntax:

[expression for item in iterable if condition]

Example:

# Creating a list of squares from 0 to 4

squares = [x**2 for x in range(5)]

print(squares)  # Output: [0, 1, 4, 9, 16]

 

# Using a condition to filter even numbers

even_numbers = [x for x in range(10) if x % 2 == 0]

print(even_numbers)  # Output: [0, 2, 4, 6, 8]

Nested Lists : Lists can contain other lists as elements. These are called nested lists.

 

Example:

nested_list = [1, [2, 3], 4, [5, 6]]

print(nested_list[1])  # Output: [2, 3]

print(nested_list[1][0])  # Output: 2

 

List Methods: Here are some common methods that can be used with lists:

 

  • append(item) — Adds an item to the end of the list.
  • insert(index, item) — Inserts an item at a specified index.
  • remove(item) — Removes the first occurrence of the item from the list.
  • pop(index) — Removes and returns the item at the specified index.
  • sort() — Sorts the list in ascending order.
  • reverse() — Reverses the order of elements in the list.
  • clear() — Removes all items from the list.

 

fruits = ["apple", "banana", "cherry"]

fruits.sort()  # Sorts the list alphabetically

print(fruits)  # Output: ['apple', 'banana', 'cherry']

 

fruits.reverse()  # Reverses the list

print(fruits)  # Output: ['cherry', 'banana', 'apple']

 

fruits.clear()  # Clears all items in the list

print(fruits)  # Output: [ ]

 

Python Dictionary

·       A dictionary in Python is an unordered collection of key-value pairs.

·       Each item in a dictionary has a unique key and a corresponding value.

·       It is one of the most versatile and widely used data structures in Python.

 

Creating a Dictionary

·       A dictionary is created by placing key-value pairs inside curly braces {}, separated by commas.

·       The key and value are separated by a colon : .

 

Syntax:

my_dict = {key1: value1, key2: value2, key3: value3, ...}

 

Example:

# A dictionary of fruits with their colors

fruit_colors = {"apple": "red", "banana": "yellow", "cherry": "red"}

 

 

 

Accessing Dictionary Values : We can access the value associated with a key by using square brackets [ ] with the key inside.

Syntax:

my_dict[key]

 

Example:

fruit_colors = {"apple": "red", "banana": "yellow", "cherry": "red"}

print(fruit_colors["apple"])  # Output: red

 

·       If we try to access a key that doesn’t exist in the dictionary, it will raise a KeyError.

·       To handle missing keys safely, we can use the get() method, which returns None if the key is not found (or a default value you specify).

Example:

print(fruit_colors.get("orange", "Not found"))  # Output: Not found

 

Adding or Modifying Items : To add a new key-value pair or modify an existing value in a dictionary, we simply assign a value to a key.

 

Examples:

fruit_colors["orange"] = "orange"  # Adds a new key-value pair

fruit_colors["banana"] = "green"  # Modifies the value for the key "banana"

print(fruit_colors)

 

Ouput:

{'apple': 'red', 'banana': 'green', 'cherry': 'red', 'orange': 'orange'}

 

Removing Items : We can remove items from a dictionary using the del keyword or the pop() method.

  • del statement: Removes the item with the specified key.
  • pop( ) method: Removes and returns the value associated with a specified key.

 

Examples:

# Using del to remove a key-value pair

del fruit_colors["cherry"]

 

# Using pop() to remove a key-value pair and get the value

removed_value = fruit_colors.pop("apple")

 

print(fruit_colors)  # Output: {'banana': 'green', 'orange': 'orange'}

print("Removed value:", removed_value)  # Output: Removed value: red

 

Accessing All Keys, Values, and Items

  • keys( ) method: Returns a view object containing all the keys.
  • values( ) method: Returns a view object containing all the values.
  • items( ) method: Returns a view object containing all the key-value pairs as tuples.

 

Examples:

fruit_colors = {"apple": "red", "banana": "yellow", "cherry": "red"}

 

# Accessing all keys

print(fruit_colors.keys())  # Output: dict_keys(['apple', 'banana', 'cherry'])

 

# Accessing all values

print(fruit_colors.values())  # Output: dict_values(['red', 'yellow', 'red'])

 

# Accessing all items (key-value pairs)

print(fruit_colors.items())  # Output: dict_items([('apple', 'red'), ('banana', 'yellow'), ('cherry', 'red')])

 

 

Dictionary length : To determine the numbers of key:values present in the dictionary, len() function is used.

Example:

# A dictionary of fruits and their colors

fruit_colors = {"apple": "red", "banana": "yellow", "cherry": "red", "orange": "orange"}

 

# Getting the length of the dictionary

length = len(fruit_colors)

print("Length of the dictionary:", length)

 

Looping through Dictionary: We can loop through the dictionary using the for loop to print all the elements one by one.

Examples:

fruit_colors = {"apple": "red", "banana": "yellow", "cherry": "red", "orange": "orange"}

 

# Looping through dictionary keys

for key in fruit_colors:

    print(key)

 

# Looping through dictionary values

for value in fruit_colors.values():

    print(value)

 

# Looping through key-value pairs

for key, value in fruit_colors.items():

    print(f"Key: {key}, Value: {value}")

 

# Looping through with index

for index, (key, value) in enumerate(fruit_colors.items()):

    print(f"Index {index}: Key = {key}, Value = {value}")

 

 

 

Dictionary Comprehension : Just like list comprehension, we can also use dictionary comprehension to create dictionaries.

Syntax:

{key: value for key, value in iterable if condition}

 

Example:

# Creating a dictionary with squares of numbers

squares = {x: x**2 for x in range(5)}

print(squares)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

 

Nested Dictionaries : A dictionary can contain other dictionaries as values, creating nested dictionaries.

Example:

# A dictionary with nested dictionaries

students = {

    "John": {"age": 25, "grade": "A"},

    "Anna": {"age": 22, "grade": "B"},

}

 

# Accessing nested dictionary values

print(students["John"]["age"])  # Output: 25

print(students["Anna"]["grade"])  # Output: B

 

Checking if a Key Exists : We can check if a key exists in a dictionary using the in keyword.

 

Example:

fruit_colors = {"apple": "red", "banana": "yellow", "cherry": "red"}

# Checking if a key exists

if "apple" in fruit_colors:

    print("Apple is in the dictionary")

 

Merging Dictionaries : We can merge two dictionaries using the update() method or the | operator (Python 3.9+).

  • Using update(): Merges another dictionary or iterable of key-value pairs into the original dictionary.
  • Using | operator (Python 3.9+): Combines two dictionaries into a new one.

 

Examples:

# Using update()

dict1 = {"apple": "red", "banana": "yellow"}

dict2 = {"cherry": "red", "orange": "orange"}

dict1.update(dict2)

print(dict1)  # Output: {'apple': 'red', 'banana': 'yellow', 'cherry': 'red', 'orange': 'orange'}

 

# Using | operator (Python 3.9+)

dict3 = dict1 | dict2

print(dict3)  # Output: {'apple': 'red', 'banana': 'yellow', 'cherry': 'red', 'orange': 'orange'}

 

Dictionary Methods : Here are some common dictionary methods:

 

  • clear() — Removes all items from the dictionary.
  • copy() — Returns a shallow copy of the dictionary.
  • fromkeys() — Creates a dictionary with specified keys and a default value.
  • get() — Returns the value for a key, or None if the key doesn't exist.
  • pop() — Removes and returns the value for a specified key.
  • popitem() — Removes and returns a random key-value pair.
  • setdefault() — Returns the value of a key, and if the key doesn’t exist, inserts it with a default value.

 

Example:

fruit_colors = {"apple": "red", "banana": "yellow", "cherry": "red"}

 

# Using popitem()

item = fruit_colors.popitem()

print(item)  # Output: ('cherry', 'red')

print(fruit_colors)  # Output: {'apple': 'red', 'banana': 'yellow'}

 

7.15 Uses of Library functions : String Functions (center, upper, lower, Len), Numeric and mathematical (sum, pow, round, abs, sqrt, Int)

7.13 Iteration (for and while) | Grade 9 New Curriculum Computer Science 2082

 


7.13 Iteration (for and while)

Iteration is the process of repeating a block of code multiple times until a specified condition is satisfied.

 

Types of iterations

·       for loop

·       while loop

 

For Loop

A for loop in Python is a control flow structure that allows to iterate over a sequence (like a list, tuple, string) or a range of numbers.

It is used when we know in advance how many times we want to execute a statement or a block of statements.

 

Syntax:

for variable in sequence:

    # Code to execute

 

Example:

# Iterating over a range of numbers from 0 to 4

for i in range(5):

    print(i)

 

Example:

#Using for loop to print “jump” five times

for x in range(5):

     print(“Jump!”)

 

Example:

# Iterating over a list

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

    print(fruit)

 

While Loop

“While loop” in Python is a control structure that allows to repeatedly execute a block of code as long as certain conditions remain true.

Syntax:

while condition:

    # Code to execute

 

Example:

# Using while loop to print numbers from 0 to 4

i = 0

while i < 5:

    print(i)

    i += 1  # Incrementing the value of i to avoid infinite loop

 

pass Statement

·       In Python, the pass keyword is a null operation or a no-operation statement.

·       It acts as a placeholder where some code is required but no action is necessary.

·       It is often used when a statement is required by Python syntax, but you don’t want to execute any code.

 

Syntax:

if condition:

    # Some code here

else:

    pass # Nothing happens in the “else” case

 

Example:

for i in range(5):

    if i == 2:

        pass  # Do nothing if i is 2

    else:

        print(i)

 

Output:

0

1

3

4

 

In this example, when i is equal to 2, the pass statement is executed, which does nothing, so the loop continues without printing 2.

 

 

 

 

continue Statement

·       In Python, the continue keyword is used in loops (such as for or while loops).

·       It is used to skip the rest of the code inside the loop for the current iteration and move on to the next iteration.

·       It allows us to bypass certain parts of the loop based on a condition without exiting the loop entirely.

 

Example:

 

for i in range(5):

    if i == 2:

        continue  # Skip the rest of the code when i is 2

    print(i)

 

Output:

 

0

1

3

4

 

Here, when i == 2, the continue statement skips the print(i) and moves to the next iteration of the loop, so 2 is not printed.

 

break Statement

·       In Python, the break keyword is used in loops (such as for or while loops) to exit the loop early, even if the loop’s condition hasn’t been fully satisfied.

·       It allows us to terminate the loop based on a certain condition.

 

Example:

 

for i in range(5):

    if i == 3:

        break  # Exit the loop when i is 3

    print(i)

 

Output:

 

0

1

2

 

In this case, when i == 3, the break statement causes the loop to terminate, and no further numbers are printed.