All Collections
CodeMonkey Courses | Dive Deeper
Banana Tales course
Banana Tales Part 1 - Python - Coding Concepts
Banana Tales Part 1 - Python - Coding Concepts

This article will provide you with in-depth explanations of the coding concepts taught on Banana Tales Part 1, how and when to use them.

Livnat Hershkovitz avatar
Written by Livnat Hershkovitz
Updated over a week ago

These are the coding concepts that are taught on Banana Tales Part 1 and will be reviewed in this article:

  1. Lists and Indexes - challenges 19 - 25

  2. For Loops - challenges 26 - 30

  3. Range - challenges 31 - 40

  4. Variables - challenges 41 - 47

  5. Conditional Loops (while) - challenges 60 - 66

  6. Functions - challenges 79 - 87


The print() function

The print() function prints the specified message to the screen. The message can be a string (a text surrounded with quotation marks) or a variable.

Place the message inside the parenthesis.

For example:

print("I love Python")

In Banana Tales, the messages are printed in the console. When a challenge is opened, the console tab is closed. If the function print() is used, the console is opened and the messages are displayed.

In programming, it is very common to use prints as a way to debug your program. For example, if you want to know the value of a variable, or to make sure the program reached a certain line of code.


Lists and Indexes

A list is a named collection of items. The items have order in the list and are indexed. These items are accessed by using square brackets - []. To refer to an item in a list, use the list's name and square brackets; Inside the brackets write the index number of the item.

The first index is 0. The last index will be the number of items in the list minus 1 (since the first index is 0).

The items in a list can be changeable and their values are not unique.

The items in a list can be of any data types. Items can be of the same data type or mixed.

For example you can define a list:

my_list = [2, 4, 6, 8]

Refer to the first item in the list:

my_list[0] # it's value is 2

print(my_list[0]) # will print '2'

Refer to the last item in the list:

my_list[3] # it's value is 8

print(my_list[3]) # will print '8'

The len() function returns the number of items in the list.

The syntax is:

len(list_name)

For example:

my_list = [2, 4, 6, 8, 10, 12]

len(my_list) # will return 6

print(len(my_list)) # will print '6'

In Banana Tales, the challenges that practice lists use the list named "whales".

Each whale needs to blow water to a certain height. The water of the whale's blow will lift the banana up.

The whale blows water using the blow() function. The argument of the function will determine how high the water will blow.

The syntax is:

whales[1].blow(5)

whales[3].blow(7)

For example:

In the last two challenges, the lists are "giraffes" and "snakes". The syntax to change the height/length (respectively) is for example:

giraffes[1].height = 4

snakes[2].length = 6


For Loops

A for loop is used to repeat code for all items in a sequence. A sequence can be: list, tuple, dictionary, set or string. It is used when we want to perform the same action on each of the items. The for loop will keep going until all the actions were completed on all the items in the sequence.

In Banana Tales, the sequence used in the challenges that teach for-loops is a list. In later challenges other types of sequences are used. The following explanations and examples will refer to a for loop on a list.


The syntax to use a for loop is:

for loop_variable in list_name:

# Your code here

The loop_variable is a name we assign; it can be any name we want. It is common to name it as the singular form of the list's name (whale, giraffe, snake, etc).
When the computer executes a for-loop, it first replaces loop_variable with the first item in the list and runs the instructions inside the loop for that item. Then, it continues to the second item in the list, and so on. The loop will run as the number of items in the list.

For example, if we have a list with 4 items:

numbers = [7, 4, 1, 10]

The items of this lists are: numbers[0] (the number 7), numbers[1] (4), numbers[2] (1) and numbers[3] (10).

If we write the following code:

for number in numbers:

print(number)

The loop_variable in this example is number.

The first time this loop will run, the computer will replace number with numbers[0]. The actual code that will run is:
print(numbers[0]) # will print '7'
Then, number will be replaced with numbers[1]. The actual code that will run is:
print(numbers[1]) # will print '4'
Then, number will be replaced with numbers[2]. The actual code that will run is:
print(numbers[2]) # will print '1'
Finally, the last run will be:
print(numbers[3]) # will print '10'

You can see in the example below, that printing each item in the list vs. using a for loop, produces the same results!


Range

range()

The range() function returns a sequence of numbers. It starts from 0 (by default), increments by 1 (by default) and ends at a specified number.

The range can have one, two or three arguments.

  1. start (optional) - from which number to start the sequence; the default is 0

  2. stop (required) - at which number to stop the sequence; this number is not included in the sequence; the last number in the sequence will be stop minus one

  3. step (optional) - by how much to increment the numbers; the default is 1

The syntax to use the function range() is:

range([start], stop, [step])

In Banana Tales, we will use range with one (stop) or two (start, stop) arguments only.

Examples of the different uses of range():

Usage

Sequence created

Comments

range(7)

[0, 1, 2, 3, 4, 5, 6]

ends at stop-1 (7-1=6)

range(5)

[0, 1, 2, 3, 4]

ends at stop-1 (5-1=4)

range(3, 11)

[3, 4, 5, 6, 7, 8, 9, 10]

starts at 3; ends at 10

range(5, 9)

[5, 6, 7, 8]

starts at 5; ends at 8

For with range()

When a for loop is used with range(), the loop repeats for all items in the sequence created by range().

The syntax to use a for loop with range() is:

for loop_variable in range([start], stop, [step]):

# Your code here

For example:

for index in range(5):

print(index)

range(5) creates the sequence [0, 1, 2, 3, 4].

The following table summarizes the value of index, the code that is executed and the value displayed when the for loop runs:

Iteration

Value of index

Executed code

Value displayed

first

0

print(0)

0

second

1

print(1)

1

third

2

print(2)

2

forth

3

print(3)

3

fifth

4

print(4)

4

In Banana Tales, a for-loop with range() is used to change both giraffes and snakes in one for-loop. It is also used to change a set of giraffes or snakes (and not all objects in the list of giraffes/snakes). The loop variable is used as the index of the giraffes/snakes that need to be changed.

In the example below:

for index in range(4):

giraffes[index].height = 8

snakes[index].length = 5

The for loop iterates 4 times (range(4) creates the sequence [0, 1, 2, 3]). Executed code in each iteration:

First iteration (value of index is 0):

giraffes[0].height = 8

snakes[0].length = 5

Second iteration (value of index is 1):

giraffes[1].height = 8

snakes[1].length = 5

Third iteration (value of index is 2):

giraffes[2].height = 8

snakes[2].length = 5

Last iteration (value of index is 3):

giraffes[3].height = 8

snakes[3].length = 5


Variables

A variable can be thought of as a container that holds one value at a time. It is a place in the computer’s memory for storing some kind of data.

The value can be any kind of data. For example: number, string, or list. A variable is referred to by a name. A variable's value can be changed.

To assign a value to a variable, use the = symbol.

In the following code:
my_var = 10
my_var is the variable name and 10 is the value assigned to it.
If you want to change the value of the variable, you can assign a different number to it. For example:
my_var = 5
Now the value of my_var is 5.

In Banana Tales, variables are used in various ways.

There have been different kinds of animal objects that were automatically created and named by the CodeMonkey system. If a challenge had a single giraffe on the screen, the system gave us a pre-made variable called giraffe so we can refer to it.

We’ve also seen variables created when using for-loops. In code like:

for snake in snakes:

snake.length = 2

A new variable called snake is created and it contains the next item from the snakes list each time throughout the loop's execution.

We can also create our own variables. The code:

goal_height = 6

Creates a storage space, gives it the name goal_height, and stores the number 6 in that space. Then later in the code we can use goal_height instead of using the number 6.

In the variables challenges, the variables are used to change the heights/lengths of the giraffes/snakes. The variables are also used to set different heights/lengths. The value of the variables is changed throughout the code and each giraffe/snake is changed to a different height or length.

In Banana Tales, there are some challenges where the game is split into two play areas each with its own monkey. The goal is to write one code which solves both settings. The first such challenge is in the variable challenges (challenge 44). Setting the giraffes' heights to a specific number (and not using variables) will only solve one of the games.

Tip: when coding, printing the value of a variable can help you find a problem in your code. Use the print() function to see the value of a variable.

In the example below we sum the numbers from 1 to 5 and then print it. We also print the number we add each time.

sum = 0

for number in range(1, 6):

print(number) # will print '1', then '2', '3', '4' and lastly '5'

sum = sum + number

print("The sum is: " + str(sum)) # will print '15'


Conditional Statements (if-else)

Conditional statements are if and if-else statements. They are used for decision making.

Sometimes when writing code, we want something to happen only if a certain condition is met. For example: if I am sick, I will stay in bed, otherwise, I will go to school.

An if-else statement defines two code blocks: one for the if statement; one for the else statement. First, the computer checks the condition. If the condition is met (the answer is True), then the code block of the if statement is executed. Otherwise, the code block of the else statement is executed.

The syntax for an if-else statement is:

if condition:

# Do something

else:

# Do something else

The else statement is optional and will be used only when we want something to happen when the if condition is not met (when it is False).

When using an if-else statement, either the code block of the if statement is executed or the code block of the else statement is executed.

In Banana Tales, the if-else challenges include a dragon and obstacles. The obstacle types are: ice cube, box or fence. The dragon will help remove the obstacles by smashing the boxes and fences and melting the ice cubes.

In order to decide how to handle each different obstacle, if-else statements are used

The following table summarizes the return values of each of the functions for each of the obstacles.

Obstacle

is_ice()

is_box()

is_fence()

ice cube

True

False

False

box

False

True

False

fence

False

False

True

The else statement "catches" anything that is not an ice cube (a box and a fence). This works because the same action is required when the obstacle is a box or a fence.


Conditional Loops (while)

A while loop contains a block of code that will continue to run as long as a specific condition is met. This condition is called the loop condition. You can think of the condition as a question; every time before running the loop, the computer asks what is the answer to the question. If the answer is True (yes), the loop will keep going and the code inside the loop will be executed. The loop will stop once the answer is False (no).

The syntax to use a while loop:

while condition:

# Your code here

Example of a while loop:

while dog.hungry():

dog.eat()

The while loop will run as long as the function hungry() returns True (as long as the dog is hungry). Once hungry() returns False (the dog is not hungry), the loop will end and the dog will not eat anymore.

When writing a conditional loop, you need to make sure that the loop will end. Meaning that eventually, the condition will be False. Otherwise, the loop will continue "indefinitely" and may even cause the program to crash.

In Banana Tales, the while challenges include elephants and wells. The elephant needs to fill the well. The well has two properties:

  1. water_level - the current water level of the well; With each elephant.spray(), the water level increases.

  2. max_water_level - the maximum water level (the depth of the well). If the elephant fills more water than the maximum, then the crocodile steps out of the well and the banana can not drive over the well.

A while loop is used to fill the well. The elephant will spray water at the well while the water level is less than the maximum water level.

We use the operator < to check if a value is less than another value.

The code will be:

while well.water_level < well.max_water_level:

elephant.spray_at(well)


Boolean Operators (and, or, not)

The Boolean operators covered in Banana Tales are:

and operator

The and operator combines two conditions. It returns True when both conditions are True, otherwise it returns False.

The and operator can be used in a conditional loop (while loop) or in an if statement. The syntax to use the and operator in an if statement is:

if condition1 and condition2:

# Your code here

The condition of the if statement consists of two parts: condition1 and condition2. Only when both parts evaluate to True then the condition of the if statement will be True.

The following table shows when the and operator returns True:

condition1

condition2

condition1 and condition2

True

True

True

True

False

False

False

True

False

False

False

False

In the example below, we check if two numbers are positive.

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 Banana Tales, the and challenges include a dragon and obstacles, the same as in the if-else challenges. We are introduced to a new function is_on_ground(). This function returns True when the obstacle lays on the ground and False otherwise (if the obstacle is in the air, or on another obstacle).

There is also another obstacle - the boulder. The dragon can not remove it. If you melt ice cubes which are not on the ground, the boulder will fall and block the way for the banana.

or operator

The or operator combines two conditions. When at least one of the conditions is True - the or condition evaluates to True. Otherwise it is False.

The or operator can be used in a conditional loop (while loop) or in an if statement. The syntax to use the or operator in an if statement is:

if condition1 or condition2:

# Your code here

The condition of the if statement consists of two parts (condition1 and condition2).

When at least one of the conditions is True, the condition of the if statement will be True.

The following table shows when the or operator returns True:

condition1

condition2

condition1 or condition2

True

True

True

True

False

True

False

True

True

False

False

False

In the example below, we check if any number is positive.

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 Banana Tales, the or challenges include a dragon and obstacles, the same as in the if-else challenges. The same types of. obstacles are used. The or operator is used to check if the obstacle is a box or a fence.

not operator

The not operator reverses the result of the condition: True becomes False, and False becomes True.

The not operator can be used in a conditional loop (while loop) or in an if statement. The syntax to use the not operator with an if statement is:

if not condition1:

# Your code here

The following table shows the values of the not operator:

condition1

not condition1

True

False

False

True

Example using the not operator:

if not baby.sleeping():

baby.play()

else:

parent.say("Shhh...!")

In the example above, if the baby is not sleeping then the baby plays, otherwise, the parent says "Shhh...!".

In Banana Tales, the not challenges includes the elephants and wells. This time the crocodile's mouth can be open. If it is opened, the banana can not drive over the crocodile. We have access to the crocodile.mouth_closed property. So, we need to use the not operator to check if not crocodile.mouth_closed.

The function toggle() switches between the two states of the crocodile's mouth - open and closed.


Functions

A function is a set of instructions that performs a specific task. The computer will only execute the function when you use it in your code.

You should give a meaningful name to the function to describe what the function does. This will help others easily understand what the function does. We used many functions in previous challenges in Banana Tales, for example: spray_at(), fire_at(), smash(), is_ice(), is_on_ground(), etc. By reading the name of the function, we can guess what the function will do without seeing the function's code.

A function can use parameters, which enable you to use the same code with different values. These values are sent to the function by other code that calls the function.

In Python, when defining a function, we use the reserved word def before the function's name.

The syntax to define a function with no parameters is:

def function_name():

# Your code here

To use this function, write:

function_name()

The syntax to define a function with one parameter is:

def function_name(parameter):

# Your code here

To use this function, write:

function_name(argument)

When argument holds the value to be sent to the function.

If you want to define a function with more than one parameter, use a comma to separate between the parameters.

All the function's code is indented under the function's definition. The first line that is not indented is not part of the function.

Let's look at the code of the function print_is_positive as an example.

The function is defined as:

def print_is_positive(n):

if (n > 0):

print("positive")

else:

print("negative")

Let's see what happens when we use this function with three different arguments. When the computer executes the code it starts with the "main" code, which is the code outside function definitions. When it encounters a function, it moves to the function's code and replaces the function's parameter with the argument used.

The computer starts with line 7 - print_is_positive(6). It moves to line 1 to execute the print_is_positive function and replaces n with 6. So, the actual code that runs is:

if (6 > 0):

print("positive")

else:

print("negative")

Then it continues to line 8 - print_is_positive(-3). It moves again to line 1 to execute the print_is_positive function and replaces n with -3. So the actual code that runs is:

if (-3 > 0):

print("positive")

else:

print("negative")

Finally, it continues to line 9 - print_is_positive(-19). It moves again to line 1 to execute the print_is_positive function this time replacing n with -19. So the actual code that runs is:

if (-19 > 0):

print("positive")

else:

print("negative")

In Banana Tales, most of the function challenges include the elephants and wells. In these challenges, there are no lists of elephants and wells. The challenges can not be solved using a for loop. Instead of repeating the code of the while loop for each pair of elephant and well, we will use a function. The function will fill the well and we call it each time with a different pair of elephant and well.

In later challenges, we will also need to check if the crocodile's mouth is not closed. This check will be added only once in the function's code.


Relevant Articles:

Did this answer your question?