0% found this document useful (0 votes)
51 views

Session 2

The document discusses Python tuples, sets, and dictionaries. Tuples are ordered and unchangeable collections accessed by index. Sets are unordered and unindexed collections that cannot contain duplicate elements. Dictionaries are unordered collections of key-value pairs that are changeable, indexed, and cannot have duplicate keys. Common operations for each include accessing elements, adding/removing elements, checking for existence, and iterating over elements.

Uploaded by

Ah M Ed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Session 2

The document discusses Python tuples, sets, and dictionaries. Tuples are ordered and unchangeable collections accessed by index. Sets are unordered and unindexed collections that cannot contain duplicate elements. Dictionaries are unordered collections of key-value pairs that are changeable, indexed, and cannot have duplicate keys. Common operations for each include accessing elements, adding/removing elements, checking for existence, and iterating over elements.

Uploaded by

Ah M Ed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Network Automation using

Python
Session 2

Ahmed Elaraby 1
Tuples
• A tuple is a collection which is ordered and unchangeable In Python tuples are
written with round brackets.

• You can access tuple items by referring to the index number, inside square
brackets.

• Negative indexing means beginning from the end.

• You can specify a range of indexes by specifying where to start and where to end
the range.

• When specifying a range, the return value will be a new tuple with the specified
items.
Ahmed Elaraby 2
• thistuple = ("apple", "banana", "cherry")
• print(thistuple)
• >>> ('apple', 'banana', 'cherry')
• >>> thistuple = ("apple",)

• tuple1 = ("abc", 34, True, 40, "male")

• It is also possible to use the tuple() constructor to make a tuple.


• thistuple = tuple(("apple", "banana", "cherry"))

• thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


• print(thistuple[1])
• print(thistuple[-1])
• print(thistuple[2:5])
• print(thistuple[:4])
• print(thistuple[2:])
• print(thistuple[-4:-1])
• if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Ahmed Elaraby 3
• Once a tuple is created, you cannot change its values. Tuples are unchangeable, or
immutable as it also is called.

• But there is a workaround. You can convert the tuple into a list, change the list, and
convert the list back into a tuple.
• x = ("apple", "banana", "cherry")
• y = list(x)
• y[1] = "kiwi"
• x = tuple(y)
• print(x) >>> ("apple", "kiwi", "cherry")

• Add Items:
• y = list(x)
• y.append("orange")
• thistuple = tuple(y)
• Add tuple to a tuple:
• thistuple += y
• Remove Items:
• y = list(thistuple)
• y.remove("apple")
• thistuple = tuple(y)
• del thistuple Ahmed Elaraby 4
Tuple Methods

Method Description
Returns the number of times a specified value occurs
count()
in a tuple
Searches the tuple for a specified value and returns
index()
the position of where it was found

Ahmed Elaraby 5
Sets
• A set is a collection which is unordered and unindexed In Python sets are written with curly
brackets.

• You cannot access items in a set by referring to an index, since sets are unordered the items has
no index.
• But you can loop through the set items.
• thisset = {"apple", "banana", "cherry"}
• for x in thisset:
print(x)

• Once a set is created, you cannot change its items, but you can add new items.
• thisset = {"apple", "banana", "cherry"}
• print(thisset)
• print(len(thisset))
• print(type(thisset))
• thisset = set(("apple", "banana", "cherry"))

• Sets cannot have two items with the same value.

Ahmed Elaraby 6
• To add one item to a set use the add() method.
• thisset = {"apple", "banana", "cherry"}
• thisset.add("orange")
• print(thisset)

• To add items from another set into the current set, use the update() method.
• thisset = {"apple", "banana", "cherry"}
• tropical = {"pineapple", "mango", "papaya"}
• thisset.update(tropical)
• print(thisset)

• To remove an item in a set, use the remove(), or the discard() method.


• thisset.remove("banana")
• If the item to remove does not exist, remove() will raise an error.
• Remove "banana" by using the discard() method:
• thisset.discard("banana")
• Remove the last item by using the pop() method:
• x = thisset.pop()
• The clear() method empties the set:
• thisset.clear()
• The del keyword will delete the set completely:
• del thisset
Ahmed Elaraby 7
• Join Two Sets
• You can use the union() method that returns a new set containing all items from both
sets, or the update() method that inserts all the items from one set into another:
• set1 = {"a", "b" , "c"}
• set2 = {1, 2, 3}
• set3 = set1.union(set2)
• print(set3)
>>> {'c', 'a', 'b', 2, 3, 1}
• set1.update(set2)
>>> {1, 'a', 'c', 2, 3, 'b'}
• Both union() and update() will exclude any duplicate items.
• The intersection_update() method will keep only the items that are present in both sets.
• x.intersection_update(y)
• The intersection() method will return a new set, that only contains the items that are
present in both sets.
• z = x.intersection(y)
• The symmetric_difference_update() method will keep only the elements that are NOT
present in both sets.
• x.symmetric_difference_update(y)
• The symmetric_difference() method will return a new set, that contains only the
elements that are NOT present in both sets.
Ahmed Elaraby 8
• z = x.symmetric_difference(y)
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
Ahmed Elaraby 9
update() Update the set with the union of this set and others
Dictionary
• A dictionary is a collection which is unordered, changeable , indexed and do not allow duplicates.
In Python dictionaries are written with curly brackets, and they have keys and values.
• You can access the items of a dictionary by referring to its key name, inside square brackets.
• You can change the value of a specific item by referring to its key name.
• You can loop through a dictionary.
• When looping through a dictionary, the return value are the keys of the dictionary, but there are
methods to return the values as well.

• thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict) >>> {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
print(thisdict["brand"]) >>> Ford
print(len(thisdict)) >>> 3
print(type(thisdict)) >>> <class 'dict'>
thisdict["year"] = 2018
Ahmed Elaraby 10
• Dictionaries cannot have two items with the same key.

• Duplicate values will overwrite existing values.

• It is also possible to use the dict() constructor to make a dictionary.

• There is also a method called get() that will get item by key.
• x = thisdict.get("model")

• The keys() method will return a list of all the keys in the dictionary.
• x = thisdict.keys()

• The values() method will return a list of all the values in the dictionary.
• x = thisdict.values()

• The items() method will return each item in a dictionary, as tuples in a list.
• x = thisdict.items()

• To determine if a specified key is present in a dictionary use the in keyword:


• if "model" in thisdict: Ahmed Elaraby 11
print("Yes, 'model' is one of the keys in the thisdict dictionary")
• The update() method will update the dictionary with the items from the given
argument.
• thisdict.update({"year": 2020})
• Adding an item to the dictionary is done by using a new index key and assigning a
value to it:
• thisdict["color"] = "red"
• thisdict.update({"color": "red"})
• The pop() method removes the item with the specified key name:
• thisdict.pop("model")
• The popitem() method removes the last inserted item.
• thisdict.popitem()
• The del keyword removes the item with the specified key name:
• del thisdict["model"]
• The del keyword can also delete the dictionary completely:
• del thisdict
• The clear() method empties the dictionary:
• thisdict.clear()
• Make a copy of a dictionary with the copy() method:
• mydict = thisdict.copy()
• Make a copy of a dictionary with theAhmed
dict() function:
Elaraby 12
• mydict = dict(thisdict)
• Print all key names in the dictionary, one by one:
• for x in thisdict:
print(x)

• Print all values in the dictionary, one by one:


• for x in thisdict:
print(thisdict[x])

• You can also use the values() method to return values of a dictionary:
• for x in thisdict.values():
print(x)

• You can use the keys() method to return the keys of a dictionary:
• for x in thisdict.keys():
print(x)

• Loop through both keys and values, by using the items() method:
• for x, y in thisdict.items():
print(x, y) Ahmed Elaraby 13
Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
Returns the value of the specified key. If the key does not exist: insert the key,
setdefault()
with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Ahmed Elaraby 14
Arithmetic Operators

Symbol Operator Name Description


+ Addition Adds the values on either side of the operator and calculate a
result.
- Subtraction Subtracts values of right side operand from left side operand.
* Multiplication Multiplies the values on both sides of the operator.
/ Division Divides left side operand with right side operand.
% Modulus It returns the remainder by dividing the left side operand with
right side operand
** Exponent Calculates the exponential power

Ahmed Elaraby 15
Assignment Operators

Symbol Operator Name Description


= Equal Assigns the values of right side operand to left side
operand.
+= Add AND Adds right side operand value to the left side operand
value and assigns the results to the left operand.
-= Subtract AND Subtracts right side operand value to the left side
operand value and assigns the results to the left
operand.
*= Multiply AND Similarly does their respective operations and assigns
the operator value to the left operand.

Ahmed Elaraby 16
Logical Operators

Symbol Operator Name Description

or Logical OR If any of the two operands are non zero, then the
condition is true.
and Logical AND If both the operands are true, then the condition
is true.
not Logical NOT It is used to reverse the logical state of its
operand.

Ahmed Elaraby 17
logical conditions

Symbol Operator Name


a == b Equals
a != b Not Equals
a<b Less than
a <= b Less than or equal to
a>b Greater than
a >= b Greater than or equal to

Ahmed Elaraby 18
Membership Operators
• In
• The result of this operation becomes True if it finds a value in a specified
sequence and False otherwise.

• Not in
• The result of this operation becomes True if it doesn't find a value in a
specified sequence and False otherwise.

Ahmed Elaraby 19
Decision making
• Python Conditions and If statements :
• These conditions can be used in several ways, most commonly in "if statements" and loops.
• An "if statement" is written by using the if keyword.
• a = 33
• b = 200
• if b > a:
print("b is greater than a")
• Python relies on indentation (whitespace at the beginning of a line) to define scope in the code.
Other programming languages often use curly-brackets for this purpose.
• The elif keyword is pythons way of saying "if the previous conditions were not true, then try this
condition".
• if b > a:
print("b is greater than a")
• elif a == b:
print("a and b are equal")
• The else keyword catches anything which isn't caught by the preceding conditions.
• else:
print("a is greater than b") Ahmed Elaraby 20
• If you have only one statement to execute, you can put it on the same line as the
if statement.
• if a > b: print("a is greater than b")

• If you have only one statement to execute, one for if, and one for else, you can
put it all on the same line:
• a=2
• b = 330
• print("A") if a > b else print("B")

• You can also have multiple else statements on the same line:
• print("A") if a > b else print("=") if a == b else print("B")

• The and keyword is a logical operator, and is used to combine conditional


statements:
• if a > b and c > a:
print("Both conditions are True")

• The or keyword is a logical operator, and is used to combine conditional


statements:
• if a > b or a > c:
print("At least one of the conditionsAhmed
is True")
Elaraby 21
• You can have if statements inside if statements, this is called nested if
statements.
• x = 41
• if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

• if statements cannot be empty, but if you for some reason have an if


statement with no content, put in the pass statement to avoid getting
an error.
• if b > a:
pass

Ahmed Elaraby 22
While Loops
• With the while loop we can execute a set of statements as long as a condition is true.
• i=1
• while i < 6:
print(i)
i += 1
• The while loop requires relevant variables to be ready, in this example we need to define an indexing
variable, i, which we set to 1.
• With the break statement we can stop the loop even if the while condition is true:
• i=1
• while i < 6: 1
print(i)
if i == 3:
2
break 3
i += 1
• With the continue statement we can stop the current iteration, and continue with the next:
• i=0
• while i < 6: 1
i += 1 2
if i == 3: 4
continue 5
print(i)
6 Ahmed Elaraby 23
• With the else statement we can run a block of code once when the
condition no longer is true:
• i=1
• while i < 6: 1
print(i) 2
3
i += 1 4
• else: 5
print("i is no longer less than 6") i is no longer less than 6

Ahmed Elaraby 24
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).
• Anything in a sequence or list can be used in a For loop.
• Just be sure not to modify the list while looping.
• fruits = ["apple", "banana", "cherry"]
apple
• for x in fruits: banana
print(x) cherry

• Even strings are iterable objects, they contain a sequence of characters: b


• for x in "banana": a
print(x) n
a
n
Ahmed Elaraby
a
25
• With the break statement we can stop the loop before it has looped through all the items:
• fruits = ["apple", "banana", "cherry"]
• for x in fruits: apple
print(x) banana
if x == "banana":
break
• With the continue statement we can stop the current iteration of the loop, and continue with the
next:
• for x in fruits:
apple
if x == "banana":
continue cherry
print(x)
2
• To loop through a set of code a specified number of times, we can use the range() function,
5
• The range() function returns a sequence of numbers, starting from 0 by default, and increments 8
by 1 (by default), and ends at a specified number.
• for x in range(6):
11
print(x) 0 14
• for x in range(2, 6): 1 2 17
print(x) 2 3 20
• The range() function defaults to increment the sequence by 1, 3 4 23
however it is possible to specify the increment value 4 5 26
5 29
by adding a third parameter: range(2, 30, 3):
• for x in range(2, 30, 3): Ahmed Elaraby 26
print(x)
• The else keyword in a for loop specifies a block of code to be
executed when the loop is finished:
0
• for x in range(6): 1
print(x) 2
3
else: 4
print("Finally finished!") 5
Finally finished!

• Break the loop when x is 3, and see what happens with the else block:
• for x in range(6):
if x == 3: 0
break 1
2
print(x)

Ahmed Elaraby 27
Nested Loops

• A nested loop is a loop inside a loop.


• The "inner loop" will be executed one time for each iteration of the "outer loop":
• adj = ["red", "big", "tasty"]
• fruits = ["apple", "banana", "cherry"]
• for x in adj: red apple
for y in fruits: red banana
print(x, y) red cherry
big apple
• for loops cannot be empty, but if you for some reason big banana
have a for loop with no content, put in the pass big cherry
tasty apple
statement to avoid getting an error. tasty banana
• for x in [0, 1, 2]: tasty cherry
pass

Ahmed Elaraby 28
Functions
• A function is a block of code which only runs when it is called.

• You can pass data, known as parameters, into a function.

• A function can return data as a result.

• There are two kinds of functions in Python:


• Built in functions that are provided as part of Python raw_input (), type(), float(),
max(), min(),int (), str (),….
• Functions (user defined) that we define ourselves and then use.

• In Python a function is some reusable code that takes arguments(s) as


input does some computation and then returns a result or results.
Ahmed Elaraby 29
• Creating a Function : In Python a function is defined using the def keyword:
• def my_function():
print("Hello from a function")

• Calling a Function : To call a function, use the function name followed by


parenthesis and arguments in an expression:
• my_function()

• Arguments are specified after the function name, inside the parentheses. You can
add as many arguments as you want, just separate them with a comma.
• def my_function(fname):
print(fname + " Refsnes")
• my_function("Emil")
• my_function("Tobias")

Ahmed Elaraby 30
• A parameter is the variable listed inside the parentheses in the function
definition.
• An argument is the value that is sent to the function when it is called.

• A function must be called with the correct number of arguments. Meaning that if
your function expects 2 arguments, you have to call the function with 2
arguments, not more, and not less.
• def my_function(fname, lname):
print(fname + " " + lname)
• my_function("Emil", "Refsnes")

• If you do not know how many arguments that will be passed into your function,
add a * before the parameter name in the function definition.
• This way the function will receive a tuple of arguments, and can access the items
accordingly:
• def my_function(*kids):
print("The youngest child is " + kids[2])
• my_function("Emil", "Tobias", "Linus")
Ahmed Elaraby 31
• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.
• def my_function(child3, child2, child1):
print("The youngest child is " + child3)
• my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

• If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the
function definition.
• This way the function will receive a dictionary of arguments, and can access
the items accordingly:
• def my_function(**kid):
print("His last name is " + kid["lname"])
• my_function(fname = "Tobias", lname = "Refsnes")
Ahmed Elaraby 32
• If we call the function without argument, it uses the default value:
• def my_function(country = "Norway"):
print("I am from " + country)
• my_function("India")
• my_function()

• To let a function return a value, use the return statement:


• def my_function(x):
return 5 * x
• print(my_function(3))

• function definitions cannot be empty, but if you for some reason have a function
definition with no content, put in the pass statement to avoid getting an error.
• def myfunction():
pass
Ahmed Elaraby 33
Recursion
• Python also accepts function recursion, which means a defined function can call
itself.
• Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through
data to reach a result.

• def tri_recursion(k):
1
if(k > 0):
3
result = k + tri_recursion(k - 1)
6
print(result)
10
else:
15
result = 0
21
return result
• tri_recursion(6)

Ahmed Elaraby 34
lambda function
• A lambda function is a small anonymous function.

• A lambda function can take any number of arguments, but can only have
one expression.

• Syntax : lambda arguments : expression

• x = lambda a : a + 10
• print(x(5))

• x = lambda a, b : a * b
• print(x(5, 6))

Ahmed Elaraby 35

You might also like