0% found this document useful (0 votes)
19 views26 pages

Lecture 1

Uploaded by

ayataljarrah89
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views26 pages

Lecture 1

Uploaded by

ayataljarrah89
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Cybersecurity Programming

Crash Course In Python Programming Language—Lesson 1

Dr. Mustafa Ababneh


Why Should We Learn How To Code?

As a network engineer or a security professional, should you learn


how to code?
How You Can Become a Next-Gen Network Engineer
https:
//www.cbtnuggets.com/blog/technology/networking/
how-you-can-become-a-next-gen-network-engineer
“Everybody should learn how to program a computer because it
teaches you how to think.”
Steve Jobs, Founder, Apple1
“[Coding] is the closest thing we have to a superpower.”
Drew Houston, Dropbox Creator1

https://www.youtube.com/watch?v=nKIu9yen5nc1

1 From Cisco’s Model Driven Programmability: YANG/RESTCONF/NETCONF 1/


Why Python?

2/
Features

Interpreted; no compilation & linking


Dynamically typed
Variables do not have a predefined type
The first assignment to a variable creates it
Variable types don’t need to be declared
Python figures out the variable types on its own
Ideal for scripting & rapid application development
Same script runs on several platforms & freely available
Rich, built-in collection types (high-level data structures)
Lists
Tuples
Dictionaries (maps)
Sets

3/
Features

Concise
No { } for blocks (indentation instead)
No ( ) for if/while conditions
Rich standard library of modules
Several third party modules & tools
Procedural vs. Object-oriented programming
Multi-threading
GUI, Web, Database connectivity, network programming, distributed
computing, cryptography libraries, security tools, etc., etc., etc.
Strong open-source community

4/
Informal Introduction To Python

Make sure you have python3.6 installed


If not, install it with sudo apt install python3.6
This crash course is based on
https://docs.python.org/3.6/tutorial/index.html

5/
Python’s Advanced “Hello World!”

# Example1.py
print("Hello World !")
ahmad@ubuntu:~$ python3.6 Example1.py
print('Hello World !') Hello World !
print("Hello\nWorld!") Hello World !
print("""Hello Hello
World World!
!""") Hello
World
!
x = 23 # A comment 23
print(x) 5.7 foo2
foo1
Traceback
x, y, z = 'foo1', "foo2", 5.7
(most
print(z, y, x) recent
del x call
print(x) last):
File "Example1.py", line 15, in <module>
print(x)
NameError: name 'x' is not defined

6/
Making Python Source File Executable

#!/usr/bin/python3.6

print("Hello World !") ahmad@ubuntu:~$ ./Example2.py


print('Hello World !') Hello World !
print("Hello\nWorld!") Hello World !
Hello
print("""Hello
World!
World Hello
!""") World
!
x = 23 # A comment 23
5.7 foo2
print(x) foo1
Traceback
x, y, z = 'foo1', "foo2", 5.7 (most
print(z, y, x) recent
call
del x last):
print(x) File "./Example1.py", line 16, in <module>
print(x)
NameError: name 'x' is not defined

7 / 13
Numbers

#!/usr/bin/python3.6

x = (50 - 5 * 6) / 4
print(x)
print ('The value of x is', x)

y = 17 / 3 # conventional division
z = 17 // 3 # floor division
w = 17 % 3 # reminder
a = 5 ** 3 # power operator

print(y, z, w, a)

ahmad@ubuntu:~$ ./Example2.py
5.0
The value of x is 5.0
5.666666666666667 5 2 125

8 / 13
Strings (1)

#!/usr/bin/python3.6

str1 = 'a-\t-b-\n-c'
str2 = r'a-\t-b-\n-c'
print(str1)
print(str2)
str3 = 7 * 'ab-' +
"--cde" # Concise
code
print(str3)
print(len(str3))

ahmad@ubuntu:~$ ./Example3.py
a- -b-
-c
a-\t-b-\n-c
ab-ab-ab-ab-ab-ab-ab---cde
26

9 / 13
Strings (2)

#!/usr/bin/python3.6

word = 'Python'
print(word[0])
print(word[5])
print(word[-1])
print(word[0:2] # characters from position 0 (included)
) # to 2 (excluded)
print(word[2:5])
print(word[2:])
print(word[:4])

ahmad@ubuntu:~$ ./Example4.py
P
n
n
Py
tho
thon
Pyth
10 /
Strings (3)

#!/usr/bin/python3.6

word = 'Python'
print(word[15]) # gives IndexError Exception
print(word[2:25]) # prints thon
print(word[12:]) # prints only new line

word[2] = 'R' # gives TypeError Exception


# Strings are immutable
# I.e., they have fixed value
# I.e., they cannot be changed
# If a different value is needed,
# a new object has to be created

newword = word[:2] + "R" + word[3:]

11 /
Compound Data Types: Lists (1)
#!/usr/bin/python3.6

list1 = [1, 4, 9, 16, 25]


print(list1)
list2 = [1, "a", 'qqe']
print(list2)

print(list1[0])
print(list1[-3:])

list3 = list1 +
[36, 49, 64]
list3[0] = -9 # Lists are mutable
list3.append(90)
list3[2:5] = ['A', "B", 'C']
print(list3)

ahmad@ubuntu:~$ ./Example6.py
[1, 4, 9, 16, 25]
[1, 'a', 'qqe']
1
[9, 16, 25]
[-9, 4, 'A', 'B', 'C', 36, 12 /
Lists (2)

...
list1[:] = [] # Clearing the list

print(len(list3))

a = ['a', 'b', 'c']


n = [1, 2, 3]
x = [a, n]

print(x)
print(x[0])
print(x[0][1])

...
9
[['a', 'b', 'c'], [1, 2, 3]]
['a', 'b', 'c']
b

13 /
Cybersecurity Programming
Crash Course In Python Programming Language—Lesson 2

Dr. Mustafa Ababneh


Indentation & Control Flow: while

while i < 10:


tot += i
tot, i = 0, 1
i += 1
print(tot)
while i < 10:
tot += i
while i < 10:
i += 1
tot += i
print(tot)
i += 1 # IndentationError
print(tot)
while i < 10:
tot += i
while i < 10:
i += 1
tot += i
print(tot)
i += 1 # IndentationError
print(tot)

1 / 11
if Statement

#!/usr/bin/python3.6

x = int(input("Please enter an integer: "))

if x < 0:
a = -1 * x
elif x
== 2:
a = 2 * x
elif x == 3:
a = x
else:
a = x / 2
print(a)

2 / 11
for Statement

for i in range(10):
print(i ** 2) # outputs squares 0 to 81

for i in range(5, 10):


print(i ** 2) # outputs squares 25 to 81

for i in range(1, 10, 4):


print(i ** 2) # outputs 1,
25, 81

words = ['A', 'AB', 'ABC', 'ABCD']


for w in words:
print(len(w)) # outputs 1 to
4

for i in range(len(words)):
print(len(words[i])) # outputs 1 to 4

for i in 'abcd':
print(i) # outputs a
to d
3 / 11
Functions
(1)
def mul(a, b):
""" This is the function doc string """
return a * 2, b + 2, a * b

def add(list_arg):
s = list_arg[0]
for i in range(1, len(list_arg)):
s += list_arg[i]

return s

print(mul(9, 7)) # outputs '(18, 9, 63)'

list1 = [1, 2, 3, 4]
print (add(list1)) # outputs 10

list2 = ['a', 'b', 'c']


print (add(list2)) # outputs 'abc'

Myadd = add
print(Myadd(list2)) # outputs 'abc'
4 / 11
Functions
(2)

Functions can be used just like any other data


They can be
Arguments to function
Return values of functions
Assigned to variables (as in previous slide)
Parts of tuples, lists, etc.

def fun2(x):
return x * 3

def fun1(q,
x):
return q(x)
print(fun1(fun2, 7)) # outputs 21

5 / 11
Functions (3): Parameter Passing

def f1(a, b):


print(a, b)

f1(1, 2) # outputs 1 2

f1(b = 1, a = 2) # outputs 2 1

f1(1, b = 2) # outputs 1 2

# f1(b = 1, 2) # SyntaxError: positional argument follows


# keyword argument

6 / 11
More on Lists
a = [66.25, 333, 333, 1, 1234.5]
print(a.count(333), a.count(66.25), a.count('x')) # outputs 2 1 0

a.insert(2, -1)
a.append(333)
print(a) # outputs [66.25, 333, -1, 333, 1, 1234.5, 333]

print(a.index(333)) # outputs 1

a.remove(333)
print(a) # outputs [66.25, -1, 333, 1, 1234.5, 333]

a.reverse()
print(a) # outputs [333, 1234.5, 1, 333, -1, 66.25]

a.sort()
print(a) # outputs [-1, 1, 66.25, 333, 333, 1234.5]

print(a.pop()) # outputs 1234.5

print(a) # outputs [-1, 1, 66.25, 333, 333]


7 / 11
List Comprehensions

A concise way to create lists

a1 = []

for x in [1, 2, 3]:

for y in [3, 1, 4]:

if x != y:

a1.append((x,
y))

# a1 = [(1, 3), (1, 4), (2,


3), (2, 1), (2, 4), (3, 1),
(3, 4)]

a2 = [(x, y) for x in
[1,2,3] for y in [3,1,4] if
x != y]
8 / 11
More on Data Structures

Not to be covered
Tuples
Sets
Dictionaries
In other programming languages, called maps
Indexed by keys (strings or numbers)
• Where as, lists are indexed by a range of numbers

Un-ordered set of ‘key:value’ pairs


Keys must be unique in a given dictionary

9 / 11
Dictionaries
(1)
student = {'name' : 'Mohammad', 'StudentID' : 111111}

student['gender'] = 'male'

print(student)
# outputs {'StudentID': 111111, 'gender': 'male', 'name': 'Mohammad'}

print(student['name']) # outputs Mohammad

print(list(student.items()))
# outputs [('StudentID', 111111), ('gender', 'male'), \
# ('name', 'Mohammad')]

print(list(student.keys())) # outputs ['StudentID', 'gender', 'name']

print(list(student.values())) # outputs [111111, 'male', 'Mohammad']

student['name'] = 'Ahmad'
print(student)
# outputs {'StudentID': 111111, 'gender': 'male', 'name': 'Ahmad'}

10 /
Dictionaries (2)

student = {'name': 'Ahmad', 'StudentID': 111111, 'gender': 'male'}

k, v = list(student.items())[0]
print(k, v) # outputs StudentID 111111

for k, v in student.items():
print(k, v)

# outputs
# StudentID 111111
# gender male
# name Ahmad

MyList = {10 : 'klmn', 20 : 134, 'k1' : 56}


print(MyList[10], MyList[20], MyList['k1']) # outputs klmn 134 56

11 /

You might also like