Python Fundamentals
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 Python?
Python is a computer programming language.
It is easy to learn and helps us write instructions for the computer.
In Banana Tales, Python Coding is used to clear the way to reach the banana to baby monkey.
Objects in Python
In Python, everything is an object.
👉 An object is something that has properties (details) and methods (things it can do).
🔹 Object and its property
A snake is an object and length is the property.
Example: snake.length = 5
Properties: color = yellow, size = small
Actions: can be eaten, can be collected
🔹 Object and its method
A whale is an object and blow is the property.
Example: whale.blow(6)
The print() Function
The print() function in Python is a built-in function used to output data to the console.
To use the print() function, place the message inside parentheses.
Example:
print("Hello")
>>> This will print the message: Hello
Try it >>>
1. Sequencing in Python
Sequencing means the order in which instructions are written and followed in a program.
In Python, the computer reads the code line by line, from top to bottom.
The order matters because the computer will not “guess” what we want – it just follows the sequence we give.
2. Why is Sequencing Important?
If the order of instructions is correct → the program works properly.
If the order is wrong → the program may give the wrong answer or an error.
3. ExampleA
Imagine the sequence to eat the banana:
Walk to the banana tree
Pick the banana
Eat the banana
👉 If we change the order (e.g., Eat the banana before picking), it doesn’t make sense!
A list is a collection of items arranged in a specific order. Each item has a position, called an index, which starts at 0.
You can access an item in a list using square brackets [] and the index of the item.
Example:
num = [10, 20, 30, 40] # num is the name of the list
# Access the first item (index 0)
print(num[0]) # prints 10
# Access the last item (index 3)
print(num[3]) # prints 40
List Characteristics:
The items in a list can be changed (mutable).
Items in a list don’t have to be unique(duplicate values are accepted).
A list can hold items of any data type, and it can contain mixed types.
Example:
mixed_list = [2, "hello", True, 4.5]
Lists in Banana Tales
In Banana Tales, lists are used for challenges involving animals like whales, giraffes, and snakes.
The whales list controls how high the whales blow water to lift the car and banana. You can use the blow() function to control the height.
Example:
whales[4].blow(3) # Whale at index 4 blows water 3 units high
In other challenges, the lists giraffes and snakes are used to adjust their heights and lengths.
Example:
giraffes[3].height = 10 # Set giraffe at index 3 to a height of 10
snakes[5].length = 2 # Set snake at index 5 to a length of 2
Key Points:
Lists are ordered collections of items that you can access using their index.
The len() function gives you the number of items in a list.
In Banana Tales, lists are used to control animal behaviors, like how high whales blow water or how tall giraffes stand.
A for loop is used to repeat a set of actions for every item in a sequence (like a list, tuple, dictionary, set, or string). It’s useful when you want to perform the same task on each item.
In Banana Tales, for loops are used to work with sequences, usually starting with lists.
Syntax:
The basic syntax of a for loop is:
for loop_variable in list_name:
# Your code here
The loop_variable is a name you choose for the current item the loop is working on.
The loop goes through each item in the list, one by one, and runs the code inside the loop for that item.
Example:
Let’s say we have a list of numbers:
names = ["Dawa", "Dorji", "Eden", "Maya"]
Here’s how to print each number using a for loop:
for name in names:
print(name)
What happens step by step:
First iteration: name becomes "Dawa", and print("Dawa") runs.
Second iteration: name becomes "Dorji", and print("Dorji") runs.
Third iteration: name becomes "Eden", and print("Eden") runs.
Fourth iteration: name becomes "Maya", and print("Maya") runs.
This will print:
>>> Dawa
>>> Dorji
>>> Eden
>>> Maya
Indentation
Indentation means leaving spaces at the beginning of a line in Python.
In Python, indentation is not just for neatness — it tells the computer which lines of code belong inside the loop, function, or condition.
for snake in snakes:
....... snake.length = 3 # ....... before snake.length is the indentation
For Loops in Banana Tales
In Banana Tales, you often use for loops to control animals like snakes, giraffes and whales. The loop goes through each item in a list and performs an action on it.
For example, if you have a list of whales and want each whale to blow water:
for snake in snakes:
snake.length = 4 # the length of each snake will be 4
Key Points:
For loops are used to repeat actions for every item in a sequence.
The loop goes through each item in the list and performs the specified action.
In Banana Tales, for loops are commonly used to control the behavior of animals.
This makes it easy to handle sequences of items efficiently!
The range() function generates a sequence of numbers, starting from 0 by default, increasing by 1 by default, and stopping at a specified number (but not including that number).
Syntax:
range([start], [stop], [step])
Arguments:
start (optional): The number to start from. If not given, it starts from 0.
stop (required): The number to stop at. The sequence will go up to stop - 1.
step (optional): The amount to increase between numbers. The default is 1.
The start and step are optional. If not provided, Python uses the defaults (0 for start and 1 for step).
Examples:
range(5): Creates: [0, 1, 2, 3, 4] (Starts at 0, ends at 4)
range(2, 10): Creates: [2, 3, 4, 5, 6, 7, 8, 9] (Starts at 2, ends at 9)
range(3, 15, 2): Creates: [3, 5, 7, 9, 11, 13] (Starts at 3, ends at 13)
Using range( ) in For Loops
When combined with a for loop, range() allows you to repeat actions for every number in the sequence.
Example:
for x in range(4):
print(x)
This loop will print the numbers from 0 to 3 (since range(4) generates [0, 1, 2, 3]).
For Loops with range( ) in Banana Tales
In Banana Tales, range() is used in for loops to control animals like giraffes and snakes. You can use range() to adjust a specific set of giraffes or snakes by their index in a list.
Example:
for index in range(3):
giraffes[index].height = 4
snakes[index].length = 3
This loop runs 4 times (since range(4) creates [0, 1, 2, 3]). In each iteration, it updates the height of a giraffe and the length of a snake at the corresponding index.
First iteration: giraffes[0].height = 4, snakes[0].length = 3
Second iteration: giraffes[1].height = 4, snakes[1].length = 3
Last iteration: giraffes[2].height = 4, snakes[2].length = 3
Key Points:
The range() function generates a sequence of numbers.
You can use range() with for loops to repeat actions for each number in the sequence.
In Banana Tales, range() helps adjust animal properties like heights and lengths by looping through specific sets of giraffes or snakes.
This makes it easier to control a group of animals at once!
A variable is like a container that holds a value. It can store different types of data, such as numbers, strings, or lists. A variable is given a name so you can refer to it later, and its value can change during the program.
Assigning a Value:
To assign a value to a variable, use the = symbol.
Example:
age = 15 # age is the variable, 15 is the value
Variables in Banana Tales
In Banana Tales, variables are used in many ways:
Pre-made variables: In some challenges, variables like giraffe are automatically created to refer to specific animals.
For loops: A variable is created in for loops to represent each item in a list. For example:
for snake in snakes:
snake.length = 2
Here, the variable snake refers to each item in the snakes list during the loop.
Custom variables: You can create your own variables. For example:
goal_height = 6
This creates a variable called goal_height that stores the value 6. Later, you can use goal_height in your code instead of writing the number 6.
Variables in Challenges
In some challenges, you use variables to change the heights or lengths of animals like giraffes or snakes. Variables allow you to easily adjust these values throughout the code.
In more complex challenges, the game might have two areas, each with its own monkey. To solve both areas with the same code, you need to use variables to set values like the giraffes' heights. Hard-coding specific numbers won’t work in both areas.
Key Points:
Variables are containers for data that can change.
You can use variables in loops, create your own, and refer to them throughout your code.
In Banana Tales, variables are used to control the heights/lengths of animals, among other things.
Printing variable values can help debug your code.
Conditional statements allow you to make decisions in your code. You can use an if statement to do something only if a certain condition is True. If the condition is False, you can use an else statement to do something else.
Example:
"If I am sick, I will stay in bed, otherwise, I will go to school."
Syntax:
The basic syntax of an if-else statement is:
if condition:
# Do something
else:
# Do something else
The if block runs if the condition is True.
The else block runs if the condition is False.
The else statement is optional and is only used when you want to do something if the condition is not met.
If-Else in Banana Tales
In Banana Tales, if-else statements are used to handle different types of obstacles, like ice cubes, boxes, and fences. The dragon can melt ice cubes and smash boxes and fences.
You use if-else statements to decide what the dragon should do with each obstacle. The game provides functions to check the type of obstacle:
is_ice(): Returns True if it’s an ice cube.
is_box(): Returns True if it’s a box.
is_fence(): Returns True if it’s a fence.
Example:
if obstacle.is_ice():
dragon.melt_ice()
else:
dragon.smash()
In this code:
If the obstacle is ice, the dragon melts it.
Otherwise, the dragon smashes the obstacle (which works for both boxes and fences).
Summary of Return Values:
Obstacle is_ice() is_box() is_fence()
Ice Cube True False False
Box False True False
Fence False False True
The else statement handles both boxes and fences because they require the same action: smashing.
Key Points:
if-else statements are used to make decisions in your code based on conditions.
The if block runs if the condition is True.
The else block runs if the condition is False.
In Banana Tales, you use if-else to decide how to handle different obstacles.
A while loop runs a block of code as long as a specific condition is met. Before each repetition, the computer checks the condition. If it’s True, the loop continues. If it’s False, the loop stops.
Syntax:
while condition:
# Your code here
Example:
Here’s an example of a while loop:
while dog.hungry():
dog.eat()
This loop runs while the dog is still hungry. Each time the loop runs, the dog eats. When the dog is no longer hungry (hungry() returns False), the loop stops.
Important:
When writing a while loop, make sure the condition will eventually become False. If not, the loop will run forever and may cause the program to crash.
While Loops in Banana Tales
In Banana Tales, while loops are used to solve challenges involving elephants and wells. The elephant fills the well with water using a while loop.
The well has two properties:
water_level: The current water level.
max_water_level: The maximum allowed water level.
The elephant sprays water into the well until the water level reaches the maximum. If the well is overfilled, a crocodile appears, and the banana cannot pass.
Example:
while well.water_level < well.max_water_level:
elephant.spray_at(well)
In this code:
The elephant keeps spraying water into the well while the water level is less than the maximum.
Once the water level reaches the maximum, the loop stops.
Key Points:
While loops repeat actions while a condition is True.
Be sure the condition will eventually be False to avoid infinite loops.
In Banana Tales, while loops help control the elephant as it fills the well without overfilling it.
Boolean operators are used to combine conditions. The three Boolean operators covered are:
and
or
not
and Operator
The and operator combines two conditions. It returns True only if both conditions are True. If either condition is False, the result will be False.
Syntax:
if condition1 and condition2:
# Your code here
Example:
a = 5
b = 3
if a > 0 and b > 0:
print("Both numbers are positive")
else:
print("At least one number is not positive")
In this example, the and condition will be True because both a and b are greater than 0.
Truth Table for and operator:
condition1 condition2 Output
True True True
True False False
False True False
False False False
In Banana Tales, the and operator is used with a dragon and obstacles, checking conditions like whether an obstacle is on the ground.
or Operator
The or operator also combines two conditions. It returns True if at least one condition is True. If both conditions are False, the result will be False.
Syntax:
if condition1 or condition2:
# Your code here
Example:
a = 5
b = -3
if a > 0 or b > 0:
print("At least one number is positive")
else:
print("Both numbers are not positive")
In this case, the or condition will be True because a is greater than 0.
Truth Table for or operator:
condition1 condition2 Output
True True True
True False True
False True True
False False False
In Banana Tales, the or operator is used to check if an obstacle is either a box or a fence.
not Operator
The not operator reverses the result of a condition. If a condition is True, not makes it False, and if it’s False, not makes it True.
Syntax:
if not condition:
# Your code here
Example:
if not baby.sleeping():
baby.play()
else:
parent.say("Shhh...!")
In this example, if the baby is not sleeping, the baby plays. Otherwise, the parent says "Shhh...!".
Truth Table for not operator:
condition not condition
True False
False True
In Banana Tales, the not operator is used with an elephant and crocodile. For example, you can check if the crocodile’s mouth is not closed to determine if the banana can pass.
Key Points:
and: True if both conditions are True.
or: True if at least one condition is True.
not: Reverses the condition (True becomes False, and False becomes True).
A function is a set of instructions that performs a specific task. The computer only runs the function when you call it in your code. Functions are helpful because they allow you to reuse code and keep it organized.
You should give functions meaningful names that describe what they do. For example, in Banana Tales, functions like spray_at(), fire_at(), and smash() have names that clearly indicate their purpose.
Defining a Function
To define a function in Python, use the def keyword followed by the function's name.
Syntax (without parameters):
def function_name():
# Your code here
Example:
def greet():
print("Hello!")
To call this function:
greet() # This will print "Hello!"
Functions with Parameters
A parameter is a value that you pass to the function, allowing you to use the same function with different inputs.
Syntax (with parameters):
def function_name(parameter):
# Your code here
Example:
def greet(name):
print("Hello, " + name + "!")
To call this function:
greet("Alice") # This will print "Hello, Alice!"
You can also define functions with multiple parameters:
def add(a, b):
return a + b
To call this function:
print(add(5, 3)) # This will print 8
Example of a Function:
Here’s a function that checks if a number is positive or negative:
def print_is_positive(n):
if n > 0:
print("positive")
else:
print("negative")
To call this function with different values:
print_is_positive(6) # prints "positive"
print_is_positive(-3) # prints "negative"
print_is_positive(0) # prints "negative"
Functions in Banana Tales
In Banana Tales, functions are used to avoid repeating code. For example, when filling wells with elephants, instead of repeating the same code for each pair of elephant and well, you can define a function to handle it:
def fill_well(elephant, well):
while well.water_level < well.max_water_level:
elephant.spray_at(well)
You can then call this function for different pairs of elephants and wells:
fill_well(elephant1, well1)
fill_well(elephant2, well2)
This makes the code cleaner and easier to manage!
Key Points:
Functions allow you to group code into reusable blocks.
Functions can take parameters to work with different values.
In Banana Tales, functions simplify tasks like filling wells with elephants.