Introduction
This is a continuation of our python discussion from where we stopped in Python Made Easy - Part One. Consequently, part one is a prerequisite for this tutorial, especially for beginners in python. If you are a beginner in Python, it is highly advisable for you to go back and study part one.
In this tutorial, we shall discuss more python concepts to broaden our readers knowledge, skills and applications of python. As we did in part one and for the same reason, we are going to use replit IDE for writing and demonstrating code in this tutorial. Notwithstanding, you can use any other IDE of your choice especially if you are not new to coding.
We often use explanatory comments in our example codes, please pay attention to the comments while you are studying this tutorial. They were inserted into the codes to make it simpler and easier for you to understand. Now, without any further waste of time, let us dive into the business straight away.
Set
Set is one of the python inbuilt data types that is used to keep collections of data. The other python inbuilt data types are: List, Tuples and Dictionary. Remember that we discussed List and Tuples in part one. Sets are used to store multiple items in a variable. The items in a set are unordered, unchangeable (but you can remove and add new items) and unindexed. In addition, set does not allow duplication of items, it ignores any duplications. The general syntax for declaring a set is as shown below:
a_set = {"Item1", "Item2", "Item3",..."Itemn"}
Practice declaring a set with the example code below:
my_set = {"John","Peter", "Mark", "Paul", "James"}
print(my_set)
'''
Output:
{'James', 'John', 'Mark', 'Peter', 'Paul'}
'''
Items in set are unordered - it means when you run print command to display items in a set on the console, the order in which they appear is random. If you run the command again, you might not necessarily have the items appear in the same order as before.
Duplicates items not allowed - If any of the items in a set is duplicated, python will only recognise one of them. Note that duplicate here is case sensitive. If “james” starting with a lower case “j” is added to the items in the set above, it will not be treated as duplicate. But, if another “James” starting with upper case “J” is added, python will ignore one of them. Practice this in your IDE as shown below:
my_set = {"John", "james", "Peter", "James", "Mark", "Paul", "James"}
print(my_set)
'''
Output:
{'james', 'John', 'James', 'Mark', 'Peter', 'Paul'}
'''
In sets, True
and 1
are considered the same and hence, treated as duplicates. Similarly, False
and 0
are considered the same and therefore treated as duplicates. Practice with the lines of code below:
my_set = {"John", "james", "Peter", "James", "Mark", "Paul", "James", 0, 1, 2, 3, True, False}
print(my_set)
'''
Output:
{'james', 0, 2, 3, 1, 'John', 'James', 'Mark', 'Peter', 'Paul'}
'''
You would have noticed that when the code above is run, only one of True
or 1
appeared in the output and same goes for False
and 0
, only one of them would be displayed on the console. Usually, the first of the duplicate items is picked while the second one is ignored.
The length of a set - You can determine the length of a set, i.e the number of items in a set using the len()
function as shown below. You will observe that while counting the number of items in a set, duplicates items are ignored, that is why the total number of items in my_set
below is displayed as 10
my_set = {"John", "james", "Peter", "James", "Mark", "Paul", "James", True, 1, 2, 3, False, 0}
print(len(my_set))
'''
Output:
10
'''
Python set()
Constructor - You can also declare a set with set()
constructor by following the general syntax below:
a_set = set(("Item1", "Item2", "Item3",..."Itemn"))
Note that we did not use curly bracket with set()
constructor. Practice with the code below:
my_set = set(("John", "james", "Peter", "James", "Mark", "Paul", "James", True, 1, 2, 3, False, 0))
print(my_set)
'''
Output:
{'james', True, 2, 3, False, 'John', 'James', 'Mark', 'Peter', 'Paul'}
'''
Adding items to a set - You can add an item to a set using add()
method. Practice with the example below:
my_fruits = {"Orange", "Mango", "Banana"}
my_fruits.add("Pears")
print(my_fruits)
'''
Output:
{'Orange', 'Mango', 'Pears', 'Banana'}
'''
Inserting items from one set to the other - You can add items from another set or even from lists, tuples or dictionary to a set using update()
method. Note that update method excludes duplicate items. Practice with the example below:
my_fruits = {"Orange", "Mango", "Banana"}
my_food = {"Pizza", "Burger", "Pasta"}
my_veggies = ["Tomato", "Carrot", "Onion", "Orange"]
my_fruits.update(my_food)
print(my_fruits)
my_fruits.update(my_veggies)
print(my_fruits)
'''
Output:
# my_friuts after the first update() method operation
{'Pasta', 'Banana', 'Orange', 'Mango', 'Burger', 'Pizza'}
# my_friuts after the second update() method operation
{'Burger', 'Orange', 'Tomato', 'Pizza', 'Banana', 'Mango', 'Carrot', 'Onion', 'Pasta'}
'''
Combining two sets using union()
method - union()
method combines items from both sets (excluding any duplicate) to form a new set. Practice with the example below:
alpha = {"a", "b", "c", "d"}
numeric = {"1","2", "3", "4"}
alpha_numeric = alpha.union(numeric)
print(alpha_numeric)
'''
Output:
{'b', '3', '2', 'a', 'd', '4', '1', 'c'}
'''
To keep only items that are present in both sets, use the intersection_update()
method. Practice with the example below:
fruit_list = {"Pear", "Papaya", "Blackberry", "Raspberry", "Mango", "Banana"}
my_fruits = {"Raspberry", "Mango", "Banana"}
fruit_list.intersection_update(my_fruits)
print(fruit_list)
'''
Output:
{'Mango', 'Raspberry', 'Banana'}
'''
The intersection()
method will create a new set that contains only the items that are common to to both sets. Practice with the example below:
fruit_list = {"Pear", "Papaya", "Blackberry", "Raspberry", "Mango", "Banana"}
my_fruits = {"Raspberry", "Mango", "Banana"}
new_fruit_list = fruit_list.intersection(my_fruits)
print(new_fruit_list)
'''
Output:
{'Mango', 'Raspberry', 'Banana'}
'''
The symmetric_difference_update()
method keeps items which are not common to both sets. Practice with the example below:
fruit_list = {"Pear", "Papaya", "Blackberry", "Raspberry", "Mango", "Banana"}
my_fruits = {"Raspberry", "Mango", "Banana", "Orange"}
fruit_list.symmetric_difference_update(my_fruits)
print(fruit_list)
'''
Output:
{'Blackberry', 'Orange', 'Papaya', 'Pear'}
'''
The symmetric_difference()
method creates a new set that contain items which are not common to both sets. Practice with the example below:
fruit_list = {"Pear", "Papaya", "Blackberry", "Raspberry", "Mango", "Banana"}
my_fruits = {"Raspberry", "Mango", "Banana", "Orange"}
new_fruit_list = fruit_list.symmetric_difference(my_fruits)
print(new_fruit_list)
'''
Output:
{'Blackberry', 'Orange', 'Papaya', 'Pear'}
'''
Removing items from a set - This can be achieved with any of the following:
remove()
method - it will take out the specified item from the set and if the specified item does not exist in the set, it will throw up an error.discard()
method - it will take out the specified item from the set and if the specified item does not exist in the set, it will NOT throw up an error.pop()
method - this will remove a random item from the setclear()
method - this removes all the items in the set but the set still existsdel
keyword - del keyword will delete the set outrightly, the set will no longer exist
Practice with examples below:
my_fruits = {"Orange", "Mango", "Banana"}
my_food = {"Pizza", "Burger", "Pasta"}
my_veggie = {"Tomato", "Carrot", "Onion"}
my_fruits.remove("Mango")
print(my_fruits)
my_food.discard("Pasta")
print(my_food)
my_veggie.pop()
print(my_veggie)
my_fruits.clear()
print(my_fruits)
del my_food #If you try to print my_food after this line you will receive an error message because my_food no longer exists.
print(my_food)
Dictionary
Dictionary is one of python inbuilt data types that is used to keep data values in key:value
pairs inside a curly bracket. Items in a dictionary are ordered (except in the older version of python before version 3.7), changeable and do not allow duplicates. Practice with an example of a dictionary that contains information about a student:
student = {"Name": "John", "Age": 25, "Gender": "Male", "Height": 1.75}
print(student)
'''
Output:
{'Name': 'John', 'Age': 25, 'Gender': 'Male', 'Height': 1.75}
'''
If you duplicate a key in dictionary, python will read the key once and assign the most recent value to the key. In the code below, Age will be printed once in the console with assigned value of 35:
student = {"Name": "John", "Age": 25, "Gender": "Male", "Height": 1.75, "Age": 40, "Age": 35}
print(student)
'''
Output:
{'Name': 'John', 'Age': 35, 'Gender': 'Male', 'Height': 1.75}
'''
You can determine the number of items (key:value pairs
) in a dictionary with len()
function. Note that python will ignore duplicate items. Try with the code below:
student = {"Name": "John", "Age": 25, "Gender": "Male", "Height": 1.75, "Age": 40, "Age": 35}
print(len(student))
'''
Output:
4
'''
You can declare a dictionary with dict()
constructor by turning the key:value
pairs into variables with each variable separated by a comma and pass them in as the arguments in dict()
function. Try with the code below:
student = dict(Name = "John", Age = 25, Gender = "Male", Height = 1.75)
print(student)
'''
Output:
{'Name': 'John', 'Age': 25, 'Gender': 'Male', 'Height': 1.75}
'''
You can access the values in a dictionary by referencing the key name inside a square bracket or by using get()
method. Practice with the codes below:
student = {"Name": "John", "Age": 25, "Gender": "Male", "Height": 1.75}
name = student["Name"]
print(name)
# note that the variable name can be anything instead of name, e.g label, x or a. We used name because it is more meaningful and clearer in this context. Let us change the name to x
x = student["Name"]
print(x)
# Let us do the same to Age
age = student["Age"]
print(age)
y = student["Age"]
print(y)
#Let us use get() method to access Gender and Height values
gender = student.get("Gender")
print(gender)
height = student.get("Height")
print(height)
You can generate a list of keys in a dictionary using keys()
method. Similarly, you can return a list of values in a dictionary with values()
method and a list of items (key:value pairs
) in a dictionary using items()
method. Practice with the codes below:
student = {
"Name": "John",
"Age": 25,
"Gender": "Male",
"Height": 1.75
}
# You can rearrange a dictionary as we did to student above to make your code more readable, especially when you have several key:value pairs or nested dictionary.
my_keys = student.keys() # this returns a list of the dictionary's keys
my_values = student.values() # this returns a list of all the values in the dictionary
my_items = student.items() # this returns a list containing a tuple for each key value pair
print(my_keys)
print() # this is just to create space between two prints
print(my_values)
print() # this is just to create space between two prints
print(my_items)
You can check to confirm if a specified key exist in a dictionary using in
keyword. Practice with the codes below:
student = {"Name": "John",
"Age": 25,
"Gender": "Male",
"Height": 1.75,
}
if "Height" in student:
print("Yes, Height is in the dictionary")
else:
print("No, Height is not in the dictionary")
'''
Output:
Yes, Height is in the dictionary
'''
You can change the value of a given item by writing the dictionary name followed by the key name enclosed in a square bracket. You can also used the same approach to add item to the dictionary. Alternatively, you can change value of a given item or add a new item to a dictionary using update()
method. For update()
method to work, the *argument must be a dictionary or an iterable objects with key:value
pairs. Practice with the codes below:
*(argument(s) is/are value(s) you pass into the parenthesis at the front of a function when you call the function)
student = {"Name": "John",
"Age": 25,
"Gender": "Male",
"Height": 1.75,
}
student["Name"] = "Bradley" # this line and the next two are used to change the value of a key using bracket notation
student["Age"] = 20
student["Height"] = 1.60
student["Weight"] = 70 # this line is used to add a new item using bracket notation
student.update({"House": "Mansion"}) # this line is used to add a new item using update() method
print(student)
student.update({"Name": "Laura"}) # this line and the next two are used to change the value of a key using update() method
student.update({"Gender": "Female"})
student.update({"Height": 1.65})
print(student)
You can remove items from a dictionary using any of the following:
pop()
method - it removes the item with the specified key namepopitem()
method - it removes the last inserted itemclear()
method - it removes all the items in the dictionary, that is, it empties the content of the dictionary but the dictionary still exits, hence, you can still print the dictionary.del
keyword - it removes the item with the specified key name. If you fail to specify a key name, del keyword will delete the entire dictionary and you will get an error message if you try to print the dictionary after it has been deleted.
Practice each of the concept above with the codes below on your IDE, pay attention the comments:
student = {"Name": "John",
"Age": 25,
"Gender": "Male",
"Height": 1.75,
"Weight": 70,
}
student.pop("Weight") # this line removes Weight and its value
print(student)
student.popitem() # this line removes Height, the last item
print(student)
del student["Gender"] # this line removes Gender and its value
print(student)
student.clear() # this line removes all items, so the dictionary is empty
print(student)
del student # this line delete the dictionary, so the variable student does not exist again from this point
print(student) # this line prints an error because the variable student does not exist anymore
You can make a copy of a dictionary with copy()
method or with dict()
function. The copy created with any of this approach will be independent of subsequent changes made to the original dictionary. This will not be the case if you attempt to create a copy of a dictionary with assignment operator =
, for example saying my_dictA = my_dictB
will not give you a copy because my_dictB
is just a reference to my_dictA
. Hence, every changes that is made in my_dictA
will automatically reflect in my_dictB
. Practice with the codes below on your IDE:
student = {"Name": "John",
"Age": 25,
"Gender": "Male",
"Height": 1.75,
"Weight": 70,
}
new_student = student.copy()
print(new_student)
print() # this is just to create a space between the two prints
my_student = dict(student)
print(my_student)
print() # this is just to create a space between the two prints
student["Name"] = "Benson"
print(student)
print() # this is just to create a space between the two prints
print(new_student)
print() # this is just to create a space between the two prints
print(my_student)
In the exercise above, you will notice that new_student
and my_student
retained the original items in student even after the “Name”
value in student
was changed to “Benson”
. This would not have been the case if we had attempted to use assignment operator =
to create a copy of student. In that case, subsequent changes made to student
will reflect in the copy we created using assignment operator as illustrated in the code below, where the “Name”
value was also updated to “Benson”
in new_student
when the update was made in student
. Try it on your IDE:
student = {"Name": "John",
"Age": 25,
"Gender": "Male",
"Height": 1.75,
"Weight": 70,
}
new_student = student
print(new_student)
print() # this is just to create a space between the two prints
student["Name"] = "Benson"
print(student)
print() # this is just to create a space between the two prints
print(new_student)
Nested Dictionaries
This is a situation where you have a dictionary or multiple dictionaries inside another dictionary. Practice with the codes below:
my_friends = {
"Tom": {
"age": 23,
"gender": "male"
},
"Jerry": {
"age": 21,
"gender": "female"
},
"Harry": {
"age": 19,
"gender": "male"
},
}
print(my_friends)
'''
Output:
{'Tom': {'age': 23, 'gender': 'male'}, 'Jerry': {'age': 21, 'gender': 'female'}, 'Harry': {'age': 19, 'gender': 'male'}}
'''
Alternatively, you can create each of items in my_friends as separate dictionaries and then add them to a new dictionary called my_friends or whatever name you want to call it. Practice with the codes below in your IDE:
Tom = {
"age": 23,
"gender": "male"
}
Jerry = {
"age": 21,
"gender": "female"
}
Harry = {
"age": 19,
"gender": "male"
}
my_friends = {
"Tom": Tom,
"Jerry": Jerry,
"Harry": Harry
}
print(my_friends)
# Note that in my_friends, "Tom", "Jerry" and "Harry" in double quote are keys and therefore can be named anything you like and the code will still work. Just ensure that they are unique and as best practice, ensure that they are meaningful within the context of your code. See the example below:
my_siblings = {
"first_born": Tom,
"second_born": Jerry,
"last_born": Harry
}
print() # this is just to create a space between the two prints
print(my_siblings)
'''
Output for my_friends:
{'Tom': {'age': 23, 'gender': 'male'}, 'Jerry': {'age': 21, 'gender': 'female'}, 'Harry': {'age': 19, 'gender': 'male'}}
Output for my_siblings:
{'first_born': {'age': 23, 'gender': 'male'}, 'second_born': {'age': 21, 'gender': 'female'}, 'last_born': {'age': 19, 'gender': 'male'}}
'''
You can access items in a nested dictionary by using the name of the dictionaries starting with the outermost dictionary. Practice the codes below on your IDE:
Tom = {
"age": 23,
"gender": "male"
}
Jerry = {
"age": 21,
"gender": "female"
}
Harry = {
"age": 19,
"gender": "male"
}
my_friends = {
"Tom": Tom,
"Jerry": Jerry,
"Harry": Harry
}
print(my_friends)
print() # this is just to create a space between the two prints
my_siblings = {
"first_born": Tom,
"second_born": Jerry,
"last_born": Harry
}
print(my_siblings)
print() # this is just to create a space between the two prints
print(my_friends["Tom"]["age"])
print() # this is just to create a space between the two prints
print(my_siblings["last_born"]["gender"])
Code Blocks
A code block are lines of code which are executed together as a unit. In python, the first line of a code block is usually terminated with a colon sign :
while the subsequent line(s) of codes within the block are indented. Python takes colon and indentation very seriously whenever it is required. When you miss the colon, you will definitely get an error. And if you fail to indent properly, you will either get an error or the output of your code might be widely different from what you intended. So you need to pay serious attention to use of colon and indentation. Luckily, python will automatically indent for you provided you terminate the first line of the code block with colon sign. Line(s) of codes which are out of the indentation are said to be out of the code block and can only run after the execution of code block. Common examples of code blocks are: function, if statement (and its associated keywords; elif and else) while loop and for loop.
The while Loop
Python has two types of loops, the while
loop and for
loop. while
loop is used to execute a set of instructions repeatedly as long as a specified boolean condition is True
. For while
loop to work, we need to declare at least a variable to guide the operation of the loop. Most times, an indexing variable is set beforehand in while
loop. The general syntax will look like this:
variable = value
while (state the condition):
lines of code to be executed
Let us go to our IDE and practice this with a real examples, pay attention to the comments in the examples:
cycle = 5 # to set the number of time we want the code to execute
count = 0 # to count the number of times the code is executed
while count < cycle: # the condition that is checked before each loop
print(count)
count += 1 # this is an alternative and shorter way of writing: count = count + 1
print() # this is just to create a space between the two prints
# note that python executes the code from top to bottom, so the print statement will be executed first, then the count will be incremented by 1. This way, the printing of count will start from and exclude 5. If you want the count to start from 1 and include 5, you need to place the count += 1 before print statement as shown below:
cycle = 5
count = 0
while count < cycle:
count += 1
print(count)
If you want to make the count a count down, that is from the highest to lowest you can do it by modifying the code as shown below:
cycle = 5
count = cycle # to set the initial count to cycle value
while count > 0:
print(count)
count -= 1
'''
Output:
5
4
3
2
1
'''
We can use while loop to perform other tasks other than printing the count. We can use it to print a sentence or phrase a number of time. Try the code below in your IDE:
cycle = 5
count = 0
while count < cycle:
print("I am learning Python on Tutorialsnote")
count += 1
print("Python is done with the loop")
'''
Output:
I am learning Python on Tutorialsnote
I am learning Python on Tutorialsnote
I am learning Python on Tutorialsnote
I am learning Python on Tutorialsnote
I am learning Python on Tutorialsnote
Python is done with the loop
'''
You can make the code a bit interactive by asking user to supply certain data and the cycle value. Practice with the code below:
name = input("Enter your name: ")
cycle = input("Enter a number: ")
cycle = int(cycle) # to convert cycle to integer
count = 0
while (count < cycle):
print(f"Hello {name}! You entered {cycle} that's why I'm repeating this {cycle} times") # *f-string is an alternative means of printing variable in a string instead of concatenation
print() # this is just to create a space between the two prints
count += 1
*Recall we discussed formatted string for printing and user input in part one of this tutorial. If you found it difficult to understand any of them, just check out Python Made Easy - Part One.
You can use break
statement to stop a loop even when the while condition is true by specifying another condition using if
statement. Practice with the code below:
cycle = 5
count = 0
while count < cycle:
print(count)
if count == 2:
break
count += 1
print("Done!")
'''
Output:
0
1
2
Done!
'''
You can make python to skip a specific iteration and move to the next one with continue
statement. Practice with the code below:
cycle = 5
count = 0
while count < cycle:
count += 1
if count == 3:
continue
print(count)
print("Done!")
# Output of the code above will exclude 3.
'''
Output:
1
2
4
5
Done!
'''
You can use else
statement to run another block of code when the while condition is no longer true. Practice with the codes below:
cycle = 5
count = 0
while count < cycle:
print(count)
count += 1
else:
name = input("Enter your name and press the enter key to exit: ")
print(f"Goodbye {name}")
In the code above, a condition count < cycle
is attached to the while
statement. This condition puts a limit on the loop, the loop will only keep going as long as count < cycle
. Once the condition is no longer True
, the loop will stop and the else
block will be executed.
The while True
Statement
The while True
statement is a variant of while
loop that is used together with break
statement to run a block of code repeatedly. The break
statement is used to control or stop the loop upon occurrence of a specified condition so that the loop will not run perpetually. With while True
, you do not need an indexing variable to be set beforehand. while True
is usually used to create interactive apps that accept and process user input. Practice with the code below:
while True:
count = int(input("Enter a number: "))
for item in range(count+1):
if count <= 10:
print(item)
break
print("Done!")
In the code above, if you delete or comment out break, the loop will continue forever. It will keep asking the user for a number at the end of the loop and the last line of code print("Done!") will never get executed. Try it and see.
The for
Loop
The for
loop is used to iterate over the items in a sequence such as a string, a list, a set, a tuple or a dictionary. Unlike while
loop, for
loop does not need an indexing variable to be set beforehand. The general syntax of a for loop is as follows:
for variable in a_sequence:
lines of code to be executed
Note that a_sequence in the general syntax above can be a string, a tuple, a list, a range, etc. Also, pay attention to the colon that terminates for
loop line. If you miss it out python will yell at you. To make it clearer, practice with the code below. Pay attention to the explanatory comments:
my_string = "Hello World"
for i in my_string:
print(i)
print() # This is just to create space between two prints
names = ("Michael", "James", "Teddy", "Harry")
for i in names:
print(i)
# Not that i is a variable and can be called anything. For example, it can be changed to name to make it more meaningful in the context of this code as shown below:
print() # This is just to create space between two prints
for name in names:
print(name)
You can terminate the loop before it iterates through all the items in the sequence with combination of if
and break
statements. Practice with the examples below:
names = ("Michael", "James", "Teddy", "Harry")
for name in names:
print(name)
if name == "Teddy":
break
'''
Output:
Michael
James
Teddy
'''
In the example above, Teddy is printed in the output because the print command comes before the if statement that sets the condition to break the loop. Again, the point to note here is python executes code instructions line by line and block by block. In the example below, Teddy will not printed because the print command is out of the if
block (note the if
block is inside for
loop block) but within for
loop block and comes after the if
condition has been satisfied and the break command has been executed. Try it out on your IDE:
names = ("Michael", "James", "Teddy", "Harry")
for name in names:
if name == "Teddy":
break
print(name)
'''
Output:
Michael
James
'''
To enhance your understanding line by line and block by block “rule”, try the following scenarios on your IDE and review the outcome on your console:
Place a print(name)
command in the if
block before the break
statement:
names = ("Michael", "James", "Teddy", "Harry")
for name in names:
if name == "Teddy":
print(name)
break
'''
Output:
Teddy
'''
Add another print(name)
command outside the for
loop block to the code above:
names = ("Michael", "James", "Teddy", "Harry")
for name in names:
if name == "Teddy":
break
print(name)
print("\nHere is the output print(name) command outside the for loop block:")
print(name)
'''
Output:
Michael
James
Here is the output print(name) command outside the for loop block:
Teddy
'''
When you review the output of the code, you will see clearly that python executes code instruction line by line and block by block.
You can jump the current iteration of the loop and move to the next with continue
statement. Practice with the code below:
names = ("Michael", "James", "Teddy", "Harry")
for name in names:
if name == "Teddy":
continue
print(name)
'''
Output:
Michael
James
Harry
'''
You can use for
loop and continue
statement to filter numbers as demonstrated in the code below. The code will skip iteration of even numbers and print out only the odd numbers in the list or range of numbers:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for number in numbers:
if number % 2 == 0: # We used modulus operation to set the condition. x % y means x mod y. That is, divide x by y and return the remainder. In this case even_numbers % 2 will be 0.
continue
print(number)
print() # this is just to create space
# Instead of assigning long list of numbers to variable numbers, we can use range() function to generate a list of numbers. This is more efficient if you have plenty of numbers to work with. The code below will acchieve the same result as the code above
numbers = range(1,16)
for number in numbers:
if number % 2 == 0:
continue
print(number)
You can modify either of the code above to skip odd numbers and print even numbers by deleting the continue
statement in the if
block and indent the print(number)
command to move it into the if
block as shown below:
numbers = range(1,16)
for number in numbers:
if number % 2 == 0:
print(number)
'''
Output:
2
4
6
8
10
12
14
'''
You can use else
keyword in a for
loop to specify a block of code to be executed when the loop cycle is completed. Practice with the codes below:
names = ["Peter", "Steve", "Natasha"]
for name in names:
print(name)
else:
print("There are no more names in the list")
'''
Output:
Peter
Steve
Natasha
There are no more names in the list
'''
Note that the else
block will not be executed if the loop is stopped by a break statement. Practice with the codes below:
names = ["Peter", "Bruce", "Steve", "Tom", "Natasha"]
for name in names:
if name == "Steve":
break
print(name)
else:
print("The list has been printed")
'''
Output:
Peter
Bruce
'''
Nested Loops
A nested loop is a loop inside another loop. In such scenario, the inner loop will be executed one time for each iteration of outer loop. Practice with the codes below:
adjectives = ["Pretty", "Agile", "Smart" ]
names = ["Laura", "Amy", "Natasha"]
for adjective in adjectives:
for name in names:
print(adjective, name)
'''
Output:
Pretty Laura
Pretty Amy
Pretty Natasha
Agile Laura
Agile Amy
Agile Natasha
Smart Laura
Smart Amy
Smart Natasha
'''
The range()
Function
The range()
function is used to return a series of numbers. If just a number is passed as an argument in the range()
function. When you loop through a range, by default, the series starts from zero, increments by 1 and exclude the number that is passed in. However, you can specify the starting number and the increment value as illustrated in the general syntax below.
a_range = range(a, b, c)
In the general syntax illustration above:
a - is the starting number (or the lower limit of the range)
b - is the upper limit of the range. if the upper limit value is the only argument passed into a range, by default, the range series will start from 0, increment by 1 and exclude the upper limit in the series
c - is the increment value
Note, you can pass in only a and b and the default increment of 1 will apply but you cannot pass in only b and c.
Practice with examples below in your IDE:
my_range = range(7)
print(my_range)
'''
Output:
range(0, 7)
'''
The code above returns range(0, 7)
, this aligns with the fact that the series in a range starts from 0 if it is not specified. If you loop through the range, you will get values from 0 to 6. When you loop through a range, the starting number (lower limit of the range) is included in the series that is returned but the upper limit of the range is excluded. Try the code below in your IDE:
my_range = range(5)
for number in my_range: #number can be anything, e.g i, j or k etc
print(number)
'''
Output:
0
1
2
3
4
'''
Now, let us look at an example with a starting number. In the code below the range has a lower limit of 2 and upper limit of 7. The series that will be returned when you loop through the range will include 2 but exclude 7. Try the code below in your IDE:
my_range = range(2, 7) # range(2,7) means values from 2 to 7 but excluding 7
for number in my_range:
print(number)
'''
Output:
2
3
4
5
6
'''
As mentioned earlier, when you loop through a range the default increment value is 1, but increment value can be stated by adding a third argument as shown in the code below:
my_range = range(2, 12, 3)
for number in my_range:
print(number)
'''
Output:
2
5
8
11
'''
Python pass
Statement
Code blocks such as if
statements, while
loops, for
loops, functions (we are going to discuss functions in the next section) etc, cannot be left empty without content. The pass
statement can be used as a placeholder for the content of the code block to avoid getting an error if for any reason, you have a code block without content. Practice with the example below:
names = ["Peter", "Bruce", "Steve", "Tom", "Natasha"]
for name in names:
pass
x = 0
while x < len(names):
pass
for name in names:
if name == "Steve":
pass
If you comment out or delete the pass statement in any of the code block above, you will get an error message.
Python Functions
A function is a reusable code block that performs a specific task and executes only when it is called. Functions facilitates code reusability and hence avoid unnecessary code repetition. In addition, functions facilitates segmentation of complex program into modules which are simpler and hence, makes programming, debugging and maintenance easier. In Python, a function is defined with def
keyword. The general syntax for declaring a function is as shown below:
def functionname(parameter_1, parameter_2, ...parameter_x):
#lines of code to be executed
Function Naming Rules - all the rules that applies to naming variables also apply to function naming. We discuss this in part one.
You can declare a function without any parameter as in the case of the first example below. Declaring a function with parameters gives us the opportunity to create a more versatile functions. Let us declare a function following the illustration of the general syntax above but excluding the parameters:
def greetings():
print("Hello Student")
When you run the code above, nothing gets printed on the console because the function was not called. And the fact that we did not get an error is a reliable confirmation that our code syntax is correct. Now, to call the function, we use the function name followed by parenthesis as shown below. Note that the line of code greetings()
for calling the function is outside the function block:
def greetings():
print("Hello Students")
greetings()
'''
Output:
Hello Students
'''
Here is another simple function that performs the task of adding two numbers stored in variables numa
and numb
. Try the code on your IDE:
def my_sum():
numa = 5
numb = 12
print(numa + numb)
my_sum()
'''
Output:
17
'''
The function above can only perform sum of 5 and 12, we can make the function more versatile by specifying parameters while declaring the function. That way, my_sum()
function can be used to compute the sum of any two numbers by passing them in as arguments when calling my_sum()
as shown below:
def my_sum(a, b):
print(a + b)
my_sum(12, 200) # this will return 212 on the console
my_sum(8, 12) # this will return 20 on the console
my_sum(33, 42) # this will return 75 on the console
my_sum(28, -3) # this will return 25 on the console
We can make my_sum()
function interactive by applying some of the other concepts we have learnt. In the code below, while True
is used to create a loop to enable user to perform addition operation as many time as they want. Then the if
and the break
statement was used to allow the user to decide if they want to continue with addition operations or exit the program. Try the code below in your IDE:
def my_sum():
name = input("Enter your name: ")
print(f"Hello {name}! Enter the numbers you want to add in the prompt below:\n")
while True:
numa = int(input("Enter the first number: "))
numb = int(input("Enter the second number: "))
print(f"\n{numa} + {numb} = {numa + numb}\n")
if input(f"{name}! Do you want to perform another addition? (y/n): ") == "n":
print(f"Bye {name}!")
break
my_sum()
By using parameter while declaring the function, we can also make the output of greetings()
functions specific to a named student. That is we can say Hello to a named student rather than “Hello Students” as show below:
def greetings(name):
print(f"Hello {name}")
greetings("John") # this will return "Hello John" on the console
#Alternatively, you can declare a variable to ask user for their name, then pass the variable to the function
my_name = input("Enter your name:")
greetings(my_name)
Parameter and Argument in functions
A function parameter is a variable enclosed in the functions parentheses when the function is declared. An argument is the variable (parameter) value that is passed in when the function is called. A function must be called with the right number of arguments. If the number parameters that was set during the function definition (declaration) is two, you must call the function with two arguments, if you attempt to call the function with less or more than two arguments, you will have an error. Practice with the example below:
def greetings(name, age):
print(f"Hello {name}! You are {age} years old")
greetings("Johnson", 28)
greetings("Amy", 22)
greetings("Daniel", 25)
greetings("Rick") # this line will give an error because it only assigns one argument to the function
Keyword Arguments - You can pass in argument with the key = value syntax. When you do this, the order of argument does not matter but you must still pass the correct number of arguments when calling the function. That is, the number of arguments you pass when you call the function must be equal to the number of parameters set up during the function declaration. If the function has 3 parameters, you must pass 3 arguments when calling it. In the example below, if you only pass two arguments instead of three, you will get an error:
def my_sum(a, b, c):
print(a + b + c)
my_sum(a=5, c=8, b=17)
'''
Output:
30
'''
Arbitrary Arguments (*args
) - This is used in a situation where you want your function to accommodate any number of arguments, thereby making the function more versatile. This is achieved by adding an asterisk *
before the parameter name while declaring the function. This way the function will receive a tuple of arguments and can have access to items as appropriate. The first example below will redefine my_sum()
such that it can add multiple numbers instead of a pair of numbers:
def my_sum(*a):
result=0
for item in a:
result += item # this is the same as result = result + item
print(result)
my_sum(10,20,30,40,50)
my_sum(250,500)
# Note that the print() command is out of the for loop block. If you include the print() command in the for loop block, it will print the result for each iteration of the loop
'''
Output:
150
750
'''
We can use the same concept to declare a function for computing multiplication of numbers as shown below:
def my_multiple(*a):
result=1
for item in a:
result *= item # this is the same as result = result * item
print(result)
my_multiple(2,5,9)
my_multiple(200,500)
'''
Output:
90
100000
'''
Arbitrary Keyword Arguments (**kwargs
) - If you want your function to accept any number of keyword arguments, add two asterisk **
before the parameter while you are declaring the function. When you do this, the function will accept a dictionary of arguments and can access them accordingly. Practice with example codes below:
def student_age(**student):
for i in student.items(): #recall that items() method returns a tuple with the key and value of each item in the dictionary
print(i)
student_age(Daniel=15, Kim=12, Jason=14, Darren=13)
'''
Output:
('Daniel', 15)
('Kim', 12)
('Jason', 14)
('Darren', 13)
'''
Your can use values()
method to extract only the values as shown below:
def student_age(**student):
for i in student.values():
print(i)
student_age(Daniel=15, Kim=12, Jason=14, Darren=13)
'''
Output:
15
12
14
13
'''
You can also use the values()
method to modify my_sum()
function we declared earlier to allow it accept any number of key arguments as shown below:
def my_sum(**a):
result = 0
for i in a.values():
result += i
print(result)
my_sum(a=5, c=8, b=17, d=10)
'''
Output:
40
'''
Similarly, you can access only the keys using keys()
method as shown below:
def student_age(**student):
for i in student.keys():
print(i)
student_age(Daniel=15, Kim=12, Jason=14, Darren=13)
'''
Output:
Daniel
Kim
Jason
Darren
'''
Default Parameter Value - If you attempt to call a function with parameter(s), without passing the argument(s), Python will give you an error. You can avoid this by assigning default value(s) to the function parameter(s) during function definition (declaration). So, when you call the function without argument, it uses the default value(s) rather than throwing out error. Practice with the example below:
def greetings(name = "Daniel"): #Daniel is the default value
print(f"Hello {name}")
greetings("John")
greetings() #Calling the function without argument
greetings("Amy")
'''
Output:
Hello John
Hello Daniel
Hello Amy
'''
Passing Different Data Types as Argument - You can pass any data type as an argument to a function and it will be treated as the same data type inside the function. For example, if you send a list as an argument, it will still be a list when it gets to the function. Practice with example codes below:
def my_class(students):
for student in students:
print(student)
year_4 = ["James", "Amy", "Tom"]
my_class(year_4)
'''
Output:
James
Amy
Tom
'''
Here is another example that returns the sum of numbers in a list for you to practice:
def my_sum(numbers):
result = 0
for x in numbers:
result += x
print(result)
my_numbers = [1, 2, 3, 4, 5]
my_sum(my_numbers)
'''
Output:
15
'''
The return
Keyword - return
keyword is used to terminate a function and give the value from the execution of the function’s code instructions when the function is called. Practice with the example below:
def my_sum():
numa = 5
numb = 12
return numa + numb
add = my_sum()
print(add)
'''
Output:
17
'''
The return
command does not print the output on the console but it makes the value available when the function is called. That is why we stored and thereby called the function my_sum()
in the variable add and then used print command to print add. When you run the the code below, nothing will be displayed on the console, and you will not get error either which is a confirmation that the code is syntactically correct:
def my_sum():
numa = 5
numb = 12
return numa + numb
my_sum()
If you want the output of my_sum()
displayed on the console, you need to write more lines of code as we did in the first example above. Alternatively, you can call the function directly inside print command or use print command in the function block instead of return statement as shown below:
def my_sum():
numa = 5
numb = 12
return numa + numb
print(my_sum())
# alternative approach, use print() command in the function block:
def my_sum():
numa = 5
numb = 12
print(numa + numb)
my_sum()
Any other statement written within the function block after the return
statement will not be executed. Because the return
statement returns the output of the function and terminate the function. That is why the code below will not display anything on the console:
def my_sum():
numa = 5
numb = 12
return numa + numb
print(numa + numb) # this line will not be executed because it is after the return statement
my_sum()
If you want the output to be displayed on the console, print statement (command) should come before the return statement as shown below:
def my_sum():
numa = 5
numb = 12
print(numa + numb)
return numa + numb
my_sum()
'''
Output:
17
'''
The lambda
function
A lambda
function is an “anonymous” (nameless) function that is created with keyword lambda
, which can accept parameters but can only have one expression. The general syntax for a lambda function is as shown below:
lambda parameters : expression
Note that: 1) you can declare a lambda
function without a parameter and 2) lambda
does not need return
statement, it returns the result of the expression on its own. In the example below, we declared a lambda
function without parameter and assigned it to a variable greetings
(Assigning a lambda
function to a variable gives us the opportunity to call it like a regular def
function). To execute the function, we called it with the second line of code:
greetings = lambda : print("Hello Students")
greetings() # to call the lambda function
'''
Output:
Hello Students
'''
In the next code below, we modified the lambda
function with a parameter (name) to enable the function to accept argument and customise the greetings. Then, we called the functions twice passing in "Laura"
and "Darren"
as arguments respectively. Try it on your IDE:
greetings = lambda name: print(f"Hello {name}")
greetings("Laura") # to call the lambda function
greetings("Darren") # to call the lambda function
'''
Output:
Hello Laura
Hello Darren
'''
We can make the function more versatile by adding another parameter (age) as shown below. Try it on your IDE:
greetings = lambda name, age: print(f"Hello {name}! You are {age} years old")
greetings("Laura", 22) # to call the lambda function
'''
Output:
Hello Laura! You are 22 years old
'''
We can also use lambda
function for computing values. In the example below, we declared a lambda
function with parameters a, b & c and then assigned it to a variable my_sum. Finally, we called the function as an argument for a print command. Try it on your IDE:
my_sum = lambda a,b,c : a + b + c
print(my_sum(2,3,5))
'''
Output:
10
'''
Alternatively, we can incorporate the print()
command into the lambda
function and call the function passing in necessary arguments as shown below. Try it on your IDE:
my_sum = lambda a,b,c : print(a + b + c)
my_sum(2,3,5) # To call the function
'''
Output:
10
'''
A lambda
function can be used as an anonymous function inside another regular function. In the example below, x
is a number that will be used to set multiples of x
for any other given number y
. We declared the main function my_num()
with parameter x
and inside it, we declared a lambda
function with parameter y
.
def my_num(x):
return lambda y : x * y
multiple_of_five = my_num(5) # to call the def function
multiple_of_six = my_num(6) # to call the def function
five = multiple_of_five(6) # to call the lambda function
six = multiple_of_six(4) # to call the lambda function
print(five)
print(six)
'''
Output:
30
24
'''
Projects
Let us wrap up this tutorial with three projects that will attempt to put some or possibly all of the concepts we have learnt to use. The example solutions we provided are longer than they should have been because we used plenty of explanatory comments to aid your understanding. Please, pay attention to the comments. The best way to practice the example solutions is to do the following:
Open two sessions of your IDE.
*Copy and paste the example code into one of the IDE sessions to enhance the readability of the example code, but do not run the code on this session, it is intended to be read only.
Study the code you pasted on the first session of your IDE
When you are done with step 3 above, try the code out by typing (not copying and pasting) on the second session of your IDE
If you are stuck at any point, go back to the example code on the first IDE to clarify the issue
*We do not encourage copying and pasting code because this habit is detrimental to your learning. Coding is better learnt by doing, typing the example codes out rather than copying and pasting strengthens your coding muscle and significantly enhances your learning speed.
Multiplication table generator
This is a simple app for generating multiplication table for a given number and for a specified cycle. We used a modified version of this code in the third project to incorporate this app into another app. Study and practice with the sample solution below in your IDE:
def multiplication():
print("PLEASE READ THE GUIDELINES BELOW FIRST!!! \n\n1. This is a multiplication table generator. \n2. The first number you enter will be multiplied by a range of numbers in the cycle number. \n3. The cycle will start from 0 and stop at a cycle number you enter. \n")
#\n is used to create a new line. if you use \n\n, it will create double new lines, hence, there will be an empty line between the two lines.
num1 = int(input("Enter a number: ")) #To collect user input
num2 = int(input("Enter the cycle number: ")) #To collect user input
print() # To create a blanc space
print(f"{num1} Multiplication Table \n\n")
# Declare a "child" function that handles processing of data collected in the "parent" function
def my_multiple(num1, num2):
for item in range(num2+1):
print(f" {num1} x {item} = {item * num1}")
my_multiple(num1, num2)
multiplication() # To call the function
Voting Application
The application is an a digital polling booth, it can be used to conduct election for any two candidates. It provides the opportunity for you to apply a lot of concepts we have discussed in this tutorial and in part one of this tutorial:
from getpass import getpass
# You will understand the concept of importing functions when we discuss module in subsequent tutorials. For now, just know that we need to type "from getpass import getpass" for getpass() to work in our code. getpass() function is used to get user input instead of input() function when you want user input to be hidden when it is being typed on the screen.
# declare a function with two parameters for the candidates and one for the voters id_range.
def voting_app(candidate1, candidate2, id_range):
# declare variables to store the votes for each candidate
candidate1_votes = 0
candidate2_votes = 0
print(f"Welcome to Digital Polling Booth! \n\nThe Presidential Candidates are: \n\n1. {candidate1} \n2. {candidate2}\n")
# create an empty list to store voters' ids
voters_id = []
# create a for loop to iterate through the range of voters and append their ids to the list
id_range = range(1001, id_range) # the voters' id will start from 1001 and end at the id_range
for nums in id_range:
voters_id.append(nums)
#create a variable to store the number of voters
num_of_voter = len(voters_id)
# Declare a while loop that will manage the voting process
while True:
# create voter variable to collect the voter's id inside the while loop
voter = int(input("Enter your voter ID No to start: "))
print() # just to create space
# create a conditional statement to check if the voter is a valid registered voter inside the while loop
if voter in voters_id:
print("You are a valid voter")
else:
voter not in voters_id
print("You are either not a valid voter or you entered a wrong voter ID or you have already voted\n")
continue
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(f"To vote for {candidate1}, Press 1")
print(f"To vote for {candidate2}, Press 2")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
# create a variable to store the voter's choice
vote = int(input("Enter your choice: "))
# create a variable to store thank you message
thank_you = "Thank you for casting your vote!"
# create a conditional statement to check and assign vote to the appropriate candidate
if vote == 1 or vote == 2:
voters_id.remove(voter) # to remove the voter's id from the voters_id list to prevent multiple voting by a voter. Note that this has to be in a place within the code that will ensure that the voter has successfully cast his vote before his ID is removed from the list
if vote == 1:
candidate1_votes += 1 # to increment the candidate1_votes variable by each vote he receives
print(f"\nYou voted for {candidate1}. {thank_you}\n")
elif vote == 2:
candidate2_votes += 1
print(f"\nYou voted for {candidate2}. {thank_you}\n")
else:
vote != 1 or vote != 2
print(f"\nInvalid Option! Enter a valid option to vote. \nEnter 1 to vote {candidate1}, and 2 to vote {candidate2}\n")
# create a conditional statement to check if all the voters have voted
if len(voters_id) == 0: # You can replace this line with: if voters_id == []:
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
print("All voters have voted.\n")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
# create a while loop to manage the release of election result
while True:
result_key = 777
show_result = int(getpass("Enter the result key to display result: "))
# getpass() function is used to get the result key so that it will not show on the screen when it is being typed on the screen. That way, only the authorized person will know the result key to declare the election result
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
if show_result == result_key:
print(f"Here is the Election Result: \n\n1. {candidate1} has {candidate1_votes} votes \n2. {candidate2} has {candidate2_votes} votes")
else:
show_result != result_key
print("You entered the wrong key. Please try again\n.")
continue
print() # Just to create space
# create another conditional statements to check which candidate has the highest votes
if candidate1_votes > candidate2_votes:
percentage_vote = (candidate1_votes / num_of_voter) * 100
print(f"The winner is {candidate1} with {percentage_vote}% of the votes. \nThank You!")
# The break statements were used to stop the infinite loop
break
elif candidate2_votes > candidate1_votes:
percentage_vote = (candidate2_votes / num_of_voter) * 100
print(f"The winner is {candidate2} with {percentage_vote}% of the votes. \nThank You!")
break
else:
print(f"There is a tie between {candidate1} and {candidate2}. There will be a runoff between the two candidates on a date to be announced. \nThank You!")
break
break
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
#call the function passing in the necessary arguments, the two candidates names and the upper limit of voters_id range
voting_app("James Baker", "Amy Smith", 1005)
Personal Assistant App
The objective of this project is to demonstrate and teach how to use functions to reuse code in creating apps. The idea behind the app is to create a solution that can help user perform some common regular routine tasks. The example solution below has only two functional mini apps; one of them is the Shopping List App which is new. The second mini app is the modified version of Multiplication Table App which we discussed in the first project, you will see the difference when you study and practice the code. The capacity of Personal Assistant App can be easily expanded by adding more mini apps.
# Define a function to handle shopping lis
def create_shopping_list():
# Create an empty list to store shopping list items
shopping_list = []
# create a while loop to manage user interaction with the shopping list app
while True:
print("Would you like to create a shopping list? \n")
decision = input("Enter 1 to continue or 0 to go to the main menu: ")
# Create a conditional statement to check user's decision
if decision == "1":
print("\nAdd your shopping list below, then: \n\nEnter 1 to display your list when you are done \nEnter 0 to go to main menu \n")
if decision == "0":
print("\nYou have exited Shopping List. Bye! \n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n")
break # This break statement terminates the loop, that is, exit the create_shopping_list function
# Create a "child" while loop inside the "parent" while loop to manage creation and storing of shopping list items
while True:
# Create a variable to enable user to input shopping list items
my_shopping_list = input("Add item to your shopping list: ")
shopping_list.append(my_shopping_list) # To add the shopping list items entered by the user to the shopping list
# Create a conditional that enables user to exit the "child" while loop and display the shopping list they have created
if my_shopping_list == "1":
break
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
# Create a for loop to display the shopping list items entered by the user
for item in shopping_list:
if item == "1": #This condition is to skip the item "1" added to the list to exit the "child" while loop
break
print(item)
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n")
# Define a function to handle generation of multiplication tables
def multiplication():
print("PLEASE READ THE GUIDELINES BELOW FIRST!!! \n\n1. This is a multiplication table generator. \n2. The first number you enter will be multiplied by a range of numbers in the cycle. \n3. The cycle will start from 1 and stop at a cycle number you enter. \n")
#\n is used to create a new line. \n\n will create a blank line between the lines
#Create a while loop to collect user input and manage user interaction
while True:
print("\nEnter 0 to go to the main menu \nEnter your first number to continue \n")
num1 = int(input("Enter a number: "))
if num1 == 0:
print("\nYou have exited Multiplication Table Generator. Bye! \n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n")
break
num2 = int(input("Enter the cycle number: "))
print()
print(f"{num1} Multiplication Table \n\n")
# Declare a "child" function that handles processing of data collected in the "parent" function
def my_multiple(num1, num2):
for item in range(1, num2+1):
print(f" {num1} x {item} = {item * num1}")
my_multiple(num1, num2)
# Create a while loop to manage user interaction with the entire Personal Assistant App
while True:
print("Welcome to Personal Assistant App \n")
decision = input("Enter 1 for the Menu List or 0 to exit the app: ")
if decision == "0":
break
if decision == "1":
print("\nHere is the Menu List: \n")
# Create a "child" while loop to manage display of menu list and selection of user's choice on the menu list
while True:
print("1. Enter 1 to create Shopping List \n2. Enter 2 for Multiplication Table")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
option = input("Enter your menu option: ")
print()
if option == "1":
create_shopping_list()
break
elif option == "2":
multiplication()
break
else:
print("You have entered an invalid option! \n")
continue
Conclusion
Thank you for staying till the end of this tutorial, we hope you enjoyed and found its content useful and helpful. We shall continue and go deeper into Python Programming in Part Three of this tutorial. Watch out for it.