Learn How to Think with Karel the Robot. Chapter 7. Variables
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 >=.
7.1. What are variables and why are they useful?
In computer programming, variables are used to store information for later use. Karel can use numerical variables to remember numbers:
- 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.
He can also use text string variables to store text, such as:
- 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.
7.2. Types of variables
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.
7.3. Choosing the names of variables
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.
7.4. Creating and initializing numerical variables
The following sample code creates several numerical variables, both integer and floating-point,
and initializes them with different values:
2a = 0
3my_age = 12
4seconds_per_minute = 60
5hours_per_day = 24
6temperature = -15
7
8# Floating-point variables:
9half = 0.5
10pi = 3.14159265358979323846
7.5. Assignment operator =
Notice that in the previous program, the symbol ’=’ was used to assign values to variables. This
is completely different from mathematics where the same symbol is used for comparisons and
equations.
The mathematical equality is expressed using the symbol ==. Comparison operators will be discussed in Section 7.10 (page 655).
7.6. Displaying the values of variables
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:
7.7. Basic math operations with variables
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)
Output:
The symbols ’*’ and ’/’ represent multiplication and division, respectively:
2hrs = secs / 3600
3mins = hrs * 60
4print(secs, ~seconds =~, mins, ~minutes =~, hrs, ~hours~)
Output:
7.8. Keywords inc and dec
Karel provides the keywords inc and dec which can be used to increase and decrease the value
of any numerical variable by one, respectively:
Output:
Both the commands inc and dec can also be used to increase and decrease the values of
numerical variables by more than one:
Output:
7.9. Arithmetic operators +=, -=, *= and /=
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)
Output:
7.10. Comparison operators ==, !=, <, <=, > and >=
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
to":
Output:
The comparison operator != is the opposite of ==. It means "not equal to":
Output:
The comparison operator < means "less than":
2Y = X + 6
3if X < Y
4 print(~X is less than Y.~)
5else
6 print(~X is greater than or equal to Y.~)
Output:
The comparison operator > means "greater than":
2Y = X
3dec(Y)
4if X > Y
5 print(~X is greater than Y.~)
6else
7 print(~X is less than or equal to Y.~)
Output:
The remaining two operators, <= and >= are similar to < and >, respectively, except they admit
equality. Let’s just show an example for <=:
2Y = 2 * X - 2
3if X <= Y
4 print(~X is less than or equal to Y.~)
5else
6 print(~X is greater than Y.~)
Output:
7.11. Counting maps
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
nmaps:
Output:
7.12. Water supply
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
4 put
5 inc(wb)
6while bottle
7 get
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)
12 put
13 dec(wb)
14 print(~Found a bag - placing a water bottle.~)
15 go
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:
7.13. Karel and the Fibonacci sequence
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
are
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
program:
And indeed, at the end he obtains the correct result:
7.14. Review questions
Friendly reminder - for every question either none, one, or several answers may be correct.
QUESTION 7.1. Why do we use variables?
- A
- To store useful information for later use.
- B
- To make the program run faster.
- C
- To make the program use less memory.
- D
- To make the program shorter.
QUESTION 7.2. What types of variables are provided in Karel?
- A
- Numerical variables.
- B
- Text string variables.
- C
- Boolean (logical variables).
- D
- Complex variables.
QUESTION 7.3. Which of the following are valid names of variables?
- A
- my_name
- B
- 1st_name
- C
- _x_
- D
- NUM1
QUESTION 7.5. How does one create a new variable A and assign the value 10 to it?
- A
- A(10)
- B
- A := 10
- C
- A == 10
- D
- A = 10
QUESTION 7.6. What is the correct way to display the value of a numerical variable A?
- A
- print(’A’)
- B
- print(~A~)
- C
- print(A)
- D
- print[A]
QUESTION 7.7. The initial value of a variable x is 5. What will its value be after executing inc(x, 3)?
- A
- 5
- B
- 8
- C
- 2
- D
- An error will be thrown.
QUESTION 7.8. The initial value of a variable y is 9. What will its value be after executing dec(y)?
- A
- 10
- B
- 8
- C
- 9
- D
- An error will be thrown.
QUESTION 7.9. The initial value of a variable n1 is 3. What will its value be after executing n1 -= 4?
- A
- 1
- B
- -1
- C
- -3
- D
- An error will be thrown.
QUESTION 7.10. The initial value of a variable n2 is 12. What will its value be after executing n2 /= 4?
- A
- 8
- B
- 16
- C
- 3
- D
- An error will be thrown.
QUESTION 7.11. The value of a variable m is 5. Will the condition if m != 5 be satisfied?
- A
- Yes
- B
- No
QUESTION 7.12. The value of a variable M is 10. Will the condition if M <= 11 be satisfied?
- A
- Yes
- B
- No
QUESTION 7.14. The initial values of the variables x, y and z are 1, 2, 3, respectively. What values will they have after executing x += y, y *= x and z = y / z ?
- A
- x will be 2, y will be 4, z will be 6.
- B
- x will be 3, y will be 6, z will be 2.
- C
- x will be 2, y will be 4, z will be 3/4.
- D
- x will be 3, y will be 2, z will be 6.
Table of Contents
- About
- 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