0% found this document useful (0 votes)
28 views33 pages

ELEC423 - Tutorial 05

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 33

The Internet of Things:

Architecture and Applications


(ELEC423)
Dr Valerio Selis

[email protected]
Shell scripting
Strings

• Basic operation with strings:


• Obtain the string length:
${#name}
• Convert the string as a list of words:
${name}
• Extract the substring of length (LEN) from a string
starting after a specified position (POS):
${name:$POS:$LEN}
The length is optional, if omitted, it will extract the
substring from POS to the end of the string.
? Question
Create a shell script that uses the output from the
traceroute command, transform it to a list and,
print out the IP count and the IP address.
traceroute to google.com (216.58.211.174), 30 hops max, 60 byte packets
1 192.168.43.1 (192.168.43.1) 2.366 ms 3.029 ms 3.128 ms
2 169.254.252.10 (169.254.252.10) 49.557 ms 49.822 ms 51.895 ms
3 172.16.220.1 (172.16.220.1) 51.596 ms 51.668 ms 51.371 ms
4 172.16.220.10 (172.16.220.10) 49.817 ms 40.445 ms 50.942 ms
5 dub08s01-in-f14.1e100.net (216.58.211.174) 50.580 ms 38.572 ms 37.716 ms

Example:
1 192.168.43.1
2 169.254.252.10

??
3 172.16.220.1
4 172.16.220.10
5 216.58.211.174

?
Datatypes, operations and operators
Basic datatypes

Type Representation Example Description


Boolean False a = False The false value
type True a = True The true value
Absence of
None type None a = None
value
int() a = 1 Integer value
Numeric
type Floating point
float() a = 1.5
value
a = 'A' or Sequence of
String type str()
a = "a" char

In Python datatypes are automatically recognised!


Datatypes, operations and operators
Operations with basic datatypes
Operation Example
Sum of x and y x + y
Difference of x and y x - y
Product of x and y x * y
Quotient of x and y x / y
Remainder of x / y x % y
Integer part of the quotient of x and y x // y
x to the power y x ** y or pow(x, y)
Absolute value or magnitude of x abs(x)
The pair (x // y, x % y) divmod(x, y)
x rounded to n digits, rounding half to even round(x, n)
Concatenation of strings x and y x + y
Duplicate n times string x x * n
Datatypes, operations and operators
Basic datatypes
Working with basic datatypes:
• Example 1: Implicit conversion of operands to a
common type in mixed-type expressions
3 + 7.5 ⟹ 10.5
• The sum of an int and a float results in a float.
• Example 2: Explicit conversion of operands to a
specific type
3 + int(7.5) ⟹ 10
Conversion function Result Conversion function Result
int() int(10.5) 10 float() float(10) 10.0
int('10') 10 float('10') 10.0
int('10.5') ERROR float('10.5') 10.5
Datatypes, operations and operators
Basic datatypes

• Example 3: String concatenation


'a' + 'b' ⟹ 'ab'
• Example 4: String concatenation with explicit
conversion
'a' + str(1) ⟹ 'a1'
• The concatenation can only be applied to string
(str) types.
Datatypes, operations and operators
Basic datatypes

• Quick questions: what are the results when the


following are evaluated?
'a' + 10

- (15/4) + 7

'b' * 5
Datatypes, operations and operators
Basic operators
Operator Example
Assign y to x x = y
x is equal to y x == y
x is not equal to y x != y
x is greater than y x > y
x is less than y x < y
x is greater than or equal to y x >= y
x is less than or equal to y x <= y
and
Local operators or
not
Check if x and y point to the same object, True if yes x is y
Datatypes, operations and operators
Basic operators
Working with basic operators:
• Example 1: assign a value to a variable
a = 3
• The variable ‘a’ will contain the value 3 of type int
• Example 2: assign a value to a variable given by
evaluating an expression
a = 3 + int(7.5)
• The variable ‘a’ will contain the value 10 of type int
• Example 3: evaluating a Boolean expression (1)
3 == 4 ⟹ False
Datatypes, operations and operators
Basic operators

• Example 4: evaluating a Boolean expression (2)


not 3 ⟹ False
• Example 5: evaluating if the operands refer to the
same object (1)
3333 is 3333 ⟹ True
• Example 6: evaluating if the operands refer to the
same object (2)
a = 3333
b = 3333
a is b ⟹ False
• Exception for integer between -5 and 256!
Datatypes, operations and operators
Objects

Data is represented by objects consisting of:


• An identifier: assigned when the object is created and
used to uniquely identify the object in the memory.
• The identifier can be retrieved by using the id() function
• A type: used to define the type of operations and values
that the object can support.
• The type can be retrieved by using the type() function
• A value: the content of the object, this can be:
• Mutable: the value can change, e.g. user-defined classes
• Immutable: the value cannot change, e.g. int, float, bool,
string
Datatypes, operations and operators
Advanced datatypes and their constructions
List: mutable ordered sequence of items of mixed types

# Create an empty list


l = []
# Create a list containing a and b objects
l = [a, b]
# Create a list from an iterable object
l = [x for x in iterable]
# Create an empty list
l = list()
# Create a list from an iterable object
l = list(iterable)
Datatypes, operations and operators
Advanced datatypes and their constructions
The common operations for a list are:
• Determine if a list is empty: my_list == []
• Determine the length of a list: len(my_list)
• Access an element of a list: my_list[i]
• Insert element into a list: my_list.insert(i, e)
• Replace an element of a list: my_list[i] = e
• Delete an element of a list: del my_list[i]
• Sort elements of a list (ascending): my_list.sort()
• Reverse elements of a list: my_list.reverse()
• Append an element to the list: my_list.append(e)
• Where “my_list” is the list, “i” is the index, and “e” is the
element
Datatypes, operations and operators
Advanced datatypes and their constructions
# Create a list with mixed-type objects
>>> my_list = [1, '2', 4.4, True]
>>> my_list
?????????
# Determine if a list is empty
>>> my_list == []
?????????
# Determine the length of a list
>>> len(my_list)
?????????
# Access an element of a list
>>> my_list[1]
?????????
Datatypes, operations and operators
Advanced datatypes and their constructions
# Insert an element into a list
>>> my_list.insert(2, [1])
>>> my_list
?????????
# Replace an element of a list
>>> my_list[2] = 5
>>> my_list
?????????
# Delete an element of a list
>>> del my_list[1]
>>> my_list
?????????
Datatypes, operations and operators
Advanced datatypes and their constructions
# Sort elements of a list (ascending)
>>> my_list.sort()
>>> my_list
?????????
# Reverse elements of a list
>>> my_list.reverse()
>>> my_list
?????????
# Append an element to the list
>>> my_list.append('9')
>>> my_list
?????????
Datatypes, operations and operators
Advanced datatypes and their constructions
Tuple: a simple immutable ordered sequence of items,
which can be of mixed types, including collection types

# Create an empty tuple


t = ()
# Create a tuple containing the a object
t = (a,)
# Create a tuple containing a and b objects
t = (a, b)
# Create an empty tuple
t = tuple()
# Create a tuple from an iterable object
t = tuple(iterable)
Datatypes, operations and operators
Advanced datatypes and their constructions
The common operations for a tuple are:
• Determine if a tuple is empty: my_tuple == ()
• Determine the length of a tuple: len(my_tuple)
• Access an element of a tuple: my_tuple[i]
• Where “my_tuple” is the tuple and “i” is the index
# Create a tuple with mixed-type objects
>>> my_tuple = (1, '2', 4.4, True)
>>> my_tuple
?????????
# Determine if a tuple is empty
>>> my_tuple == ()
?????????
# Determine the length of a tuple
>>> len(my_tuple)
?????????
?? Question
??
? ?
Given the following list, how you can access to the
element highlighted:
my_list = ['a', 2, [3, (5, 4)], '3']
my_list[2][1][1]

Given the following tuple, how you can delete the


element highlighted:
my_tuple = ([1], [(2, [9, 3]), 2], '0')
del my_tuple[1][0][1][0]
Datatypes, operations and operators
Advanced datatypes and their constructions
Dictionary: holds mutable key-value pairs implemented as
hash table
# Create an empty dictionary
d = {}
# Create a dictionary with two key-value pairs
d = {key1: value1, key2: value2}
# Create an empty dictionary
d = dict()
# Create a dictionary with two key-value pairs
d = dict(key1=value1, key2=value2)
# Create a dictionary with two key-value pairs
d = dict(zip([key1, key2], [value1, value2]))
Datatypes, operations and operators
Advanced datatypes and their constructions

The common operations for a dictionary are:


• Determine if a dictionary is empty: my_dict == []
• Determine the length of the dictionary: len(my_dict)
• Access to the value of a key: my_dict[k]
• Replace a value of a key: my_dict[k] = v
• Delete a key-value pair: del my_dict[k]
• Check if a key exists: k in my_dict
• Check if a value exists: v in my_dict.values()
• Where “my_dict” is the dictionary, “k” is the key, and “v” is
the value
• The key can be an int, float, string and immutable object
Datatypes, operations and operators
Advanced datatypes and their constructions
# Create a dictionary with mixed-type
objects
>>> my_dict = {'int':1, 'str':'2', 1:True}
>>> my_dict
?????????
# Determine if a dictionary is not empty
>>> my_dict != {}
?????????
# Determine the length of a dictionary
>>> len(my_dict)
?????????
# Access to the value of a key
>>> my_dict[1]
?????????
Datatypes, operations and operators
Advanced datatypes and their constructions
# Replace a value of a key
>>> my_dict['str'] = 'Hello'
>>> my_dict
?????????
# Delete a key-value pair
>>> del my_dict[1]
>>> my_dict
?????????
# Check if a key exists
>>> 1 in my_dict
?????????
# Check if a value exists
>>> 1 in my_dict.values()
?????????
Datatypes, operations and operators
Advanced datatypes and their constructions
Range: type represents an immutable sequence of numbers
and is commonly used for looping a specific number of times
in for loops

"""
Create an iterable range object from the
start value to the stop value with an
optional step value
"""
r = range(start, stop, [step])
Control Structure
Sequential control:
• Implicit form of control in which instructions are
executed as they are written

Instruction 1
Instruction 2
Instruction 3
Instruction 4
Instruction 5
Instruction 6
Instruction 7

Control Structure
Selection control:
• Selectively executes instructions by using a control
statement
Instruction 1
Instruction 2
Instruction 3
Control statement

True False

Instruction 4 Instruction 7
Instruction 5 Instruction 8
Instruction 6 Instruction 9
… …
Control Structure
if statement

Nested if statements

if condition: if condition:
... ...
else: elif condition:
... ...
else:
...
Control Structure
Iterative control:
• Repeatedly executes instructions by using an
iterative control statement
Instruction 1
Instruction 2
Instruction 3
Control statement
True False

Instruction 4 Instruction 7
Instruction 5 Instruction 8
Instruction 6 Instruction 9
… …
Control Structure
for loop
for var in iterable:
...
Classic examples in Python
# for loop based on a range object for counting
for i in range(start, stop, [step]):
...
# for loop to retrieve each item i in a list
for i in list:
...
# for loop to retrieve each item in a list by
# using index i (list[i])
for i in range(len(list)):
...
Control Structure
while loop and statements

while condition:
...

Other statements

Breaks out of the innermost enclosing for or


break
while loop
continue Continues with the next iteration of the loop
This statement does nothing, used when a
pass statement is required syntactically but the
program requires no action.
?? Question
??
? ?
Given the following list, use control structures to print
only the highlighted element
my_list = ['a', 2, [3, (5, 4)], '3']
Next class?

Today at 1 p.m. in the


Electrical Engineering &
Electronics Building,
ELEC402 PC lab
(Building 235).

You might also like