Text
Variables that contain some form of text are called strings. Since text is very common, there are also built-in functionality for dealing with strings. We are going to take a look at some of them in this section.
Lower and upper case
Look at this example:
import turtle
turtle.color('red')
answer = input("How far should I go? (short/far):")
if answer == "short":
turtle.forward(50)
elif answer == "far":
turtle.forward(200)
else:
print("I don't understand")
What happens if you input "Short" or "SHORT"? In the world of the computer, that's not the same as "short", because we've changed some of the lower case to upper case letters. If a single letter is wrong, or if there's a space afterwards, Python will see this as a different string and the conditions in the above statements will be considered false.
We can obtain a lower case version of a string using a function called lower():
answer = answer.lower()
Try adding this line right after the input line. Then "Far" and "FAR" will also work.
Whenever we need the same with upper case we also have the upper() function.
Looping over a string
The individual letters in a string are a form of range as well. We can use for-loops to repeat code, once for each letter. Here's a small example:
name = "Marcus"
for letter in name:
print(name)
This for loop, just as before, runs the print statement several times. In this case, once for every letter. If you run this code, you will see each letter printed on a separate line.
We can use this to summarise instructions for the turtle in a string:
Can you see what you should put inside the variable instructions to make the turtle draw a square?
In this video, we take a closer look at strings. How can we pick out individual characters/strings, and how can we use strings to draw patterns?
- Variable: A part of the computer's memory where we can store something, like a piece of text, a name, or a number.
- String: Various pieces of text is called a string. Shortened to "str".
- for-loop: One type of loop/repetition that fits well for a predetermined number of steps.