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. picture

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: picture

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: picture

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:

Program 7.1: Creating and initializing numerical variables
1# Integer variables: 
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. picture

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:

Program 7.2: Displaying values of variables
1a = 3 
2b = 5 
3d = 15.5 
4print(a) 
5print(~Value of b is~, b) 
6print(~Distance d is~, d, ~meters.~)

The output of this program is:


PIC


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 ’-’):

Program 7.3: Addition and subtraction
1item_1 = 12.5 
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:


PIC


The symbols ’*’ and ’/’ represent multiplication and division, respectively:

Program 7.4: Multiplication and division
1secs = 5400 
2hrs = secs / 3600 
3mins = hrs * 60 
4print(secs, ~seconds =~, mins, ~minutes =~, hrs, ~hours~)

Output:


PIC


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:

Program 7.5: Increasing and decreasing the values of variables by one
1m1 = 10 
2m2 = 20 
3inc(m1) 
4print(~m1 =~, m1) 
5dec(m2) 
6print(~m2 =~, m2)

Output:


PIC


Both the commands inc and dec can also be used to increase and decrease the values of numerical variables by more than one:

Program 7.6: Increasing and decreasing the values of variables by more than one
1m1 = 10 
2m2 = 20 
3inc(m1, 3) 
4print(~m1 =~, m1) 
5dec(m2, 5) 
6print(~m2 =~, m2)

Output:


PIC


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.

Program 7.7: Operators +=, -=, *= and /=
1a = 11 
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:


PIC


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":

Program 7.8: Comparison operator ==
1X = 99 
2Y = X 
3if X == Y 
4  print(~X and Y are the same.~) 
5else 
6  print(~X and Y are different.~)

Output:


PIC


The comparison operator != is the opposite of ==. It means "not equal to":

Program 7.9: Comparison operator !=
1X = 1 
2Y = 1.1 
3if X != Y 
4  print(~X and Y are different.~) 
5else 
6  print(~X is the same as Y.~)

Output:


PIC


The comparison operator < means "less than":

Program 7.10: Comparison operator <
1X = -3 
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:


PIC


The comparison operator > means "greater than":

Program 7.11: Comparison operator >
1X = 1 
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:


PIC


The remaining two operators, <= and >= are similar to < and >, respectively, except they admit equality. Let’s just show an example for <=:

Program 7.12: Comparison operator <=
1X = 2 
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:


PIC


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.


PIC

Figure 7.1: *

Karel is counting maps.


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:

1while not home 
2  if map 
3    get 
4  go

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:

Program 7.13: Count the maps!
1nmaps = 0 
2while not home 
3  if map 
4    inc(nmaps) 
5  go 
6print(~I found~, nmaps, ~maps.~)

Output:


PIC


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.


PIC

Figure 7.2: *

Karel is putting water bottles in bags.


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:

1wb = 0 
2while not empty 
3  put 
4  inc(wb) 
5while bottle 
6  get

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:

Program 7.14: Put the water bottles in the bags!
1# Count the water bottles: 
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:


PIC


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

1, 1, 2, 3, 5, 8, 13, 21, 34, 55.
Today, Karel wants to create this sequence by himself! He begins with two beepers on the floor, and two variables n1 = 1 and n2 = 1 for the first two numbers in the sequence:


PIC

Figure 7.3: *

Karel is going to create the Fibonacci 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 program:

Program 7.15: Create the Fibonacci sequence!
1n1 = 1 
2n2 = 1 
3repeat 8 
4  new_n = n1 + n2 
5  repeat new_n 
6    put 
7  n1 = n2 
8  n2 = new_n 
9  go

And indeed, at the end he obtains the correct result:


PIC

Figure 7.4: *

The first 10 numbers of the Fibonacci sequence.


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.4. Are x1 and X1 the same variable in Karel?

A
Yes
B
No

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.13. What numbers belong to the Fibonacci sequence?

A
1
B
5
C
33
D
55

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

Created on September 27, 2018 in Karel.
Add Comment
0 Comment(s)

Your Comment

By posting your comment, you agree to the privacy policy and terms of service.