LECTURE 1:
DATA STRUCTURE AND
INTRODUCTION TO PYTHON
SEHH2239 Data Structures
1
LEARNING OBJECTIVES:
• To overview the significance of data structure
• To review the elements in a python program
• To review the expressions, operators, and flow control in python
programs
• To declare list structure and access list elements
2
DATA STRUCTURE
• Data
• can be defined as a representation of facts, concepts, or instructions in a formalized
manner.
• Data is represented with the help of characters such as alphabets (A-Z, a-z), digits (0-9) or
special characters (+,-,/,*,<,>,= etc.)
• A data structure is a specialized format for
• organizing data,
• processing data,
• retrieving data and
• storing data.
• In computer programming, a data structure may be selected or designed to store
data for the purpose of working on it with various algorithms.
• Each data structure contains information about the data values, relationships between
the data and functions that can be applied to the data. 3
IMPORTANCE OF DATA STRUCTURES
• Data structures are essential for managing large amounts of data, such as
information kept in databases or indexing services, efficiently.
• Proper maintenance of data systems requires the identification of memory
allocation, data interrelationships and data processes, all of which data
structures help with.
• Choosing an ill-suited data structure could result in slow runtimes or
unresponsive code.
• A few factors to consider when picking a data structure include
• what kind of information will be stored,
• where should existing data be placed,
• how should data be sorted and
• how much memory should be reserved for the data
4
DATA STRUCTURE CLASSIFICATION
https://bcastudyguide.wordpress.com/unit-1-introduction-to-data-structure-and-its-characteristics/
5
OVERVIEW OF TYPES OF DATA STRUCTURES
Primitive and non-primitive
• Primitive are predefined types of data supported by the
programming language.
• For example, integers, float numbers, and characters are all primitive data
types. E.g. 3, 0.45, s, ^,…
• Non-primitive are not defined by the programming language
but are instead created by the programmer.
• They are sometimes called "reference variables" or "object references"
since they reference a memory location, which stores the data.
6
INTRODUCTION TO
PYTHON
7
WHAT IS PYTHON?
• Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
• It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.
• What can Python do?
• Python can be used on a server to create web applications.
• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software
development.
8
https://www.w3schools.com/python/python_intro.asp
HELLO WORLD IN PYTHON
• In Google colab
• https://colab.research.google.com/notebooks/
print(“Hello World!”)
• In IDE (e.g. PyCharm)
• Save it as helloWorld.py
9
PYTHON EXPRESSIONS AND
OPERATORS
10
Hello my name is John
Hello my name is John
COMPONENTS OF A PYTHON PROGRAM
• Executable statements are placed in functions
• Known as methods, that belong to class definitions.
class Person:
def __init__(self, name):
self.name = name
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John")
p1.myfunc()
>>Hello my name is John
11
https://www.w3schools.com/python/python_classes.asp
EXPRESSIONS AND OPERATORS
• The semantics of an operator depends upon the type of its
operands.
• For example
1. a and b are numbers, the syntax a + b indicates addition
2. a and b are strings, the operator + indicates concatenation
• Assignment Operator (=)
= is used in python to assign values to variables
12
NUMBERS IN PYTHON
• Different numeric types in
Python: To view the number type:
• Int print(type(x))
>><class 'int’>
• x = 5
print(type(y))
• Float >><class 'float’>
• y =3.46
print(type(z))
• Complex >><class 'complex’>
• z = 2 + 5j
To print the number:
• Scientific numbers print(m)
• m = 2e5 >> 200000.0
• n= 3.53E4 print(n) 13
>>35300.0
STRINGS
• Both “” or ‘’ can be used to quote strings
• a="ABC"
• b1='dddggg lll llll .adf'
• c_dfasdf_='123123’
• d="'swing swimming so many medals add oil!’”
To print the string
print(a[2])
>> C
print(d)
>>'swing swimming so many medals add oil!'
14
STRINGS
• Get a character from a string • Search in a string
print(a[2]) print("silver" in d)
>>C >>False
• String length
if "medals" in d:
print(len(a))
print("yes, found")
>>3
>>yes, found
print(len(b1))
>>20
• Slicing
print(b1[3:8])
>>ggg l
15
ESC APE CHARACTERS
Escape Sequence Meaning
• Allows you to use
\newline Backslash and newline ignored
some special
characters \\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
print("\t\"hello world\"") \b ASCII Backspace (BS)
>> "hello world" \f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\v ASCII Vertical Tab (VT)
\ooo Character with octal value ooo
16
\xhh Character with hex value hh
C ASTING OF NUMBERS
• Casting in python is done by constructor functions:
• int() - constructs an integer number from an integer literal, a float literal
(by removing all decimals), or a string literal (providing the string
represents a whole number)
• float() - constructs a float number from an integer literal, a float literal or a
string literal (providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including
strings, integer literals and float literals
x = 5.5
y = int(x)
print(y)
17
>>5
ARITHMETIC OPERATORS
• Python supports the following arithmetic operators:
• If both operands have type int, then the result is an int
• If one or both operands have type float, the result is a float.
• Floor division has its result truncated.
Try this: operators.ipynb
https://www.w3schools.com/python/python_operators.asp 18
INCREMENT AND DECREMENT OPS
• Python does not have unary increment/decrement operator
(++/--). Instead to increment a value, use
a=2
a += 1
print(a)
>>3
19
COMPARISON AND LOGICAL OPERATORS
• Python supports the following comparison operators for
values, which result in Boolean values:
• x < y
• S == “abc”
• b1 != True
• Boolean values also have the following logical operators:
• x < y and S == “abc”
• not (x < y)
• (S == “abc” or b1 != True)
20
PYTHON INDENTATION
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code is
for readability only, the indentation in Python is very important.
• Python uses indentation to indicate a block of code.
y = 14
if y<5:
print("this line run when true")
print("this line run anyway")
>>this line run anyway
21
FLOW CONTROL
22
IF STATEMENTS
• The syntax of a simple if statement is as follows:
x=5
y=13
if y>x:
print("y is greater.")
>>y is greater.
• if…else…
y=2
if y>x:
print("y is greater.")
else:
print("y is not greater.")
>>y is not greater. 23
COMPOUND IF
• There is also a way to group a number of boolean tests, as follows:
if firstBooleanExp: if y>x:
firstBody print("y is greater.")
elif secondBooleanExp: elif y==x:
secondBody print("they are equal.")
else: else:
thirdBody print("y is smaller.")
• Short-hand if...else (Ternary Operator)
variable = expressionTrue if condition else expressionFalse
# Python Ternary Operator
ylarge = True if y >x else False 24
WHILE LOOPS
• Such a loop tests that a certain condition is satisfied and will perform the body
of the loop each time this condition is evaluated to be true.
• The syntax for such a conditional test before a loop body is executed is as
follows:
while booleanExpression:
loopBody
>>
i=1
1
while i<6: 2
print(i) 3
i+=1 4
5
25
BREAK AND CONTINUE
• break statement that immediately terminate a while or for loop when
executed within its body.
a = 3
while a < 7: >>
print(a) 3
if a == 4: 4
break
a += 1
• continue statement that causes the current iteration of a loop body to
stop, but with subsequent passes of the loop proceeding as expected.
a = 3 >>
while a < 7: 4
a +=1 6
if a == 5: 7
continue 26
print(a)
FOR LOOPS
• A for loop is used for iterating over a sequence (that is
either a list, a tuple, a dictionary, a set, or a string).
• The basic structure is as follows:
for counter in range(m, n)
loopBody
>>
for i in range(0, 4): 0
print(i) 1
2
3
27
VARIABLE NAMES IN PYTHON
• Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
28
KEYWORDS IN PYTHON
• Keywords in Python are reserved words that cannot be used as a variable
name.
help("keywords")
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
29
SUMMARY OF KEY TERMS
• Data Structure
• Basic Python
• Expressions and Operators
• Arithmetic
• Logical
• Comparison
• Flow Control
• if
• while
• for 30
REFERENCES:
• Textbook:
• Adam Drozdek, Data Structures and Algorithms in
Python , 1st Edition, Cengage Learning, 2021
• References
• https://www.tutorialspoint.com/computer_fundamentals/compu
ter_data.htm
• https://searchsqlserver.techtarget.com/definition/data-structure
• https://www.w3schools.com/python/
• https://www.geeksforgeeks.org/array-copying-in-python/
31