0% found this document useful (0 votes)
6 views52 pages

Module4 - Types and Operations

Uploaded by

Blossomlove12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
6 views52 pages

Module4 - Types and Operations

Uploaded by

Blossomlove12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 52

COMPUTER PROGRAMMING I

Types and Operations

COURSE CODE:
(COS201)

COURSE LECTURERS

1 Dr. Olaniyan Deborah


2 Dr. Julius Olaniyan

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.

 Python has five standard data types. They are:


1. Numeric Types
 int: Integer values (e.g., 10, -3)
 float: Floating-point numbers (e.g., 3.14, -0.5)
 complex: Complex numbers (e.g., 3+5j)
2. Sequence Types
 str: String, a sequence of characters (e.g., "hello")
 list: Ordered, mutable collection (e.g., [1, 2, 3])
 tuple: Ordered, immutable collection (e.g., (1, 2, 3))
4
DATA TYPES
 3. Mapping Type
 dict: Key-value pairs, mutable (e.g., {"name": "Alice", "age":
25})
4. Set Types
 set: Unordered collection of unique elements (e.g., {1, 2, 3})
 frozenset: Immutable set (e.g., frozenset([1, 2, 3]))
5. Boolean Type
 bool: Represents True or False values
6. None Type
5
 NoneType: Represents the absence of a value, None
NUMERIC DATA TYPES
 A Python numeric data type is used to hold numeric values.
Example:
 1. int - holds signed integers of non-limited length.
 2. long- holds long integers (exists in Python 2.x, deprecated in Python 3.x).
 3. float- holds floating precision numbers, and it's accurate up to 15
decimal places.
 4. Complex- holds complex numbers.

 Usually, in the Python language, we need not declare a data type


during variable declaration as we do in languages like C or C++.
Rather, we simply assign values to the variable. However, to see
the exact type of numerical value it is holding, we can use type().
6
NUMERIC DATA TYPES
 Example 1: To create a variable “a” to hold an integer value “100”,
we use the following line python line of code:
 a = 100
 To view the exact type of numeric value for valuable "a", we use
the following Python code:
 print("The type of variable having value", a, " is ", type(a))
 Example 2: To create a variable with a floating point value, we
can use the following code snippet:
 b = 10.2345
 and to view the type of numeric value for valuable "b", we use the
following Python code:
 print("The type of variable having value", b, " is ", type(b))
7
NUMERIC DATA TYPES
 Example 3: To create a variable with a complex value, we can use
the following code snippet:
 c = 100+3j
 and to view the type of numeric value for valuable "c", we use the
following Python code:
 print("The type of variable having value", c, " is ", type(c))

 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"

# Triple quotes for multiline strings


multiline_string = '''
This is a multiline string
in Python.
'''

Dec-24 Programming 11
ACCESSING CHARACTERS

 You can access individual characters of a string using


indexing, with the first character having index 0.
my_string = "Python"
print(my_string[0]) # Output: P
print(my_string[-1]) # Output: n (last character)

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.

my_string = "Python Programming"


substring = my_string[0:6] # Get the substring from
index 0 to 5
print(substring) # Output: Python

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!"

 print(my_string.upper()) # Output: " HELLO, WORLD! “

 print(my_string.lower()) # Output: " hello, world! "

 print(my_string.split(",")) # 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.

# Using join() to concatenate list elements into a single


string
words = ["Hello", "world", "Python"]
joined_string = " ".join(words) # Join elements with space
as separator
print(joined_string) # Output: "Hello world Python"
Dec-24 Programming 19
FIND() METHOD
 The find() method returns the index of the first
occurrence of a substring within the string. If the
substring is not found, it returns -1.
 # Using find() to find the index of a substring
 sentence = "Python is an amazing language"

 index = sentence.find("amazing")

 print(index) # Output: 13 (index of the start of "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"

 new_sentence = sentence.replace("amazing", "awesome")

 print(new_sentence) # Output: "Python is an awesome


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.

 print(mList [0]) # Output: 1


 print(mList [-1]) # Output: 5 (last element)
LIST METHODS
 Python provides a variety of built-in methods for working with lists, such as
append(), extend(), insert(), remove(), pop(), index(), count(), sort(), reverse(),
etc.
 my_list.append(6) # Append an element
 print(my_list) # Output: [1, 2, 3, 4, 5, 6]

 my_list.insert(2, 'abc') # Insert an element at index 2


 print(my_list) # Output: [1, 2, 'abc', 3, 4, 5, 6]

 my_list.remove('abc') # Remove the first occurrence of 'abc'


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

 my_list.sort() # Sort the list for descending order (my_list.sort(reverse=true)


 print(my_list) # Output: [1, 2, 3, 4, 5, 6]
LIST COMPREHENSIONS
 List comprehensions provide a concise way to create
lists.
squared_numbers = [x**2 for x in range(1, 6)]
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
TUPLES
 Tuples are similar to lists, but they are immutable
(cannot be modified after creation) and are created
using parentheses ().
 my_tuple = (1, 2, 3, 4, 5)
 Accessing Elements:
 You can access elements of a tuple using indexing, similar to lists.
 print(my_tuple[0]) # Output: 1

 print(my_tuple[-1]) # Output: 5 (last element)


TUPLE METHODS
 Tuples have fewer methods compared to lists because
they are immutable. However, they have methods like
count() and index().
 print(my_tuple.count(3)) # Output: 1 (count occurrences of 3)
 print(my_tuple.index(4)) # Output: 3 (index of the first occurrence
of 4)
TUPLE PACKING AND UNPACKING
 You can pack multiple values into a tuple and unpack
them into individual variables.

 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)

 Removing Elements: Use the remove() or discard()


method to remove elements from a set. The difference
between them is that remove() will raise an error if the
element is not present, while discard() won't.
 my_set.remove(2)
 my_set.discard(2)

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}

 This will achieve the same result as using the set()


function but in a more concise way.

Dec-24 Programming 35
DICTIONARIES

 Dictionaries in Python are unordered collections


of items.
 Each item in a dictionary is a key-value pair.
 Dictionariesare mutable, meaning you can add,
modify, or delete items from them.
 Dictionaries are defined using curly braces {}, and items are
separated by commas. Each item has a key and a value
separated by a colon :

Dec-24 Programming 36
CREATING DICTIONARIES

 You can create a dictionary by enclosing key-


value pairs within curly braces {}.
 my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
 Accessing Items:
 You can access the value associated with a key using square brackets [].
 print(my_dict['name']) # Output: John
 Adding or Modifying Items:
 You can add new items or modify existing ones by assigning values to
keys.
 my_dict['occupation'] = 'Engineer'
 my_dict['age'] = 31

Dec-24 Programming 37
REMOVING ITEMS

 You can remove items from a dictionary


using the del keyword or the pop()
method.
 del my_dict['city']
 my_dict.pop('age')

 Iterating Over Dictionaries


 You can iterate over dictionaries using a for loop.
 for key, value in my_dict.items():
 print(key, value)

Dec-24 Programming 38
DICTIONARY METHODS
 Python provides several methods to
manipulate dictionaries, such as keys(),
values(), items(), get(), etc.

 keys = my_dict.keys() # Returns a view object of all keys


 values = my_dict.values() # Returns a view object of all values

 items = my_dict.items() # Returns a view object of all key-value

pairs

Dec-24 Programming 39
OPERATIONS ON DICTIONARIES
Operation Meaning

len(d) Number of key:value pairs in d


d.keys() List containing the keys in d
d.values() List containing the values in d
k in d True if key k is in d
d[k] Value associated with key k in d
d.get(k, v) If k is present in d, then d[k] else v
d[k] = v Map the value v to key k in d
(replace d[k] if present)
del d[k] Remove key k (and associated value) from d
Dec-24 Programming 40
CREATING DICTIONARY FROM A SEQUENCE
 What is a Sequence?

 In Python, a sequence is an ordered collection


of items.
 Sequences can be finite or infinite.
 Common examples of sequences include:
 lists;
 tuples;
 strings; and
 range objects.
CHARACTERISTICS OF SEQUENCES
1. Ordered: The elements in a sequence have a defined order, which means
you can access them by their position (index).

2. Indexing: Each item in a sequence is assigned an index, starting from 0


for the first item, 1 for the second, and so on.

3. Iteration: You can iterate over the elements of a sequence using loops (e.g.,
for loop).

4. Immutable vs. Mutable: Sequences can be either immutable (cannot be


changed after creation) or mutable (can be changed). For example, tuples
and strings are immutable, while lists are mutable.

5. Homogeneous or Heterogeneous: Sequences can contain elements of


the same type (homogeneous) or different types (heterogeneous).
EXAMPLES OF SEQUENCES
 Lists: Ordered collections of items, mutable.
 Tuples: Ordered collections of items, immutable.

 Strings: Ordered collections of characters, immutable.

 Range objects: Represents a sequence of numbers,


typically used in loops.
EXAMPLES OF SEQUENCES
 # List
 my_list = [1, 2, 3, 4, 5]

 # 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

Boolean Type (bool)


 Definition: Represents one of two values, True
or False.
 Usage: Booleans are often used in conditional
statements and to represent the outcome of
comparisons.
 Creation: True and False are keywords in
Python and are case-sensitive.
48
BOOLEAN TYPE

# Basic Boolean values


is_active = True
is_closed = False

# Using Booleans in a condition


if is_active:
print("The system is active.") # This will print because
is_active is True

# Boolean from a comparison


result = (5 > 3) # result will be True
49
print(result) # Output: True
NONETYPE IN PYTHON

 NoneType is the type of the singleton object None


in Python. It represents the absence of a value or
a null value.
 Key Points:
 None is an actual object in Python, not a keyword.
 It's used to signify "nothing" or "no value here."
 It is immutable, and there is only one instance of
None in a Python program.
50
NONETYPE IN PYTHON
 NoneType is the type of the singleton object None
in Python. It represents the absence of a value or
a null value.
 Key Points:
 None is an actual object in Python, not a keyword.
 It's used to signify "nothing" or "no value here."
 It is immutable, and there is only one instance of
None in a Python program.
 Example:
 x = None
 print(type(x)) # Output: <class 'NoneType'> 51
USE CASES OF NONETYPE IN PYTHON
def greet(name=None):
if name is None:
return "Hello, stranger!"
return f"Hello, {name}!"

print(greet()) # Output: Hello, stranger!


print(greet("Alice")) # Output: Hello, Alice!

52

You might also like