0% found this document useful (0 votes)
11 views5 pages

6 - Control Structures

Uploaded by

fersd2018
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)
11 views5 pages

6 - Control Structures

Uploaded by

fersd2018
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
You are on page 1/ 5

6.

Control structures
This section covers program flow control:
• branching with if/elif/else
• repeating actions using for and while loops
• exception handling with try/except

if/elif/else
Example of if statement:
a = 9

if a == 10:
print('a equal to 10')
elif a < 10:
print('a less than 10'):
else:
print('a greater than 10')

Operator in
Operator in allows checking for the presence of element in a sequence (for example,
element in a list or substrings in a string):
'Fast' in 'FastEthernet' # True

vlan = [10, 20, 30, 40]


10 in vlan # True

When used with dictionaries, in condition performs check by dictionary keys:


r1 = {'IOS': '15.4',
'IP': '10.255.0.1',
'model': '4451'}
'IOS' in r1 # True
'4451' in r1 # False

33
for
For loop iterates elements of specified sequence and performs actions specified for each
element. Examples of sequences of elements that can be iterated by for:
string,list, dictionary, range, Any Iterable.

Example:
words = ['list', 'dict', 'tuple']

for word in words:


print(word)

Example of loop for with range() function:


for i in range(10):
print('interface FastEthernet0/{}'.format(i))

This loop uses range(10). Function range() generates numbers in range from zero to
specified number (in this example, up to 10) not including it.

When a loop runs through dictionary, it actually goes through keys:


r1 = {'ios': '15.4',
'ip': '10.255.0.1',
'model': '4451'}

for k in r1:
print(k)
# ios ip model

You can use items() method which allows you to run loop over a key-value pair:
for key, value in r1.items():
print(key + ' => ' + value)

while
Example:
a = 5
while a > 0:
print(a)
a -= 1

34
for/else, while/else
In loops for and while you may optionally use else block.

Example:
for num in range(5):
print(num)
else:
print("Run out of numbers")

# 0
# 1
# 2
# 3
# 4
# Run out of numbers

Working with try/except/else/finally

try/except/else/finaly
Examples of exceptions:
try:
a = 2/0
except ZeroDivisionError:
print("You can't divide by zero")

#You can't divide by zero

try:
a = input("Enter first number: ")
b = input("Enter second number: ")
print("Result: ", int(a)/int(b))

except ValueError:
print("Please enter only numbers")
except ZeroDivisionError:
print("You can't divide by zero")

35
If you do not need to print different messages on ValueError and ZeroDivisionError, you
can do this:
try:
a = input("Enter first number: ")
b = input("Enter second number: ")
print("Result: ", int(a)/int(b))

except (ValueError, ZeroDivisionError):


print(""Something went wrong...")

Try/except has an optional else block. It is implemented if there is no exception.

Block finally is another optional block in try statement. It is always implemented, whether
an exception has been raised or not. It’s about actions that you have to do anyway. For
example, it could be a file closing.
try:
a = input("Enter first number: ")
b = input("Enter second number: ")
print("Result: ", int(a)/int(b))

except (ValueError, ZeroDivisionError):


print(""Something went wrong...")
else:
print("Result is squared: ", result**2)
finally:
print("And they lived happily ever after.")

36
Tasks

Task 6.1 :
The mac list contains MAC addresses in the format XXXX:XXXX:XXXX However, in Cisco
equipment MAC addresses are in XXXX.XXXX.XXXX format.

Write a code that converts MAC addresses to cisco format and adds them to a new list
named result. Print the result list to the stdout using print function.
mac = ["aabb:cc80:7000", "aabb:dd80:7340", "aabb:ee80:7000",
"aabb:ff80:7000"]

Task 6.2 :
Prompt the user to enter an IP address in the format 10.0.1.1. Depending on the type of
address (described below), print to the stdout:
• ‘unicast’ - if the first byte is in the range 1-223
• ‘multicast’ - if the first byte is in the range 224-239
• ‘local broadcast’ - if the IP address is 255.255.255.255
• ‘unassigned’ - if the IP address is 0.0.0.0
• ‘unused’ - in all other cases

37

You might also like