User-Defined Data Types
Example Pre-Determined Data Types in Python
int: Represents whole numbers (e.g., 10, -5, 0)
o Limitation: Cannot store fractional values.
o Solution: Use float for decimal numbers.
float: Represents numbers with decimal points (e.g., 3.14, -0.5)
o Limitation: Limited precision due to how floating-point numbers are stored in
memory.
o Solution: For very high precision calculations, consider using libraries like
decimal.
str: Represents text data (e.g., "Hello", "Python")
o Limitation: Can be inefficient for very large amounts of text data.
o Solution: Explore more efficient text processing libraries like re (for regular
expressions) or consider using external databases for large text datasets.
bool: Represents logical values (True or False)
o Limitation: Can only hold two values.
o Solution: For more than two states, use an enum (if available in your
language) or create a custom class.
Addressing Limitations
Multiple Variables/Arrays:
o If you need to store multiple values of the same type, use arrays (lists in
Python) to efficiently store and access them.
o For example, to store a list of temperatures: temperatures = [25.5, 28.2,
22.1]
Classes:
o For more complex data structures, create custom classes. This allows you to
group related data and methods together, providing better organization and
encapsulation.
o For example, to represent a person:
Python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Libraries and External Tools:
o Utilize specialized libraries for specific data types or operations. For example,
use numpy for efficient numerical computations or pandas for data analysis.
o Consider using external databases (like SQL databases) for storing and
managing large datasets.
Discussion Points:
When would you choose one data type over another?
How can you identify potential limitations of a data type in a given scenario?
What are the trade-offs between using built-in data types and creating custom data
structures?
How can you effectively use libraries and external tools to overcome data type
limitations?
Why User-Defined Types are Necessary
Enhanced Readability and Maintainability
o User-defined types allow you to create custom data structures that reflect the
specific needs of your problem. This makes your code more readable and
easier to understand, as the data types themselves become meaningful labels.
Improved Code Organization
o By grouping related data together into a single type, you can improve the
organization and modularity of your code. This makes it easier to manage and
modify your program as it grows.
Reduced Errors
o User-defined types can help you enforce data integrity by restricting the values
that can be assigned to variables. This can help prevent errors that might
otherwise occur if you were to use more generic data types.
Code Reusability
o Once you've defined a user-defined type, you can reuse it throughout your
program or even in other programs. This saves you time and effort, and helps
to ensure consistency in your code.
TYPE AWeek SUNDAY MONDAY TUESDAY WEDNESDAY
THURSDAY FRIDAY
SATURDAY
DECLARE today ΔWeek
a ctA NO Ca
fdafs dk fÑ
tommorow
today I
ff
ffy
y
Enn lists boolean
improvent
Pointer data store in computer memory
Non-Composite Data Types
Non-composite data types are user-defined data types that are not built from other data types.
They are typically used to represent a specific set of values or to provide more meaningful
names to data. Two common examples of non-composite data types are:
1. Enumerated Types LIST OF CONTENTS Extension
of Boolean
Definition: An enumerated type is a user-defined data type that consists of a list of
named constants, called enumerators. These enumerators represent the only possible
values that a variable of that type can hold.
Syntax Pseudocode Pointers
SimpliesTYPE TDay = (Monday, Tuesday, Friday, Saturday, Sunday) TYPEStrPointer STRIM
TYPE IntPointers INTEC
Refine unchangability
order
2. Pointers
initiati Definition: A pointer is a variable that stores the memory address of another variable.
This allows you to indirectly access and manipulate data stored in other memory
Thatdressof
locations.
mething
Candluble
Syntax
TYPE ptr = ^INTEGER
int* ptr; // Declare a pointer to an integer
int num = 10;
ptr = # // Assign the address of num to ptr
int myInteger = 10;
This line declares an integer variable named myInteger and assigns the value
10 to it.
TYPE integerPointer = ^INTEGER
This line declares a pointer variable named integerPointer. The ^ indicates
that it's a pointer to an integer.
Declaung variable
using
datatypepointer
TYPE StrPointe STRING
StrPointer
y
integerPointer ← &myInteger;
This line assigns the memory address of myInteger to the integerPointer. The &
operator is used to get the memory address of a variable.
int anotherInteger;
anotherInteger ← ^integerPointer;
This line declares another integer variable named anotherInteger.
^integerPointer dereferences the integerPointer, meaning it accesses the value
stored at the memory address pointed to by integerPointer.
Since integerPointer points to myInteger, the value of myInteger (which is 10) is
accessed.
Finally, the value 10 is assigned to the anotherInteger variable.
In summary:
We have an integer variable (myInteger) with a value of 10.
We have a pointer (integerPointer) that points to the memory location of
myInteger.
We use the dereference operator (^) to access the value stored at the memory location
pointed to by the pointer and assign it to another integer variable (anotherInteger).
Usage: Pointers are commonly used to:
o Create dynamic data structures like linked lists and trees.
o Pass arguments to functions by reference.
o Access memory directly for low-level operations.
1. Creating Dynamic Data Structures
Pointers are fundamental in building dynamic data structures such as linked lists,
trees, graphs, and more.
These structures allow you to allocate memory at runtime, making it possible to grow
or shrink the size of your data as needed.
For instance, in a linked list, each node contains a pointer to the next node, forming a
chain of elements.
2. Passing Arguments to Functions by Reference
When you pass an argument to a function by value, a copy of the argument is created
within the function's scope. Any changes made to the argument within the function do
not affect the original variable.
Pointers allow you to pass arguments by reference, meaning you're actually passing
the memory address of the variable. This enables the function to directly modify the
original variable's value.
This is useful when you want a function to change the value of a variable in the
calling context.
3. Accessing Memory Directly for Low-Level Operations
Pointers give you direct access to memory locations.
This is crucial for tasks like:
o Memory management: Allocating and deallocating memory blocks using
functions like malloc() and free().
o Hardware interaction: Interfacing with devices or hardware components that
require direct memory access.
o System programming: Implementing low-level system functions that operate
at the memory level.
Key Points:
Non-composite data types are fundamental building blocks in programming.
Enumerated types enhance code readability and maintainability by providing
meaningful names to constants.
Pointers offer powerful memory management and data manipulation capabilities.
Understanding non-composite data types is essential for effective programming in
various languages.
Composite Data Types
Composite data types, also known as compound data types or structured data types, are user-
defined data types that combine multiple individual data elements into a single unit. These
elements can be of different data types, allowing you to create complex structures to represent
real-world entities or relationships.
Common Composite Data Types:
1. Sets
Definition: A set is an unordered collection of unique elements. Elements in a set
cannot be duplicated.
Syntax
TYPE letters = SET OF CHAR
DEFINE vowel ('a', 'e', 'i', 'o', 'u') : letters
TYPE Color = STRING;
TYPE ColorSet = SET OF Color;
TYPE Color = STRING;: Defines a new data type Color to represent a single color as a
string.
TYPE ColorSet = SET OF Color;: Defines a new data type ColorSet to represent a set of
Color values.
# Define a set of colors
DEFINE PrimaryColors ('Red', 'Green', 'Blue') : ColorSet;
DEFINE PrimaryColors ('Red', 'Green', 'Blue') : ColorSet;: Defines a constant set
PrimaryColors containing the strings "Red", "Green", and "Blue". The : ColorSet part
specifies that this set is of the ColorSet type.
#Example usage:
PROCEDURE PrintColors(colorSet: ColorSet)
FOR EACH color IN colorSet
DO
PRINT color;
END FOR;
END PROCEDURE;
PROCEDURE PrintColors(colorSet: ColorSet): Defines a procedure named PrintColors that
takes a ColorSet as input.
The FOR EACH loop iterates through each color in the input colorSet.
Inside the loop, the PRINT statement displays the current color to the console.
# Call the procedure to print the colors
PrintColors(PrimaryColors);
PrintColors(PrimaryColors);: Calls the PrintColors procedure, passing the PrimaryColors set
as an argument.
2. Records
Definition: A record is a collection of fields, each of which can have a different data
type. It allows you to group related data together under a single name.
Syntax
TYPE
TPerson
firstName: STRING
lastName: STRING
age: INTEGER
ENDTYPE
3. Classes/Objects
Definition: Classes are blueprints for creating objects, which are instances of the
class. A class encapsulates both data (attributes) and the methods (functions) that
operate on that data.
Syntax
Key Points:
Composite data types are essential for organizing and representing complex data
structures.
Sets are useful for representing collections of unique elements.
Records provide a way to group related data fields together.
Classes and objects are fundamental concepts in object-oriented programming,
enabling data encapsulation and modularity.
Understanding composite data types is crucial for writing efficient and well-structured
programs.
Choosing and Designing User-Defined Data Types
When designing user-defined data types, consider the following:
What data needs to be represented?
What operations will be performed on the data?
How can the data be organized to make it easy to use and maintain?
Example:
writing a program to manage a library. You might define the following user-defined types:
TYPE TBook
title: string;
author: string;
ISBN: string;
ENDTYPE
TYPE TLibrary = ARRAY[1:50] OF TBook
This allows you to represent a library as a collection of books, each with its own title, author,
and ISBN.
By using user-defined data types effectively, you can write more efficient, readable, and
maintainable programs.
Composite vs. Non-Composite Data Types
Pseudocode
Non-Composite: Represents a single, atomic value.
o Examples:
INTEGER
BOOLEAN (True/False)
CHARACTER
ENUMERATED (e.g., COLOR = {RED, GREEN, BLUE})
Composite: Combines multiple data elements into a single unit.
o Examples:
ARRAY (a collection of elements of the same data type)
RECORD (a collection of fields, each with a different data type)
STRUCT (similar to RECORD, often used in C/C++)
CLASS (encapsulates data and methods that operate on the data)
Chosen Language: Python
Non-Composite:
o int: Represents whole numbers (e.g., 10, -5, 0)
o float: Represents numbers with decimal points (e.g., 3.14, -0.5)
o str: Represents text data (e.g., "Hello", "Python")
o bool: Represents logical values (True or False)
Composite:
o list: An ordered collection of elements (can contain elements of different
data types)
o tuple: An ordered, immutable collection of elements
o dict: An unordered collection of key-value pairs
o set: An unordered collection of unique elements
Need for Both Types
Non-Composite:
o Foundation: They are the basic building blocks for all other data structures.
o Simplicity: Represent fundamental concepts like numbers, characters, and
logical values.
Composite:
o Organization: Group related data together, improving code readability and
maintainability.
o Efficiency: Provide efficient ways to store and access collections of data.
o Flexibility: Allow you to create complex data structures that accurately model
real-world entities.
Example:
Non-Composite: To represent the status of a light: light_status = "ON"
Composite: To represent a person:
Python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 30)
In this example, name and age are non-composite data types (likely str and int), while
Person is a composite data type (a class) that combines these attributes.
In Summary
Non-composite data types provide the foundation, while composite data types allow you to
build more complex and meaningful representations of information within your programs.
Imagine you are creating a program to manage a zoo.
Data Items:
1. Animal Species: (e.g., Lion, Tiger, Elephant)
2. Animal Names: (e.g., Simba, Rani, Tusker)
3. Animal Ages: (e.g., 5, 8, 12)
4. Enclosure Numbers: (e.g., 1, 2, 3)
5. Diet: (e.g., Carnivore, Herbivore, Omnivore)
6. Number of Animals in Each Species: (e.g., 3 lions, 2 tigers, 1 elephant)
7. Veterinary Checkup Dates: (e.g., "2024-11-15", "2024-12-20")
Questions:
For each data item or series of items listed above, determine whether:
Non-composite data types would be sufficient.
Composite data types would be more appropriate.
Justify your choices.
Further Discussion:
Composite Data Type Example:
o Animal:create a class to represent an animal:
Python
class Animal:
Benefits of Composite Data Types:
o Organization: Group related information about an animal (species, name,
age, etc.) into a single unit.
o Reusability: Easily create multiple animal objects with different properties.
o Data Integrity: Ensure that all relevant information about an animal is kept
together.
The program code below already has a range of user-defined data types written. Use these to create a
given program.
Python
# User-defined data types
class Book:
def __init__(self, title, author, isbn):
self.title = title
self.author = author
self.isbn = isbn
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def find_book_by_title(self, title):
for book in self.books:
if book.title == title:
return book
return None
# Program using user-defined data types
if __name__ == "__main__":
my_library = Library()
book1 = Book("The Lord of the Rings", "J.R.R. Tolkien",
"9780261102354")
book2 = Book("1984", "George Orwell", "9780452284240")
my_library.add_book(book1)
my_library.add_book(book2)
search_title = input("Enter book title to search: ")
found_book = my_library.find_book_by_title(search_title)
if found_book:
print(f"Book found: {found_book.title} by {found_book.author}")
else:
print("Book not found.")
Instructions for Learners:
1. Understand the Code:
o Analyze the provided code, paying close attention to the Book and Library
classes.
o Identify the attributes and methods of each class.
o Understand how the add_book and find_book_by_title methods work.
2. Modify the Code:
o Enhance Book Class: Add new attributes to the Book class, such as genre,
publication_year, or available_copies.
o Implement New Library Methods:
Create a method to remove a book from the library.
Create a method to display all books in the library.
Create a method to find books by author.
Create a method to check if a book is currently available.
3. Test and Improve:
o Write test cases to ensure that your modified code works as expected.
o Refactor the code for better readability and maintainability (e.g., by using
more descriptive variable names).
Learning Objectives:
Understanding and Using Classes: gain experience in creating and using classes to
represent real-world objects.
Object-Oriented Programming Concepts: learn about concepts like encapsulation
(grouping data and methods within a class), abstraction (hiding implementation
details), and inheritance (if applicable).
Code Reusability: understand how to reuse user-defined data types in different parts
of a program.
Problem-Solving: apply your knowledge to solve a practical problem (library
management) using object-oriented principles.
This exercise provides a hands-on approach to learning about user-defined data types and
their applications in real-world programming scenarios.
Scenario:
You are creating a program to manage a music library.
Requirements:
The program should be able to store information about each song in the library.
Each song should have the following attributes:
o Title: (e.g., "Bohemian Rhapsody")
o Artist: (e.g., "Queen")
o Album: (e.g., "A Night at the Opera")
o Genre: (e.g., "Rock", "Pop", "Classical")
o Duration: (e.g., "5:55")
The program should allow users to:
o Add new songs to the library.
o Search for songs by title, artist, or genre.
o Display a list of all songs in the library.
Task for Learners:
1. Design a user-defined data type (e.g., a class) to represent a song.
o Include the attributes mentioned above in the data type.
o Consider any necessary methods for the song class (e.g., a method to display
song information).
2. Justify your choice of data type. Explain why you chose this particular data type and
how it helps to organize and manage the song information effectively.
Here are some examples of data types, their declarations, and classifications:
Non-Composite Data Types
Integer (int)
o Declaration: int age = 25;
o Data: 10, -5, 0, 2147483647 (maximum value for 32-bit integers)
o Type:
Primitive/Built-in: Represents whole numbers.
Float (float)
o Declaration: float pi = 3.14159;
o Data: 3.14, -0.5, 2.71828
o Type:
Primitive/Built-in: Represents real numbers with decimal points.
Character (char)
o Declaration: char initial = 'A';
o Data: 'a', 'Z', '!', '?'
o Type:
Primitive/Built-in: Represents a single character.
Boolean (bool)
o Declaration: bool is_raining = true;
o Data: true, false
o Type:
Primitive/Built-in: Represents logical values.
Enumerated Type (enum)
o Declaration: enum Color { Red, Green, Blue }; Color favoriteColor
= Red;
o Data: Red, Green, Blue (defined values)
o Type:
User-defined: Creates a new data type with a set of named constants.
Composite Data Types
Array
o Declaration: int numbers[5] = {1, 2, 3, 4, 5};
o Data: A collection of elements of the same data type.
o Type:
Structured: Holds multiple values of the same type.
Class (Python)
o Declaration:
Python
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
o Data: Encapsulates both data (attributes) and methods (functions) that operate
on the data.
o Type:
Structured: A blueprint for creating objects with specific properties
and behaviors.
Key Points:
Non-composite: Represents a single, atomic value.
Composite: Combines multiple data elements into a single unit.
Understanding these distinctions is crucial for effective data representation and
manipulation in programming.
Prompt for Learners:
Scenario:
You are given the following program code, which contains several errors related to data type
definitions and usage. Your task is to identify and correct these errors to make the program
work as intended.
Program Code (Python):
Python
class Student:
def __init__(self, name, age, grades):
self.name = name
self.age = age
self.grades = grades
def calculate_average(student):
total = 0
for grade in student.grades:
total += grade
return total / len(student.grades)
if __name__ == "__main__":
student1 = Student("Alice", 18, [90, 85, 92])
average_grade = calculate_average(student1)
print("Average grade:", average_grade)
Learning Objectives:
Identifying and correcting errors: practice identifying and fixing common errors
related to data type definitions and usage.
Understanding class definitions and object creation: reinforce your understanding
of how to create and use classes to represent real-world objects.
Data type validation: learn the importance of validating data types to prevent
unexpected behavior.
Code debugging: develop debugging skills by systematically analyzing and fixing
errors in the code.
Prompt:
Scenario: You are developing a program to manage a library's book inventory.
Task:
1. Identify the key information needed to represent a book in your program.
2. Design an appropriate user-defined data type (e.g., a class or struct) to store this
information.
3. Justify your choice of data type and its structure.
Solution:
1. Key Information:
Title: The book's title (string)
Author: The book's author(s) (string or a list of strings)
ISBN: The book's International Standard Book Number (string)
Genre: The book's genre (string or an enumerated type)
Available Copies: The number of available copies (integer)
2. User-Defined Data Type (Python Class):
Python
class Book:
def __init__(self, title, author, isbn, genre, available_copies):
self.title = title
self.author = author
self.isbn = isbn
self.genre = genre
self.available_copies = available_copies
3. Justification:
Encapsulation: The Book class encapsulates all the relevant information about a book
within a single unit, making it easier to manage and reuse.
Organization: Grouping the book attributes (title, author, etc.) within a class
improves code organization and readability.
Data Integrity: By defining the Book class, we ensure that all books in the library
have the same set of attributes, promoting data consistency.
Code Reusability: The Book class can be reused throughout the program whenever
we need to work with book information.
Additional Considerations:
Enumerated Type for Genre: For a more structured approach, you could define an
enum for the genre attribute:
from enum import Enum
class Genre(Enum):
Fiction = 1
NonFiction = 2
Mystery = 3
SciFi = 4 # ... other genres
class Book:
def __init__(self, title, author, isbn, genre: Genre,
available_copies):
# ... rest of the class
Methods: You can add methods to the Book class to perform operations on book
objects, such as:
o check_out() to decrement the number of available copies
o check_in() to increment the number of available copies
o display_info() to print the book's details
i
OMS
Write Pseudocode to define a
enumuted datatype Cars made up of
Merc Rage bmw and mini
Createpseudocodeto define a worker Relord
with id naw dob and gender
What is a user defined data type
Give 2 limitates of a user
defined data type
ffffpff.LT
into locatm
103
What is class
a
Implant one
in python
in
python
TYPE Cars 1 Mere Range BMV Mini
TYPE Worker
DECLARE id STRING
DECLARE name STRING
DECLARE dob DATE
DECLARE gender BOOLEAN
EMD TYPE
User defined data type
custom data structure
created by a developer to
solve a specific problem or
organize specific
data
Importance of user def dd
Code reusability
modularity
reduced errors
Linitating
increased complexity
poorly designed
UDTs make code less efficient
compatibility issues new UDTs
may not be compatible with some
versions of progeny languages
Class blueprint for creating
objects in Object Oriented
Progeny
class Cars
def init self brand color
self brand Ford
self color Blue
Pointes variables that store
thememoryaddress another
of
variable
DECLARE Man STRING
Have 2 Joe
TYPE Name
Ptr STRING
QN WRITE I sendode to prompt for details
for 3 workers to store the recolds
Hints
FOR 0 1 TO 3
DEILARE SteArrey ARRAY I 3 OF
WORKER
Ask
000
DECLARE stndArray ARRAY I 3
OF WORKER
FOR it 1 To 3
studArrey id input End
stud Array name a INPUT End
stud Array dob input 1 Emb
stud Array gut input Enter
NENT
Corrections
FOR I 1 To 3
studArreyfi id input End
stud Array i name a INPUT End
stud Aryre i dob input 1 Emb
stud Array if_gut input Enter
NEAT
Data represents video
Example
TYPE Clubmeet
DELARE F Name Stkille
DELARE 1 Name STRING
DELARE SDayAttended SchoolDay
DEGARE NonSDayAttend Weekend
END TYPE
BuildingRegister Building ID 1067
BuildingRegister BuildingGroup house
TYPE BuldingType house bungalow
apartment
form
DECLARE BuildingCroup BuildingType
p y pe
Unordered
sets
Classes
Pseudocode has PRIVATE and
PUBLIC Keywords
g
PRIVATE OwnerName STRING
Explain whythe properties have been
set to PRIVATE 2
attributes only be
so can accessed
by the class's own methods
to enforce encapsulation
ensure the attributes are hidden
File Organization
Organising files FileAccess Hashing
Organising files
Seniel File Organisation
addme s
sequence
file can be directed edited
Sequential File Organization
stored in order accordingto
value of the
key
to edit file update it we
first create a new version
to look for files we use
linear search
Random file Organisnh
d I f
record is
put in free
space
in a
file
we find records by
implementing hashing
algorithms
eg
Eaten
we use hashing to both
place
and access the recon'd's location
in the file
is possible
editing files directly
File Access 2
ways
A Sequential
linea search
a until Found The b
true
B direct access
use hash algorithms we don't pass through
1
p ng
anything else
Collision solutions
Be
Open Closed
linked lists Overflow area
For
retrial if the
indx searched doesn't
match the key the
overflow area is searched
Recordkey Hashval
y
1030 1
1050 0
1025 2
35 341
31 31
Floaty part numbers
fracts neg numbers
Num BFP
I Is ask.s
000110000
if I then neg
if o then post
It I
2 3
23
72
2s
I
4
Tti
7.25
fast's
It
1 1
119 It
63 9 1
f 2
a
xD
2
2 4
69,75
It hot
I
212 29
25612
2
24
2
2
1
65.25