Module4 - Types and Operations
Module4 - Types and Operations
COURSE CODE:
(COS201)
COURSE LECTURERS
First Semester
2024/2025 Session
OBJECTIVES
The objectives of the course are to:
1. explain the meaning of data typing in computer
programming.
2. describe the various data types in the Python
programming language.
3. exemplify data type declaration statements
using Python and assignment of appropriate
values.
4. explain Comma-separated-value (CSV) files and
5. demonstrate knowledge and operations on
Python files. 2
DATA TYPES
Data types are basically a classification or categorization of data items and
represent the kind of value that tells what operations can be performed on a
particular data set. Since everything is an object in Python programming, data
types are actually classes, and variables are instances (objects) of these classes.
Different languages, however, may use different data types or similar types
with different semantics. For example, a Python int represents an
arbitrary-precision integer with traditional numeric operators like
addition, subtraction, and multiplication. Java language, on the other
hand, represents the int data type as a set of 32-bit integers with
values ranging from −2,147,483,648 to 2,147,483,647. 3
DATA TYPES
Most programming languages also allow programmers to define additional
data types, usually by combining multiple elements of other types and
then defining the valid operations of the new data type.
Output
The type of variable having value 100 is <class ‘ int’>
The type of variable having value 10.2345 is <class ‘ class float’>
The type of variable having value (100+3j) is <class ‘ class complex’>
8
SEQUENCE TYPES
In Python, sequence types represent collections of
items that are ordered. The primary sequence types
are:
1. str (string),
2. list, and
3. tuple.
9
STRINGS
Strings in Python have type str
They represent sequence of characters
Python does not have a type corresponding to
character.
Strings are enclosed in single quotes(') or double
quotes(“)
Both are equivalent
Backslash (\) is used to escape quotes and special
characters
Dec-24 Programming 10
CREATING STRINGS
Immutable: Once created, it cannot be modified.
You can create strings in Python using single quotes ('), double quotes ("), or triple quotes (''' or """).
# Single quotes
single_quoted_string = 'Hello, World!'
# Double quotes
double_quoted_string = "Python Programming"
Dec-24 Programming 11
ACCESSING CHARACTERS
Dec-24 Programming 12
COMMON STRING OPERATIONS
Concatenation:
You can concatenate strings using the + operator.
string1 = "Hello"
string2 = "World"
concatenated_string = string1 + ", " + string2
print(concatenated_string) # Output: Hello, World
Dec-24 Programming 13
COMMON STRING OPERATIONS
Concatenation:
You can concatenate strings using the + operator.
string1 = "Hello"
string2 = "World"
concatenated_string = string1 + ", " + string2
print(concatenated_string) # Output: Hello, World
Dec-24 Programming 14
CONCATENATE AND REPEAT
InPython, + and * operations have special
meaning when operating on strings
• + is used for concatenation of (two) strings
• * is used to repeat a string, an int number of
time
• Function/Operator Overloading
Dec-24 Programming 15
LENGTH OF A STRING
len function gives the length of a string
You can find the length of a string using the len()
function.
Example:
my_string = "Python"
print(len(my_string)) # Output: 6
Dec-24 Programming 16
STRING SLICING
You can extract substrings using slicing.
Dec-24 Programming 17
STRING METHODS
Python provides a variety of built-in methods for
working with strings, such as upper(), lower(),
strip(), split(), join(), find(), replace(), etc.
my_string = " Hello, World! "
print(my_string.strip()) # Output: "Hello, World!"
Dec-24 Programming 18
JOIN() METHOD
The join() method joins the elements of an
iterable (such as a list) into a single string, with
the specified separator between each element.
index = sentence.find("amazing")
Dec-24 Programming 20
REPLACE() METHOD
The replace() method replaces all occurrences of a
substring in the string with another substring.
# Using replace() to replace occurrences of a substring
sentence = "Python is an amazing language"
Dec-24 Programming 21
STRING FORMATTING
You can format strings using the format() method.
name = “OreOluwa"
age = 20
message = "Hello, my name is {} and I am {} years
old.".format(name, age)
print(message) # Output: "Hello, my name is OreOluwa and I
am 20 years old."
Dec-24 Programming 22
F-STRINGS (FORMATTED STRING LITERALS)
Introduced in Python 3.6, f-strings provide a
more concise and readable way to format strings.
name = “OreOluwa"
age = 20
message = f"Hello, my name is {name} and I am {age}
years old."
print(message) # Output: "Hello, my name is Julius
and I am 22 years old."
Dec-24 Programming 23
CONCLUSION
Strings are fundamental data types in Python, and
understanding how to work with them effectively is
crucial. With the basics, common operations, and
string formatting covered in this tutorial, you should
now have a solid foundation for working with strings
in Python.
LISTS
Lists are ordered collections of items, and you can
create them using square brackets [].
mList = [1, 2, 3, 4, 5]
Accessing Elements
You can access elements of a list using indexing, with the
first element having index 0.
coordinates = (3, 4)
x, y = coordinates
print(x, y) # Output: 3 4
SETS
A set is an unordered collection of unique elements in
Python.
Sets are mutable, meaning you can add or remove items
from them.
Sets are defined using curly braces {}.
Creating Sets:
You can create a set by enclosing comma-separated values
within curly braces {}.
Example:
my_set = {1, 2, 3, 4, 5}
Dec-24 Programming 31
OPERATIONS ON SETS
Adding Elements: Use the add() method to add
elements to a set.
my_set.add(6)
Dec-24 Programming 32
OPERATIONS ON SETS CONT.
Union, Intersection, Difference: You can perform
various operations like union, intersection, and difference
on sets using corresponding methods or operators.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) # {1, 2, 3, 4, 5}
intersection_set = set1.intersection(set2) # {3}
difference_set = set1.difference(set2) # {1, 2}
Iterating Over Sets:
You can iterate over sets using a for loop.
for item in my_set:
print(item)
Dec-24 Programming 33
CREATING A SET FROM A SEQUENCE
To create a set from a sequence in Python, you can use
the set() function or set comprehension.
Using the set() Function:
You can directly pass the sequence to the set() function:
my_sequence = [1, 2, 3, 4, 5]
my_set = set(my_sequence)
This will create a set from the sequence my_sequence.
my_list = [1, 2, 3, 3, 4, 5, 5]
my_set = set(my_list)
print(my_set) # Output: {1, 2, 3, 4, 5}
duplicate elements in the list are automatically removed
Dec-24 Programming 34
CREATING A SET FROM A SEQUENCE
Using Set Comprehension:
You can also use set comprehension to create a set
from a sequence:
my_sequence = [1, 2, 3, 4, 5]
my_set = {x for x in my_sequence}
Dec-24 Programming 35
DICTIONARIES
Dec-24 Programming 36
CREATING DICTIONARIES
Dec-24 Programming 37
REMOVING ITEMS
Dec-24 Programming 38
DICTIONARY METHODS
Python provides several methods to
manipulate dictionaries, such as keys(),
values(), items(), get(), etc.
pairs
Dec-24 Programming 39
OPERATIONS ON DICTIONARIES
Operation Meaning
3. Iteration: You can iterate over the elements of a sequence using loops (e.g.,
for loop).
# Tuple
my_tuple = ('a', 'b', 'c', 'd')
# String
my_string = "Hello, World!"
# Range object
my_range = range(5) # Generates numbers from 0 to 4
BUILDING DIC FROM SEQUENCES
Using Loops:
You can iterate over the sequence and build the dictionary
manually:
sequence = ['a', 'b', 'c', 'd']
my_dict = {}
for index, value in enumerate(sequence):
my_dict[index] = value
print(my_dict)
This will output:
{0: 'a', 1: 'b', 2: 'c', 3: 'd'}
BUILDING DIC FROM SEQUENCES
Using Dictionary Comprehension:
You can also use dictionary comprehension to achieve
the same result in a more concise way:
sequence = ['a', 'b', 'c', 'd']
my_dict = {index: value for index, value in enumerate(sequence)}
print(my_dict)
BUILDING DIC FROM SEQUENCES
Using zip() Function:
If you have two sequences, one for keys and one for
values, you can use the zip() function to combine them
into pairs and then create a dictionary:
keys = ['name', 'age', 'city']
values = ['John', 30, 'New York']
my_dict = dict(zip(keys, values))
print(my_dict)
Output:
{'name': 'John', 'age': 30, 'city': 'New York'}
BOOLEAN TYPE
52