0% found this document useful (0 votes)
2 views67 pages

Module 1 - Python Basics 2324-2

Uploaded by

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

Module 1 - Python Basics 2324-2

Uploaded by

Omar Basset
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 1: Introduction to Basic

Programming with Python


SECR3253 Network Programming

Marina binti Md Arshad


Department of Computer Science, Faculty of Computing, UTM
2023/2024-2
Introduction

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Introduction to Python and Programming Basics

• This chapter of the course covers the following


objectives:
• Describe how Communities of Practice provide value to programmers.
• Use Python to create programs that accept user input and read and write to
external files.

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 3
Verify Your PC is Ready
• You should have already completed the Lab -
PC Setup for Workshop.
• Your PC should include the following:
• Python and the required modules are installed and verified
• Postman installed

• Verify that your PC is ready to complete the


tasks of the workshop.

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 4
Code and
Communities of
Practice

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Code

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Power of Code
Everybody... should learn how
to program a computer...
because it teaches you how to
Coding is a huge think. [Coding] is the closest
base...to build off Steve Jobs thing we have to a
of...to go in the
Founder, Apple superpower.
direction [you] want to.
Drew Houston
Chris Bosh
Dropbox Creator
NBA All-Star Great coders are today’s
rock stars.
[Link]
Black Eye Peas Creator
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 7
The Power of Code

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 8
Communities of
Practice

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Communities of Practice (CoPs)

Communities of practice are


groups of people who share a
concern or a passion for
something they do and learn
how to do it better as they
interact regularly.
Jean Lave & Etienne Wenger

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 10
CoPs for Programmers - GitHub

GitHub is the open source software version control


system started by Linus Torvalds, the creator of
Linux.

[Link] © 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 11
CoPs for Programmers - Stack Overflow

Stack Overflow maintains a library of detailed


answers to every question about programming.

[Link] © 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 12
CoPs for Programmers - Cisco DevNet
Cisco DevNet offers support to developers and programmers
who want to build Cisco-enable applications or use Cisco APIs
to enhance and manage their networks

[Link]
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 13
Python Basics

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Python
Interpreter

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Start Python
Windows
C:\> python
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Mac or Linux
$ python3
Python 3.5.2 (default, Aug 18 2017, 17:48:00)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 16
Python Variable Name Rules

• Must start with a letter or underscore _


• Must consist of letters and numbers and
underscores
• Case Sensitive
Good: spam eggs spam23 _speed

Bad: 23spam #sign var.12

Different: spam Spam SPAM © 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 17
Reserved Words

• You can not use reserved words as variable


names / identifiers
and del for is raise
assert elif from lambda return
break else global not try
class except if or while
continue exec import pass yield
def finally in print
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 18
Use Interactive Interpreter as a Calculator
$ python3
Python 3.5.2 (default, Aug 18 2017, 17:48:00)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 2+3
5
>>> 10-4
6
>>> 2*4
8
>>> 20/5
4
>>> 3**2
9

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 19
PEMDAS
Operator Precedence Parenthesis
Exponent
Multiplication
• Remember the rules top to bottom Division
Addition
• When writing code - use parenthesis Subtraction
Left to Right
• When writing code - keep mathematical
expressions simple enough that they are
easy to understand
• Break long series of mathematical
operations up to make them more clear

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 20
Mixing Integer and Floating

• When you perform an operation >>> print 99 / 100


where one operand is an 0
integer and the other operand is >>> print 99 / 100.0
a floating point the result is a 0.99
floating point >>> print 99.0 / 100
0.99
• The integer is converted to a >>> print 1 + 2 * 3 / 4.0 - 5
floating point before the -2.5
operation >>>

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 21
Use Interpreter to print Hello World
>>> "Hello World!"
• Strings can be 'Hello World!'
>>> 'Hello World!'
enclosed with single 'Hello World!'
quotes or double >>> print("Hello World!")
Hello World!
quotes.
• To remove the single
quotes in the output,
use the print
command.

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 22
Quit the Interpreter and Start IDLE
• Python includes the Windows
Integrated
Start > Python 3.x > IDLE (Python 3.x
Development 32-bit).
Environment (IDLE)
• Windows - open IDLE Mac or Linux
>>> "Hello World!"
from the Start menu 'Hello World!'
>>> 'Hello World!'
• Mac or Linux - open 'Hello World!’
IDLE from the >>> quit()
$ idle3
command line.
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 23
IDLE Benefits
• Provides color
coding
• Includes a text
editor for writing
programs
• Quickly save and
run programs
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 24
Activity - Write, Save, and Run Your First Program

1. In IDLE, click File > New File (Ctrl+N) to open an


Untitled script file.
2. Save the file as 01_hello-[Link] in your project
directory.
3. Enter the following in the script:
print("Hello World!")
4. Save the script; click File > Save (Ctrl+S)
5. Run the script; click Run > Run Module (F5)

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 25
First Program and Output

Program File Output

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 26
Data Types,
Variables, and
Conversions

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
What does “Type” Mean?

• In Python variables, literals, and constants


have a “type”
• Python knows the difference between an >>> ddd = 1 + 4
integer number and a string >>> print ddd
• For example “+” means “addition” if 5
something is a number and “concatenate” if
something is a string
>>> eee = 'hello ' + 'there'
>>> print eee
hello there

concatenate = put together


© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Type Matters >>> eee = 'hello ' + 'there'
>>> eee = eee + 1
• Python knows what “type” everything is
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
• Some operations are prohibited
TypeError: cannot concatenate 'str'
• You cannot “add 1” to a string and 'int' objects
• We can ask Python what type something is by >>> type(eee)
using the type() function.
<type 'str'>
>>> type('hello')
<type 'str'>
>>> type(1)
<type 'int'>
>>>
© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Basic Data Types
• The four basic data >>> type(98)
types we will use <class 'int'>
>>> type(98.6)
are: <class 'float'>
• Integer >>> type("Hi!")
• Float <class 'str'>
• String >>> type(True)
• Boolean <class 'bool'>

• Use the type()


command to
determine the data
type.

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 30
Boolean Comparison Operators
Operator Meaning >>> 1<2
True
> Greater than >>> 1>2
False
< Less than >>> 1==1
True
== Equal to >>> 1!=1
False
!= Not equal to >>> 1>=1
True
>= Greater than or equal to >>> 1<=1
True
<= Less than or equal to

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 31
Creating and Using a Variable
• Use a single >>> x=3
>>> x*5
equal sign to 15
>>> "Cisco"*x
assign a value to 'CiscoCiscoCisco'

a variable.
• A variable can
then be called for
other operations.
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 32
Concatenate Multiple String Variables
• Concatenation is >>> str1="Cisco"
>>> str2="Networking"
the process of >>> str3="Academy"
>>> space=" "
combining >>> print(str1+space+str2+space+str3)
Cisco Networking Academy
multiple strings. >>>

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 33
Converting Data Types
• Concatenation >>> x=3
>>> print("This value of X is " + x)
does not work for Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
different data print("This value of X is " + x)
TypeError: Can't convert 'int' object to str
types. implicitly

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 34
Converting Data Types
• Use the str() >>> x=3
>>> print("The value of x is " + x)
command to Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
convert the data print("This value of X is " + x)
TypeError: Can't convert 'int' object to str
type to a string. implicitly
>>> print("The value of x is " + str(x))
The value of x is 3
>>>

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 35
Converting Data Types
• The type for the >>> x=3
>>> print("The value of x is " + x)
variable x is still Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
an integer. print("This value of X is " + x)
TypeError: Can't convert 'int' object to str
implicitly
>>> print("The value of x is " + str(x))
The value of x is 3
>>> type(x)
<class 'int’>

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 36
Converting Data Types
• To convert the >>> x=3
>>> print("The value of x is " + x)
data type, Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
reassign the print("This value of X is " + x)
TypeError: Can't convert 'int' object to str
variable to the implicitly
>>> print("The value of x is " + str(x))
new data type. The value of x is 3
>>> type(x)
<class 'int'>
>>> x=str(x)
>>> type(x)
<class ‘str'>

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 37
Converting Data Types
• Use “{:.2f}”.format >>> pi = 22/7
>>> print(pi)
to display a float to 3.142857142857143
>>> print("{:.2f}".format(pi))
two decimal places. 3.14
>>>
• Change the 2 to
increase or
decrease decimal
places.

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 38
Lists and
Dictionaries

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Lists >>> hostnames=["R1","R2","R3","S1","S2"]
>>> type(hostnames)
• A list is an ordered <class 'list'>
>>> len(hostnames)
list of items. 5
>>> hostnames
• Create a list using the ['R1', 'R2', 'R3', 'S1', 'S2']
brackets [ ] and enclosing
each item in the list with
quotes.
• Use the type() command
to verify the data type.
• Use the len() command
return the number of items
in a list.
• Call the list variable name
to display it’s contents.
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 40
Lists >>> hostnames=["R1","R2","R3","S1","S2"]
>>> type(hostnames)
• Use the index to <class 'list'>
>>> len(hostnames)
refer to an item 5
and manipulate the >>> hostnames
list ['R1', 'R2', 'R3', 'S1', 'S2']
>>> hostnames[0]
• The first item in a list is 'R1'
indexed as zero, the >>> hostnames[-1]
second is indexed as one, 'S2'
and so on. >>> hostnames[0]="RTR1"
• The last item can be >>> hostnames
referenced with index [-1] ['RTR1', 'R2', 'R3', 'S1', 'S2']
• Replace an item by >>> del hostnames[3]
assigning a new value to >>> hostnames
the index. ['RTR1', 'R2', 'R3', 'S2']
• Use the del() command to >>>
remove an item from a list.
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 41
Dictionaries >>> ipAddress =
{"R1":"[Link]","R2":"[Link]","R3":"10.3.3
.1"}
• A list of >>> type(ipAddress)
<class 'dict'>
unordered
key/value pairs
• Create a dictionary using
the braces { }
• Each dictionary entry
includes a key and a
value.
• Separate key and values
with a colon.
• Use quotes for keys and
values that are strings. © 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 42
Dictionaries >>> ipAddress =
{"R1":"[Link]","R2":"[Link]","R3":"10.3.3
.1"}
• Use the key to >>> type(ipAddress)

refer to an entry <class 'dict'>


>>> ipAddress
• The key is enclosed with {'R1': '[Link]', 'R2': '[Link]', 'R3':
brackets [ ]. '[Link]'}
>>> ipAddress['R1']
• Keys that are strings can '[Link]’
be referenced using >>> ipAddress["S1"]="[Link]"
single or double quotes. >>> ipAddress
• Add a key/value pair by {'R1': '[Link]', 'R2': '[Link]', 'R3':
'[Link]', 'S1': '[Link]'}
setting the new key equal
>>> "R3" in ipAddress
to a value. True
• Use key in dictionary >>>
command to verify if a
key exist in the dictionary
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 43
Activity - Troubleshoot List and Dictionary Code

1. Open 02_list-[Link].
2. Run the code.
3. Troubleshoot the code until the script runs
without errors.
4. What errors did you fix in the script?

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 44
User Input

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
The Input Function
• The input() >>> firstName = input("What is your first
name? ")
function provides What is your first name? Bob
>>> print("Hello " + firstName +"!")
a way to get Hello Bob!
>>>
information from
the user.

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 46
Activity - Create a Script to Collect Personal
Information
1. Open a blank script file and save it in your GitHub
project directory as 03_personal-[Link].
2. Create a script that asks for four pieces of information
such as: first name, last name, location, and age.
3. Create a variable for a space: space = " "
4. Add a print statement that that combines all the
information in one sentence.
5. Run the script and troubleshoot any errors.
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 47
If Functions and
Loops

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Indentation
• Increase indent indent after an if statement or for statement
(after : )
• Maintain indent to indicate the scope of the block (which lines
are affected by the if/for)
• Reduce indent to back to the level of the if statement or for
statement to indicate the end of the block
• Blank lines are ignored - they do not affect indentation
• Comments on a line by themselves are ignored w.r.t.
indentation
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 49
Warning:
• Python cares a *lot* about how far line is
indented. If you mix tabs and spaces, you may
get “indentation errors” even if everything looks
fine

Please do this now while you are thinking about it so we can all stay sane...

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 50
If/Else Function
• Open a blank script and nativeVLAN = 1
save it as 04_if-[Link]. dataVLAN = 100
if nativeVLAN == dataVLAN:
• Create a simple if print("The native VLAN and the data VLAN
function that compares are the same.")
two values and prints the else:
results. print("This native VLAN and the data VLAN
are different.")
• Run the script and
troubleshoot any errors.
• Change the values to
test the else print
statement.

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 51
If/Elif/Else Function
• Open a blank script aclNum = int(input("What is the IPv4 ACL
and save it as 05_if- number? "))
[Link]. if aclNum >= 1 and aclNum <= 99:
print("This is a standard IPv4 ACL.")
• Create a more elif aclNum >=100 and aclNum <= 199:
print("This is a extended IPv4 ACL.")
complex if function else:
that takes user input print("This is not a standard or extended
and includes an elif IPv4 ACL.")
loop.
• Note that the input
needs to be converted
to an integer.

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 52
For Loop
• A for loop iterates >>> devices=["R1","R2","R3","S1","S2"]
through items in a >>> for item in devices:
print(item)
list, dictionary, or
other sequenced
data type. R1
R2
• The variable name R3
“item” is arbitrary S1
S2
and can be anything >>>
the programmer
chooses.

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 53
For Loop with Embedded If
• Using an If loop >>> for item in devices:
if "R" in item:
inside the For print(item)

loop R1
R2
R3
>>>

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 54
Use a For Loop to Create a New List
• Create an empty >>> switches=[]
>>> for item in devices:
list called if "S" in item:
[Link](item)
switches.
>>> switches
• Iterate through ['S1', 'S2']
>>>
the devices list to
create the switch
list.
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 55
Create a While Loop
• Open a blank script x=input("Enter a number to count to: ")
and save it as x=int(x)
06_while-[Link]. y=1
while y<=x:
• Create a program with print(y)
y=y+1
a while loop that
counts to a user’s
supplied number.
• Convert the string to an integer:
x = int(x)
• Set a variable to start the count:
y=1
• While y <= x, print the value of y
and increment y by 1.

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 56
Modify the While Loop to Use Break
• Modify the while x=input("Enter a number to count to: ")
x=int(x)
loop to use a y=1
while True:
Boolean check print(y)
y=y+1
and break to stop if y>x:
break
the loop.
• Replace while y<=x with
while True
• Add an if function to
break the loop when y>x.
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 57
Use a While Loop to Check for User Quit
• Add another while while True:

loop to the x=input("Enter a number to count to: ")


if x == 'q' or x == 'quit':
beginning of the break
script which will x=int(x)
check for a quit y=1
command. while True:
print(y)
• Add an if function y=y+1
to the while loop to if y>x:
break
check for ‘q’ or
‘quit’ .
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 58
File Access

© 2019 Cisco and/or its affiliates. All rights reserved. Cisco Confidential
Read an External File and Print the Contents
• Open a blank script file=open("[Link]","r")
and save it as for item in file:
print(item)
07_file-[Link]. [Link]()

• Create a script to
read and print the
content of a file.
• The ‘[Link]’ file
should be in the
same directory as
your script.

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 60
Remove Blank Lines from the Output
• Use the strip() file=open("[Link]","r")
for item in file:
method to remove item=[Link]()
print(item)
the leading and [Link]()

trailing whitespace
characters (new
line, carriage
return, tabs,
spaces, etc.).
© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 61
Copy File Content Into a List Variable
• Create an empty devices=[]
file=open("[Link]","r")
list. for item in file:
item=[Link]()
[Link](item)
• Use the append [Link]()
print(devices)
attribute to copy
file content to the
new list.

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 62
Activity – Modify the Script to Add an Item to the
File
1. Open a new file and save it as 07_file-access_actvity.py.
2. For the open() function use the mode a, which will allow you to
append a item to the [Link] file.
3. Inside a while True: loop, embed an input() function command
that asks the user for the new device.
4. Set the value of the user's input to a variable named newItem.
5. Use an if statement that breaks the loop if the user types exit and
prints the statement "All done!"
6. Use the command [Link](newItem + “\n”) to add the new user
provided device.

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 63
SUMMARY

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 64
Python
Python Programming Summary
• Python is an easy to learn programming language.

• Few factors that make Python a great tool for learning basic coding are:
• It is easy to learn - the time needed to learn Python is shorter than for many other
languages.
• It is easy to use for writing new software – it is possible to write code faster when
using Python.
• It is easy to obtain, install and deploy - Python is free, open and multiplatform.
• Python provides a solid foundation and allows to learn other programming languages
(for example, C++, Java, or C) much easier and faster.

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 65
Python
Lab 1 (1.3.3) - Python Programming Review
In this lab, you will complete the following objectives:
• Part 1: Launch the DEVASC VM
• Part 2: Start Python and VS Code
• Part 3: Review Data Types and Variables
• Part 4: Review Lists and Dictionaries
• Part 5: Review the Input Function
• Part 6: Review If, For, and While Functions
• Part 7: Review Methods for File Access

© 2016 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 66

You might also like