Advanced Python Concepts
Introduction
"Banana Tales" is a dynamic Python coding course in CodeMonkey Platform designed for students in classes 7 and 8. The course employs storytelling and gamification to make learning Python both fun and interactive.
Banana Tales - Part I (Class 7): Students begin their journey with 87 challenges covering foundational Python concepts such as Objects, Sequencing, Lists, For Loops, Range, Variables, If-Else Statements, While Loops, Boolean Operators, and Functions.
Banana Tales - Part II (Class 8): Building on their knowledge, students tackle 63 additional challenges (88-150) exploring advanced topics like Classes, Input Handling, Integers, Strings, Dictionaries, Sets, Tuples, 2D Lists, and Bubble Sort.
This course not only fosters coding skills but also ignites a passion for programming through its engaging and progressive structure.
What is a class?
Python is an object-oriented language, meaning everything is an object with its own properties and methods.
A class is like a blueprint for creating objects. It defines what an object looks like (its properties) and how it behaves (its methods).
For example, a class called Student might have properties like:
name (e.g., 'Dorji')
class level (e.g., 8)
grades (e.g., ‘Science’: ‘75’, ‘Math’: ‘66’)
Methods could include updating grades, calculating the average grade, or changing the class level.
Creating a Class
A class is defined using the reserved word class. By convention, the class name is capitalized.
The syntax of class defination:
class ClassName:
Once a class is defined, you can create objects of the class. This is called initializing objects.
The syntax of object creation:
object_name = ClassName()
The __init__() function
In Python, the __init__() method is special because it gets called every time an object is created from a class. It is used to initialize the object's properties. The first parameter of every method in a class is typically self, which refers to the instance of the object itself.
For example, consider a class called Student. You can create two objects, student1 and student2, with names “Dawa” and “Dema” like this:
class Student: #creating a class Student
def __init__(self, name): #initiating __init__() function
self.name = name
student1 = Student("Dawa") #creating object student1
student2 = Student("Dema") #creating object student2
You can also define other methods within the class to perform various actions. Each method starts with the keyword def and takes self as the first parameter. For instance, here’s how you can add methods to update a student's grade and print their information:
class Student:
def __init__(self, name):
self.name = name
self.grade_level = 1
def update_grade(self, level):
self.grade_level = level
def print_info(self):
print("Student name: " + self.name)
print("Grade level: " + str(self.grade_level))
student1 = Student("Sara")
student1.print_info()
In this example:
The __init__() method initializes the student’s name and sets the default grade level to 1.
update_grade() changes the student's grade level.
print_info() prints the student's name and grade level.
The input() function in Python lets the user enter text. When the program reaches input(), it pauses and waits for the user to type something and press Enter. Whatever the user types is returned as a string.
This function helps the program interact with the user. Here’s how to use it:
name = input()
You can also add a message so the user knows what to do, like this:
name = input("Enter your name: ")
The user's response is saved in a variable (like name), which you can use later in your program. For example:
answer = input("What is your name?")
print("Hello, " + answer + "!")
In the Banana Tales challenges, the input() function is used in a fun way. The challenge starts with a banana locked up by a snake. Once the banana is freed, a pigeon grabs it and drops it somewhere random. The user then types 'up' or 'down' to decide the height of the giraffes based on where the banana landed.
A data type tells us what kind of data a variable can hold, like numbers, text, or true/false values. It also tells us what we can do with that data. In Python, you don't have to say what type a variable is when you create it. Python figures it out when you assign a value.
We'll talk about two types of data: Integers and Strings.
Integers
Integers are numbers without decimal points. They can be zero, positive, or negative.
For example, in Banana Tales, the giraffe’s height or the snake’s length are integers.
If a user enters a number through the input() function, it’s stored as a string (text). Trying to do math with it will cause an error.
Example of an error:
a = input("Enter a number ")
b = input("Enter another number ")
product = a * b # This will raise an error because 'a' and 'b' are strings
To fix this, we can use the int() function to turn the string into an integer:
a = input("Enter a number ")
num1 = int(a)
b = input("Enter another number ")
num2 = int(b)
product = num1 * num2
print(product)
In Banana Tales, you often need to enter numbers as input. Since input() gives strings, we use the int() function to convert them into integers.
Strings
A string is a collection of characters (letters, numbers, and symbols). We use strings for things like messages or user inputs.
To assign a string to a variable, we use quotation marks:
my_var = "Coding is fun!"
Accessing Strings
Strings are like lists of characters, and we can access individual characters using their position (index):
my_var = "Coding is fun!"
print(my_var[0]) # prints 'C'
print(my_var[13]) # prints '!'
We can also get a range of characters using a slice:
second_word = my_var[7:9] # prints 'is'
In Python, you can also use negative indexing. For example, -1 gives the last character:
print(my_var[-1]) # prints '!'
Reversing Strings
To reverse a string, you can use [::-1]:
reverse_var = my_var[::-1]
print(reverse_var) # prints '!nuf si gnidoC'
Looping Over Strings
You can loop through each character in a string with a for-loop.
Concatenating Strings
You can combine two strings using the + operator:
str1 = "abc"
str2 = "def"
new_str = str1 + str2 # prints 'abcdef'
str() Function
The str() function turns numbers into strings. This is useful when combining numbers and text:
count = 0
print("The letter 'o' appears " + str(count) + " times")
in and not in Operators
The in operator checks if a string contains a certain character or word:
print("on" in "Python") # prints True
print("by" not in "Python") # prints True
Strings in Banana Tales
In Banana Tales, you will work with strings to open gates with codes. Each gate has a password based on a pattern. You’ll need to figure out the pattern to unlock closed gates by building passwords from the code.
For example, if the password is the same as the gate’s code:
password = gate.code
gate.open(password)
Each time you run the game, the open gate’s code is different, so you'll have to rebuild the password each time.
A dictionary is a collection of key-value pairs. Each key in a dictionary is unique, and it is linked to a specific value.
Syntax:
To define a dictionary, use curly brackets {} and separate the key and value with a colon :.
dictionary_name = {key1:value1, key2:value2, ...}
Example:
shopping_list = {"eggs": 12, "milk": 2, "apples": 5, "tomatoes": 6}
Accessing Values:
To access a value in a dictionary, use the key in square brackets [].
Example:
print(shopping_list["apples"]) # prints 5
If you try to access a key that doesn't exist in the dictionary, you’ll get an error.
Updating a Dictionary:
You can add new key-value pairs or update existing ones using this syntax:
dictionary_name[key] = value
If the key exists, its value will be updated.
If the key doesn’t exist, it will add a new key-value pair.
Example:
shopping_list["eggs"] = 18 # Updates the value of 'eggs'
shopping_list["banana"] = 2 # Adds a new key 'banana'
Checking for Keys:
You can use in and not in operators to check if a key exists in a dictionary. These operators only check the key, not the value.
Example:
if "eggs" in shopping_list:
print("Eggs are on the list!")
if "chilli" not in shopping_list:
print("No chilli on this list!")
Dictionaries in Banana Tales:
In Banana Tales, dictionaries are used to store gate codes and their corresponding passwords. For example, the rat holds a dictionary of gate codes and passwords.
To find the password for a gate, you use the gate's code:
Get the dictionary from the rat:
codes_and_passwords = rat.get_passwords()
Find the password using the gate's code:
password = codes_and_passwords[gate.code]
Open the gate:
gate.open(password)
You will also need to check if a gate's code exists in the dictionary using the in operator, especially as the game progresses and some gates are missing from the dictionary.
Key Points:
Dictionaries store unique keys and values.
You can access, add, and update values using keys.
Use in and not in to check if a key exists in the dictionary.
A set is an unordered collection of unique items. This means that a set cannot contain duplicate values. You can add or remove items from a set, but you won’t know the order of the items.
Syntax:
To define a set, use curly brackets {} with the items separated by commas.
set_name = {item1, item2, ...}
Example:
birds = {"eagle", "owl", "vulture", "falcon"}
Adding Items:
To add an item to a set, use the add() function.
Syntax:
set_name.add(new_item)
Example:
birds = {"eagle", "owl", "vulture", "falcon"}
birds.add("hawk") # Adds "hawk" to the set
If the item is already in the set, nothing will happen since sets only allow unique items.
Removing Items:
Remove any item: The pop() function removes and returns a random item from the set. You don’t know in advance which item will be removed.
Syntax:
set_name.pop()
Example:
birds = {"eagle", "owl", "vulture", "falcon", "hawk"}
removed_item = birds.pop() # Removes a random item
print(removed_item) # Prints the removed item
print(birds) # Prints the remaining items
Remove a specific item: The remove() function removes a specific item from the set.
Syntax:
set_name.remove(item)
Example:
birds = {"eagle", "owl", "vulture", "falcon", "hawk"}
birds.remove("vulture") # Removes "vulture"
If you try to remove an item that isn’t in the set, an error will occur.
Looping Over Sets:
You can loop through the items in a set using a for-loop.
Syntax:
for loop_variable in set_name:
Sets in Banana Tales:
In Banana Tales, the challenges involving sets introduce baskets with balloons. Adding a balloon makes the basket go up, and removing a balloon makes the basket go down. The property balloon_colors stores the colors of the balloons in the basket as a set, meaning there can only be one balloon of each color.
Key Points:
Adding a duplicate color (like "red" again) won’t add another balloon because sets are unique.
You can use add() to add balloons and remove() or pop() to remove them.
A tuple is an immutable (unchangeable) ordered collection of items. Once a tuple is defined, you cannot add, remove, or change its elements. However, unlike sets, tuples can contain duplicate values. The elements in a tuple are indexed, starting from 0.
Syntax:
To define a tuple, use round brackets () with the items separated by commas.
tuple_name = (item1, item2, ...)
Example:
cars = ("alto", "celero", "i20", "creta", "prado")
Accessing Items:
You can access elements in a tuple using square brackets [] and the index number.
Example:
cars = ("alto", "celero", "i20", "creta", "prado")
print(names[0]) # Prints 'alto'
print(names[2]) # Prints 'i20'
print(names[4]) # Prints 'prado'
Looping Over Tuples:
You can loop through the items in a tuple using a for-loop.
Syntax:
for loop_variable in tuple_name:
Example:
for car in cars:
print(car) # Prints each name in the tuple
Tuples in Banana Tales:
In Banana Tales, tuples are used to manage baskets with balloons. A tuple named new_colors holds predefined colors. You can use this tuple to add balloons of specific colors or to ensure that only balloons of the defined colors remain in the basket.
Key Points:
Tuples are fixed in size and cannot be changed after creation.
They are useful when you want to ensure that a collection of items remains constant throughout your program.
A 2D list (or two-dimensional list) is a list of lists, like a table with rows and columns. Each element in the 2D list is a list itself.
Syntax:
To define a 2D list, use square brackets [] and separate the inner lists with commas.
list_name = [[item1, item2, ...], [item11, item12, ...], ...]
Example:
numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Accessing Items:
To access an item in a 2D list, you need two indexes: one for the row and one for the column. Both row and column numbers start from 0.
Syntax:
list_name[row][column]
Example:
numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(numbers[0][1]) # prints 2
print(numbers[2][0]) # prints 7
print(numbers[1][2]) # prints 6
Accessing a Full Row:
To access a whole row, use just one set of square brackets with the row index.
Example:
print(numbers[1]) # prints [4, 5, 6]
Number of Rows and Columns:
You can use the len() function to get the number of rows and columns in a 2D list.
To get the number of rows: len(list_name)
To get the number of columns in a specific row: len(list_name[row_index])
Example:
numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(len(numbers)) # prints 3 (number of rows)
print(len(numbers[0])) # prints 3 (number of columns in row 0)
Looping Over 2D Lists:
To loop over a 2D list, use two nested for-loops. The outer loop goes over the rows, and the inner loop goes over the columns in each row.
Syntax:
for i in range(len(list_name)):
for j in range(len(list_name[i])):
# Do something with list_name[i][j]
Example:
numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in range(len(numbers)):
for j in range(len(numbers[i])):
print(numbers[i][j])
2D Lists in Banana Tales:
In Banana Tales, 2D lists are used to represent clouds. Each cloud is located in the list by its row and column, similar to how a table works.
To create a cloud at a specific position:
clouds[0][0] = Cloud() # Creates a cloud at row 0, column 0
To remove a cloud:
clouds[1][0] = None # Removes a cloud from row 1, column 0
Sometimes, you will need to create or remove clouds to allow the banana to pass, either by working with individual clouds or entire rows/columns using loops.
In computer science, sorting means arranging items in a specific order. For example, you can sort numbers from smallest to largest or vice versa.
Bubble Sort is a simple algorithm that sorts a list by comparing two adjacent items and swapping them if they are in the wrong order. This process repeats until the list is sorted.
Swap
Before understanding Bubble Sort, let’s learn about swapping. Swapping is when you exchange the values of two variables.
For example:
var1 = 4
var2 = 7
To swap their values, you can use a temporary variable:
temp = var1 # Save the value of var1
var1 = var2 # Assign var2’s value to var1
var2 = temp # Assign the saved value (temp) to var2
How Bubble Sort Works
Let’s say you want to sort a list from smallest to largest. The Bubble Sort algorithm works by repeatedly comparing and swapping adjacent items if they are out of order.
The algorithm starts by comparing the first two items in the list. If the first item is bigger than the second, they swap places.
This process continues, and the largest item "bubbles" to the end of the list after the first pass.
The next pass through the list doesn't include the last item, as it's already in its correct place. The second-largest item will now move to its correct position.
The algorithm keeps going until all the items are in order.
Bubble Sort Code Example
Here’s a basic implementation of Bubble Sort in Python:
numbers = [5, 6, 9, 7, 3, 4, 8, 2]
length = len(numbers) - 1
for i in range(length):
for j in range(length - i):
if numbers[j] > numbers[j + 1]:
# Swap the numbers
temp = numbers[j + 1]
numbers[j + 1] = numbers[j]
numbers[j] = temp
print(numbers) # Print the list after each pass
This code sorts the list and prints the result after each pass, so you can see how the numbers bubble to their correct places.
Bubble Sort in Banana Tales
In Banana Tales, Bubble Sort is used to arrange flamingos by height. You can't change the flamingos' heights, but you can change their positions to create steps for the banana.
Swapping Flamingos
In the first challenges, you practice swapping the flamingos' positions using a temporary variable:
temp = flamingos[0]
flamingos[0] = flamingos[1]
flamingos[1] = temp
Later, you use the full Bubble Sort algorithm to reorder the flamingos based on their heights, allowing the banana to pass.
Key Points:
Bubble Sort repeatedly compares and swaps adjacent items until the list is sorted.
In Banana Tales, you use Bubble Sort to position flamingos in height order, creating stairs for the banana to climb.