Learn How to Think with Karel the Robot. Chapter 7. Variables
In this chapter you will learn:
- What are variables and why they are useful.
- What types of variables are provided in the Karel language.
- What are admissible and inadmissible names of variables.
- How to create and initialize variables.
- How to change their values and display them.
- About the assignment operator =.
- About arithmetic operators +, -, *, / and +=, -=, *=, /=.
- About comparison operators ==, !=, <, <=, > and >=.
- How many objects he found.
- How many steps he took.
- Sizes of obstacles and distances between objects.
- GPS positions of objects or obstacles.
- How many objects are in his bag.
- Results of math calculations, etc.
- Names of objects that he found.
- Text that he obtained when translating Morse to English.
- Letters that he recognized when reading Braille alphabet, etc.
Karel can also use Boolean (logical) variables to store outcomes of conditions in the form True or False. These will be discussed in Chapter 11.
In summary, the Karel language provides the four standard types of variables which are used in most programming languages:
- Integer variables to store whole numbers.
- Floating-point variables to store real numbers.
- Text string variables to store text strings.
- Boolean variables to store Boolean (truth) values True and False.
In addition to that, other programming languages usually provide other types of variables aimed at specific applications. For example, C/C++ which is heavily computational provides six types of integer variables (char, int, short int, long int, unsigned short int, unsigned long int) and two types of floating-point variables for single and double precision numbers. Python provides the complex type to work with complex numbers. Python also provides aggregate types including lists, tuples, dictionaries and sets. Of those, Karel provides lists - these can be used to do amazing things, as you will see in Chapter 13.
The name of a variable can be almost any combination of letters of the alphabet, integer numbers, and the underscore character ’_’, such as N, m, c1, alpha, Beta, GAMMA, my_text, etc. Only remember the following important restriction:
So, names such as 1a or 8_bits cannot be used. This is the same in other programming languages too. Names starting with one or more underscores such as _x or __my_name__ are fine.
Also, importantly, recall from Section 2.14 (page 99) that the Karel language is case-sensitive. This means that, for example, the command left typed as Left or LEFT will not work. The same holds for the names of variables:
The case-sensitivity of Karel comes from Python.
2a = 0
3my_age = 12
4seconds_per_minute = 60
5hours_per_day = 24
6temperature = -15
8# Floating-point variables:
9half = 0.5
10pi = 3.14159265358979323846
The value of a variable can change during runtime. Therefore it is important to be able to display
its value at any time. This can be done using the print statement. The following sample code
illustrates various forms of its use:
The output of this program is:
You already know how to create variables and initialize them with values. These values may
come not only as raw numbers, but also from other variables and/or math expressions. Let’s
begin with addition (symbol ’+’) and subtraction (symbol ’-’):
2item_2 = 7.5
3amount_start = 30
4total_cost = item_1 + item_2
5amount_end = amount_start - total_cost
6print(~Initial amount:~, amount_start)
7print(~Total cost of both items:~, total_cost)
8print(~Remaining amount:~, amount_end)
2hrs = secs / 3600
3mins = hrs * 60
4print(secs, ~seconds =~, mins, ~minutes =~, hrs, ~hours~)
Karel can modify the values of numerical variables using the Python operators +=, -=, *= and
/=. Here a += 2 is exactly the same as a = a + 2, b -= 3 is the same as b = b - 2, c *=
4 means c = c * 4, and d /= 5 is d = d / 5.
2b = 15
3c = 5
4d = 25
5a += 2
6b -= 3
7c *= 4
8d /= 5
9print(~a =~, a)
10print(~b =~, b)
11print(~c =~, c)
12print(~d =~, d)
Sometimes one needs to decide whether the value of a variable (say X) is equal to the
value of another variable (say Y). As you already know, typing ifX=Y is wrong
because the assignment operator = will just assign the value of Y to the variable X. The
mathematical equality should be expressed using the symbol == which means "equal
2Y = X + 6
3if X < Y
4 print(~X is less than Y.~)
6 print(~X is greater than or equal to Y.~)
2Y = X
4if X > Y
5 print(~X is greater than Y.~)
7 print(~X is less than or equal to Y.~)
2Y = 2 * X - 2
3if X <= Y
4 print(~X is less than or equal to Y.~)
6 print(~X is greater than Y.~)
Hooray! Finally we know variables well enough to tackle first programming challenges with them. Today, Karel’s task is to count maps which lie randomly between him and his home square. He does not know how many there are. The resulting variable should be named nmaps. He should display the value of this variable at the end.
The easiest way to do this is to first solve a simpler task - just go and collect all the maps. This is something you can easily do by now:
In a second step, we will modify this program to create a new variable nmaps at the beginning
and initialize it with zero. Then, if Karel finds a map, instead of collecting it he will increase the
value of nmaps by one. And, at the end he will use the print statement to display the value of
Karel is carrying an unknown number of water bottles, and there is an unknown number of bags between him and his home square. He needs to put one water bottle in each one. Also, he should count how many water bottles he has at the beginning, subtract the number of water bottles which he places in the bags, and then store the number of remaining water bottles in a variable named wb.
The only way for the robot to count the water bottles he has is to place all of them on the ground, and then collect them again:
Then, he needs to walk to his home square, and put a water bottle in each bag. Since Karel might
have fewer water bottles than there are bags, the put command should only be executed if the
robot’s bag is not empty. Here is the complete code:
2wb = 0
3while not empty
8print(~I am starting with~, wb, ~water bottles.~)
9# Walk to home square and put one water bottle in each bag:
10while not home
11 if bag and (not empty)
14 print(~Found a bag - placing a water bottle.~)
16print(~Now I only have~, wb, ~water bottles left.~)
Below is the text output. It reveals that Karel had 23 water bottles at the beginning:
The Fibonacci sequence is one of the most famous sequences of mathematics. It begins with 1, 1
and each new number is the sum of the last two. So, the third number is 1 + 1 = 2. The fourth
number is 1 + 2 = 3. The fifth number is 2 + 3 = 5 and so on. The first ten numbers in the sequence
In order to obtain the third number, he will create a helper variable new_n and assign the sum
n1 + n2 to it. Then he will place new_n beepers on the ground. He will assign the value of n2
to n1 by executing n1 = n2, and then also the value of new_n to n2 by executing n2 = new_n.
Then he will move to the next grid square. Hence, after this he will have the last two numbers of
the sequence stored in n1 and n2 again. This process will be repeated eight times, because Karel
wants to calculate the first 10 numbers of the Fibonacci sequence. Here is the corresponding
And indeed, at the end he obtains the correct result:
Friendly reminder - for every question either none, one, or several answers may be correct.
- To store useful information for later use.
- To make the program run faster.
- To make the program use less memory.
- To make the program shorter.
- Numerical variables.
- Text string variables.
- Boolean (logical variables).
- Complex variables.
- A := 10
- A == 10
- A = 10
- An error will be thrown.
- An error will be thrown.
- An error will be thrown.
- An error will be thrown.
- x will be 2, y will be 4, z will be 6.
- x will be 3, y will be 6, z will be 2.
- x will be 2, y will be 4, z will be 3/4.
- x will be 3, y will be 2, z will be 6.
Table of Contents
- 1. Introduction
- 2. Basic Commands
- 3. Counting Loop
- 4. Conditions
- 5. Conditional Loop
- 6. Custom Commands
- 7. Variables
- 8. Functions
- 9. Text Strings
- 10. Testing Your Programs
- 11. Boolean Values, Variables, Expressions, and Functions
- 12. Randomness and Probability
- 13. Lists
- 14. Recursion
- 15. Advanced Applications
- Appendix A. Karel App in NCLab
- Appendix B. Self-Paced Karel Course in NCLab