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

Module_2_Edge_python

Python programming code
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Module_2_Edge_python

Python programming code
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Module #2

Python Collections (Arrays)


There are four collection data types in the Python programming language:
 List is a collection which is ordered and changeable. Allows duplicate members.
 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
 Dictionary is a collection which is ordered** and changeable. No duplicate members.

Python List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
thislist = ["apple", "banana", "cherry"]
print(thislist)

List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered
When we say that lists are ordered, it means that the items have a defined order, and that order will not
change.
If you add new items to a list, the new items will be placed at the end of the list.

Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has been
created.

Allow Duplicates
Since lists are indexed, lists can have items with the same value:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)

List Length
To determine how many items a list has, use the len() function:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))

List Items - Data Types


List items can be of any data type:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
list4 = ["abc", 34, True, 40, "male"]

type List
From Python's perspective, lists are defined as objects with the data type 'list':
mylist = ["apple", "banana", "cherry"]
print(type(mylist))

The list() Constructor


It is also possible to use the list() constructor when creating a new lis
thislist = list(("apple", "banana", "cherry")) # note the double round-
brackets
print(thislist)

Access Items
List items are indexed and you can access them by referring to the index number:
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])

Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])

Range of Indexes
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 list with the specified items.
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).

This example returns the items from the beginning to, but NOT including, "kiwi":
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])

This example returns the items from "cherry" to the end:


thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
Change Item Value
To change the value of a specific item, refer to the index number:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

Change a Range of Item Values


To change the value of items within a specific range, define a list with the new values, and refer to the
range of index numbers where you want to insert the new values:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

If you insert more items than you replace, the new items will be inserted where you specified, and the
remaining items will move accordingly:
Change the second value by replacing it with two new values:
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)

Change the second and third value by replacing it with one value:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)

Insert Items
To insert a new list item, without replacing any of the existing values, we can use the insert() method.
The insert() method inserts an item at the specified index:
Insert "watermelon" as the third item:
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)

Append Items
To add an item to the end of the list, use the append() method:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)

Insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
Extend List
To append elements from another list to the current list, use the extend() method.
Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

Remove Specified Item


The remove() method removes the specified item.
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

Remove the first occurance of "banana":


thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("banana")
print(thislist)

Remove Specified Index


The pop() method removes the specified index.
Remove the second item:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)

the pop() method removes the last item.


Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)

The del keyword also removes the specified index:


Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

The del keyword can also delete the list completely.


thislist = ["apple", "banana", "cherry"]
del thislist

Clear the List


The clear() method empties the list.
The list still remains, but it has no content.
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

Loop Through a List


You can loop through the list items by using a for loop:
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)

Loop Through the Index Numbers


You can also loop through the list items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])

Print all items, using a while loop to go through all the index numbers
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1

Looping Using List Comprehension


List Comprehension offers the shortest syntax for looping through lists:
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]

List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the values of an
existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.
Without list comprehension you will have to write a for statement with a conditional test inside:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
if "a" in x:
newlist.append(x)

print(newlist)

With list comprehension you can do all that with only one line of code:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)

The Syntax
newlist = [expression for item in iterable if condition == True]

Only accept items that are not "apple":


newlist = [x for x in fruits if x != "apple"]

You can use the range() function to create an iterable:


newlist = [x for x in range(10)]

Accept only numbers lower than 5:


newlist = [x for x in range(10) if x < 5]

Set the values in the new list to upper case:


newlist = [x.upper() for x in fruits]

Set all values in the new list to 'hello':


newlist = ['hello' for x in fruits]

Return "orange" instead of "banana":


newlist = [x if x != "banana" else "orange" for x in fruits]

Sort List
List objects have a sort() method that will sort the list alphanumerically, ascending, by default:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)

Sort the list numerically:


thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)

Sort the list descending:


thislist = [80, 50, 20, 82, 23]
thislist.sort(reverse = True)
print(thislist)

Case Insensitive Sort


By default the sort() method is case sensitive, resulting in all capital letters being sorted before lower
case letters:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort()
print(thislist)

Perform a case-insensitive sort of the list:


thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)

Reverse Order
What if you want to reverse the order of a list, regardless of the alphabet?
The reverse() method reverses the current sorting order of the elements.
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)

Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and
changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)

Another way to make a copy is to use the built-in method list().


thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)

Join Two Lists


There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

Another way to join two lists is by appending all the items from list2 into list1, one by one:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

for x in list2:
list1.append(x)

print(list1)

Or you can use the extend() method, where the purpose is to add elements from one list to another list:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)

Python Tuples
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set,
and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
thistuple = ("apple", "banana", "cherry")
print(thistuple)

Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that order will
not change.

Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has
been created.

Allow Duplicates
Since tuples are indexed, they can have items with the same value:

Create Tuple With One Item


To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not
recognize it as a tuple.
thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
.
Update Tuples
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.
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)

Add Items
Since tuples are immutable, they do not have a built-in append() method, but there are other ways to
add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list, add
your item(s), and convert it back into a tuple.
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)

2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item, (or
many), create a new tuple with the item(s), and add it to the existing tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y

print(thistuple)

Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called "packing" a tuple:
fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)
Using Asterisk*
If the number of variables is less than the number of values, you can add an * to the variable name and
the values will be assigned to the variable as a list:
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(green)
print(yellow)
print(red)

Loop Tuples
Same as list.

Join Two Tuples


To join two or more tuples you can use the + operator:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)

Multiply Tuples
If you want to multiply the content of a tuple a given number of times, you can use the * operator:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2

print(mytuple)

Python Sets
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple,
and Dictionary, all with different qualities and usage.
A set is a collection which is unordered, unchangeable*, and unindexed.
* Note: Set items are unchangeable, but you can remove items and add new items.
Sets are written with curly brackets.
thisset = {"apple", "banana", "cherry"}
print(thisset)
Note: Sets are unordered, so you cannot be sure in which order the items will appear.

Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by index or
key.

Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been created.
Once a set is created, you cannot change its items, but you can remove items and add new items.

Duplicates Not Allowed


Sets cannot have two items with the same value.
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)

True and 1 is considered the same value:


thisset = {"apple", "banana", "cherry", True, 1, 2}

print(thisset)
Note: The values False and 0 are considered the same value in sets, and are treated as duplicates:

Set Items - Data Types


set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
set4 = {"abc", 34, True, 40, "male"}

Access Items
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by
using the in keyword.
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

Add Items
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the add() method.
thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)
Add Sets
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)

Add Any Iterable


The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists,
dictionaries etc.).
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]

thisset.update(mylist)

print(thisset)

Remove Item
To remove an item in a set, use the remove(), or the discard() method.
thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)
Note: If the item to remove does not exist, remove() will raise an error.

Remove "banana" by using the discard() method:


thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)
Note: If the item to remove does not exist, discard() will NOT raise an error.

You can also use the pop() method to remove an item, but this method will remove a random item, so
you cannot be sure what item that gets removed.
The return value of the pop() method is the removed item.
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()

print(x)

print(thisset)

The clear() method empties the set:


thisset = {"apple", "banana", "cherry"}

thisset.clear()

print(thisset)

The del keyword will delete the set completely:


thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)

Join Sets
There are several ways to join two or more sets in Python.
The union() and update() methods joins all items from both sets.
The intersection() method keeps ONLY the duplicates.
The difference() method keeps the items from the first set that are not in the other set(s).
The symmetric_difference() method keeps all items EXCEPT the duplicates.

set1 = {"a", "b", "c"}


set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)
You can use the | operator instead of the union() method, and you will get the same result.

Join a set with a tuple:


x = {"a", "b", "c"}
y = (1, 2, 3)

z = x.union(y)
print(z)

Update
The update() method inserts all items from one set into another.
The update() changes the original set, and does not return a new set.
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)

Intersection
Keep ONLY the duplicates
The intersection() method will return a new set, that only contains the items that are present in both
sets.
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}

set3 = set1.intersection(set2)
print(set3)
You can use the & operator instead of the intersection() method, and you will get the same result.
Note: The & operator only allows you to join sets with sets, and not with other data types like you can
with the intersecton() method.
The intersection_update() method will also keep ONLY the duplicates, but it will change the original set
instead of returning a new set.
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}

set1.intersection_update(set2)

print(x)

Difference
The difference() method will return a new set that will contain only the items from the first set that are
not present in the other set.
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}

set3 = set1.difference(set2)

print(set3)
You can use the - operator instead of the difference() method, and you will get the same result.
Note: The - operator only allows you to join sets with sets, and not with other data types like you can
with the difference() method.
The difference_update() method will also keep the items from the first set that are not in the other set,
but it will change the original set instead of returning a new set.
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}

set1.difference_update(set2)

print(set1)

Symmetric Differences
The symmetric_difference() method will keep only the elements that are NOT present in both sets.
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}

set3 = set1.symmetric_difference(set2)

print(set3)
You can use the ^ operator instead of the symmetric_difference() method, and you will get the same
result.
Note: The ^ operator only allows you to join sets with sets, and not with other data types like you can
with the symmetric_difference() method.
The symmetric_difference_update() method will also keep all but the duplicates, but it will change the
original set instead of returning a new set.
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}

set1.symmetric_difference_update(set2)

print(set1)

Python Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
Dictionaries are written with curly brackets, and have keys and values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Dictionary Items
Dictionary items are ordered, changeable, and do not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
When we say that dictionaries are ordered, it means that the items have a defined order, and that order
will not change.
Unordered means that the items do not have a defined order, you cannot refer to an item by using an
index.

Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has
been created.

Duplicates Not Allowed


Dictionaries cannot have two items with the same key:
Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)

Dictionary Items - Data Types


The values in dictionary items can be of any data type:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

Using the dict() method to make a dictionary:


thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)

Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]

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

Add a new item to the original dictionary, and see that the keys list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.keys()

print(x) #before the change

car["color"] = "white"

print(x) #after the change

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

Make a change in the original dictionary, and see that the values list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.values()

print(x) #before the change

car["year"] = 2020

print(x) #after the change

Get Items
The items() method will return each item in a dictionary, as tuples in a list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.items()

print(x) #before the change


car["year"] = 2020

print(x) #after the change

Check if Key Exists


To determine if a specified key is present in a dictionary use the in keyword:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

Change Values
You can change the value of a specific item by referring to its key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

Update Dictionary
The update() method will update the dictionary with the items from the given argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})

Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:

Removing Items
There are several methods to remove items from a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

The del keyword can also delete the dictionary completely:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer
exists.

The clear() method empties the dictionary:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)

Loop Through a Dictionary


You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are
methods to return the values as well.
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)

Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be
a reference to dict1, and changes made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)

Make a copy of a dictionary with the dict() function:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)

Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}

Access Items in Nested Dictionaries


To access items from a nested dictionary, you use the name of the dictionaries, starting with the outer
dictionary:
print(myfamily["child2"]["name"])

Loop Through Nested Dictionaries


You can loop through a dictionary by using the items() method like this:
for x, obj in myfamily.items():
print(x)

for y in obj:
print(y + ':', obj[y])

Python input() Function


The input() function allows user input.

Syntax
input(prompt)
prompt A String, representing a default message before the input.
Use the prompt parameter to write a message before the input:
x = input('Enter your name:')
print('Hello, ' + x)

We can convert an input to an integer using int(). For example,


# convert user input to integer
num = int(input("Enter a number: "))
print(f'The integer number is: {num}')

We can convert an input to a floating point using float(). For example,


# convert user input to float
float_num = float(input("Enter a floating number: "))
print(f'The floating number is: {float_num}')

Python Conditions and If statements


An "if statement" is written by using the if keyword.
a = 33
b = 200
if b > a:
print("b is greater than a")
in this example we use two variables, a and b, which are used as part of the if statement to test
whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we
print to screen that "b is greater than a".

If statement, without indentation (will raise an error):


a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

The elif keyword is Python's way of saying "if the previous conditions were not true, then try this
condition".
a = 33
b = 33
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.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

Short Hand If
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")

Short Hand If ... Else


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")

One line if else statement, with 3 conditions:


a = 330
b = 330
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:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Nested If
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.")

The pass Statement


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.
a = 33
b = 200

if b > a:
pass

Python match-case Statement


The basic usage of match-case is to compare a variable against one or more values.
Syntax
The following is the syntax of match-case statement in Python -
match variable_name:
case 'pattern 1' : statement 1
case 'pattern 2' : statement 2
...
case 'pattern n' : statement n

n=int(input(“Enter n:”))
match n:
case 0: return "Monday"
case 1: return "Tuesday"
case 2: return "Wednesday"
case 3: return "Thursday"
case 4: return "Friday"
case 5: return "Saturday"
case 6: return "Sunday"
case _: return "Invalid day number"

Python Loops
Python has two primitive loop commands:
 while loops
 for loops

The while Loop


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 break Statement


With the break statement we can stop the loop even if the while condition is true:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

The continue Statement


With the continue statement we can stop the current iteration, and continue with the next:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

The else Statement


With the else statement we can run a block of code once when the condition no longer is true:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

Python 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).
This is less like the for keyword in other programming languages, and works more like an iterator
method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)

The range() Function


To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.

for x in range(6):
print(x)
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to specify the starting value
by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
for x in range(2, 6):
print(x)

The range() function defaults to increment the sequence by 1, however it is possible to specify the
increment value by adding a third parameter: range(2, 30, 3):
for x in range(2, 30, 3):
print(x)

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:
for y in fruits:
print(x, y)

The pass Statement


for loops cannot be empty, but if you for some reason have a for loop with no content, put in
the pass statement to avoid getting an error.
for x in [0, 1, 2]:
pass

You might also like