In programming, variables are used to store data.
For example, if you are making a game, you may want to keep track of the score or the health of a player. You can do this using variables.
We've already used variables in for loops to keep track of how many times they looped. But you can also use variables to store arbitrary information of any type, for any reason at all.
Let's look at the syntax for creating a variable called my_variable:
The value on the right is stored in the variable on the left. You can change the value of your variable at any time, and Python will keep track of it for you!
In these examples, x will have the value 7 and y will have the value 8.
You are both declaring and initializing the variable at the same time, with one line. That means you're creating a new variable and giving it a name (declaration) and assigning a value to that variable (initialization).
Is addition or multiplication performed first? Press run to see the output.
Declare your own variables, assign different values to the variables, and then print() them to see how they evaluate. Press run to see the output. Assign a new value to an existing variable to see how it changes.
The character needs energy! How much energy does the character need to reach the pixie dust?
Set the initial energy level for the character in the energy variable before you give any commands to the character. Your character uses 10 units of energy to move one space. (The energy variable starts at 0 by default. Change it to the correct number.)
| Command | Description |
|---|---|
| forward() | Moves the character one step forward. |
| turn_left() | Turns the character to the left. |
energy.energy should be enough to reach the pixie dust. For example, energy = 20.
Stock up! Provide the character with enough energy to reach the pixie dust.
Remember, energy is set to 0 by default. You need to set energy to the exact amount of energy needed to complete the puzzle.
| Command | Description |
|---|---|
| forward() | Moves the character one step forward. |
| turn_left() | Turns the character to the left. |
| turn_right() | Turns the character to the right. |
| has_path_left() | Returns true if there is a path to the left. Otherwise, it returns false. |
| has_path_right() | Returns true if there is a path to the right. Otherwise, it returns false. |
| reached_goal() | Returns true if the character has reached the pixie dust. Otherwise, it returns false. |
energy.energy should be enough to reach the pixie dust. For example, energy = 20.
Give the character enough energy to jump over gaps. Watch out! It costs 20 energy to jump, since you travel two spaces.
Remember, energy is set to 0 by default. Set its value to the correct amount.
| Command | Description |
|---|---|
| forward() | Moves the character one step forward. |
| turn_left() | Turns the character to the left. |
| has_path_left() | Returns true if there is a path to the left. Otherwise, it returns false. |
| reached_goal() | Returns true if the character has reached the pixie dust. Otherwise, it returns false. |
| is_gap_ahead() | Returns true if the path in front has a jumpable gap. Returns false if the path is clear. |
| jump() | Makes the character jump over a gap and land on the other side. |
energy.energy should be enough to reach the pixie dust. For example, energy = 20.In Python, you can use variables to store text, not just numbers. We call text based information strings. A string is just a series of characters, like "Hello" or "It's cold outside." or "Game over!"
You create a string by surrounding text with a pair of single quotes ' or double quotes ".
Programmers call numbers and strings data types, which describe the nature of the information stored in a variable. You've also seen True and False, which are boolean values, another data type.
The Python syntax for declaring strings is as follows:
If you want to use a quote inside a string, make sure to use a different quote to enclose the string. For example, you could write:
The example below shows a few strings that use single quote (') as well as double quotes (") . Try changing around the quote marks so you understand how they work. Click on the Play button to try it out.
You can join strings together using the + operator. Read this example, then press run.
Programmers call this concatenation.
Even though it seems like you can "add" two strings together, you can't add a number and a string together.
This won't work! Why not? 32 and "Hello" are two different data types. One is a string and the other is a number. To combine a number and a string, you'll need to convert the number to a string using str() first.
That function, str(), converts the number 32 into a string that holds the string "32".
What happens when you use the * instead of +, though? Try it out!
Let's look at some other methods (a special kind of function) that are useful when working with strings. Suppose that we have a variable called string1, let's take a look at what we can perform on that string:
| Method | Description |
|---|---|
len(string1) |
This function returns the length of the string (how many characters are in it). |
string1.index("text") |
This method returns the index position of the first occurrence specified by the parameter text, inside the string. If you wanted to know the position of the first instance of the letter a within string1, you would write: string1.index("a") |
string1[start:end] |
This method is used to extract a portion of the string, sometimes called a substring. The first parameter start is the starting index position for the extraction while the second parameter end specifies the last position. For example, to extract the first three characters of string1, you would write string1[0:2] |
string1.lower() |
This method converts the string to lower case. |
string1.upper() |
This method converts the string to upper case. |
Here are some examples using the string properties and methods described above. Click on the Play button to try it out.
It looks like a trap!
Set the L1 variable to the correct color, displayed inside the circle, to disable the trap. Run the program below when you are ready to try it out.
Note: You don't need to use any forward() commands in this puzzle.
In a hurry? We can define many variables to many different values all at once, in a single statement.
To define multiple variables in a single statement, separate the variables you want to define with a comma ,. Then put a = operator and the values you want to assign to the variables in corresponding order, also separated by commas. Let's see it in action.
Here, x, y, and z are assigned values in a single line of code.
The same syntax works with strings, too:
The values don't have to all be the same type, either. You can assign variables of different types on the same line.
This example declares and assigns the three variables x, y, and z in a single statement, then assigns three more called a, b, and c, in terms of x, y, and z. Then it prints the value of those variables. Press Play to see the output.
Note: You can't reference the value of variables in terms of variables you're defining in that line, though.
For example, this line of code won't work, because b is defined in terms of a, and c is defined in terms of a and b:
You can change the value of a variable at any time. Notice how the value of my_name changes and score changes. Press Play to see the output.
Declare multiple variables and assign multiple variables in a single statement. Press Play to see the output.
Hungry carnivorous plant ahead! But look, it's stronger than your average plant. See that 2? It will need two arrows to take down!
You can't jump over it, either.
You'll also need to set the power variable to the required value before sending commands to the character. Like energy, power is also set to 0 by default. Set its value to the exact number of arrows you need to clear the puzzle.
| Command | Description |
|---|---|
| forward() | Moves the character one step forward. |
| enemy_in_sight() | Returns true if there is an enemy in your line of sight. |
| fire() | Launches an arrow that travels 5 steps forward. |
fire() command to launch an arrow that travels 5 steps and destroys the enemies. Each fire() command uses one unit of power.power. The initial value of power should be enough to destroy all the enemies. For example, power = 2.energy and power variables before you send the commands to the character.energy and power should be exactly enough to complete the puzzle.
Use a new command to determine how much health a carnivorous plant has.
The command get_enemy_health() returns the health of the carnivorous plant in front of you. Try using this number in a loop!
| Command | Description |
|---|---|
| forward() | Moves the character one step forward. |
| get_enemy_health() | Returns the health of the enemy on the path ahead. Returns 0 if the path is clear. |
| fire() | Launches an arrow that travels 5 steps forward. |
get_enemy_health() command to see how much health an enemy in front of you has.get_enemy_health() to get its initial health, store the value in a local variable, then call fire() in a "for" loop.get_enemy_health() is greater than 0, then have the character fire() inside the loop.fire() command to launch an arrow that travels 5 steps and destroys the enemies. Each fire() command uses one unit of the power.power. The initial value of power should be enough to destroy all the enemies. For example, power = 2.energy and power variables before you send the commands to the character.energy and power should be exactly enough to complete the puzzle.
It looks like another trap! You must match the colors of the circles to disable the trap.
Set the L1 and L2 variables to the correct colors, displayed inside the circles, to disable the trap.
Note: You do not need to use any forward() commands in this puzzle.
Run the program when you are ready to try it out.
There are carnivorous plants and gaps! Fire at the plants and jump over the gaps.
| Command | Description |
|---|---|
| forward() | Moves the character one step forward. |
| turn_left() | Turns the character to the left. |
| turn_right() | Turns the character to the right. |
| has_path_left() | Returns true if there is a path to the left. Otherwise, it returns false. |
| has_path_right() | Returns true if there is a path to the right. Otherwise, it returns false. |
| reached_goal() | Returns true if the character has reached the pixie dust. Otherwise, it returns false. |
| enemy_in_sight() | Returns true if the path in front has an enemy. Returns false if the path is clear. |
| get_enemy_health() | Returns the health of the enemy on the path ahead. Returns 0 if the path is clear. |
| fire() | Launches an arrow that travels 5 steps forward. |
| is_gap_ahead() | Returns true if the path in front has a jumpable gap. Returns false if the path is clear. |
| jump() | Makes the character jump over a gap and land on the other side. |
get_enemy_health() command to see how much health an enemy in front of you has.get_enemy_health() to get its initial health, store the value in a local variable, then call fire() in a "for" loop.get_enemy_health() is greater than 0, then have the character fire() inside the loop.fire() command to launch an arrow that travels 5 steps and destroys the enemies. Each fire() command uses one unit of power.power. The initial value of power should be enough to destroy all the enemies. For example, power = 2.energy and power variables before you send the commands to the character.energy and power should be exactly enough to complete the puzzle.
An expression is any valid combination of variables, literals, operators, and function calls that compute to a single value.
You've already seen that expressions can assign a value to a variable.
For example, this expression assigns the literal value of 10 to the variable x.
Some expressions do not assign a value to a variable, but simply evaluate to a value. Some examples below:
An expression can evaluate to any kind of data type, such as a string, boolean, or integer, and can appear in your Python code wherever a value is expected.
You've already seen many types of operators that can be used in an expression, such as +, *, =, and so on. The kinds of expressions used in an expression hint at what kind of expression it might evaluate to. Let's take a closer look:
+, -, *, /, %, and more.not, and, or.+, and the combined concatenation and assignment operator +=.
Press Run to see the outcome of the code below. Then assign your own expressions to some new variables.
Try creating all three kinds of expressions discussed here: arithmetic expressions, logical expressions, and string expressions.
You have discovered more pixie dust, but it's guarded by another trap! This one requires you to enter an expression instead of colors.
Set the L1 variable to the correct expression on the display to disable the trap.
Note: You do not need to use any forward() commands in this puzzle.
*.**.
So far, we've mostly worked with whole numbers like 1, 2, and -1. These numbers are also called integers. But we can also store numbers with decimal values like 3.14159, which are also called floating point numbers (or floats for short).
Python has separate data types for different kinds of numbers. In Python, integers are values with type int, and floating-point numbers are values with type float. Generally, you can use an int to do the same kinds of things you might do with a float, but the reverse is not always true; some operations in Python require a value of type int and will not work with a float.
In Python, numbers can be assigned to a variable without specifying their type:
Python has functions that can be used to convert a value to a specific type, if possible.
| Function | Description |
|---|---|
int(value) |
Converts a value (such as a string or float) to an integer. |
float(value) |
Converts a value (such as a string or integer) to a floating point number. |
str(value) |
Converts a value (such as an integer or float) to a string. |
You can use int() and float() to convert integers to floating-point numbers and vice versa. Press Run to see the output.
The editor below shows how you can convert strings of numbers to int and float values. Press Run to see the output.
You can also convert an integer or float to a string. Press Run to see the output.
Try using the int() , str(), and float() functions to change between different data types. Press Run to see the output.
Operator precedence is the order in which operators in an expression are evaluated. Arithmetic operators in Python are evaluated similar to the arithmetic operator precedence you've learned in school, PEDMAS.
You can use parentheses to override precedence of operators.
Expressions will evaluate operator in this order, from first to last (highest precedence to lowest):
| Type | Operators |
|---|---|
| parentheses | () |
| exponent | ** |
| multiply/divide | *, /, % |
| addition/subtraction | +, - |
| comparison | <, <=, >, >=, ==, != |
| negation | not |
| logical-and | and |
| logical-or | or |
| assignment | =, +=, -=, *=, /=, %= |
Is addition or multiplication done first?
Add your own expressions and see how they evaluate.
Good job! There's more. This trap requires you to enter another expression.
Note: You do not need to use any forward() commands in this puzzle.
Here's a reminder of the common arithmetic operators:
+.*.**.
There are times when you'll want to store different values in a single variable.
The list data type allows a single variable to store multiple values.
The Python syntax for defining a list is as follows:
item1, item2, and so on are called the elements of the list. And elements within a list can be of any data type: numbers, strings, booleans, and so on.
For example:
To declare an empty list, simply use the square brackets without any items in it.
In Python, while defining a list, any spaces and line breaks are ignored, so your list definition can span multiple lines as shown below.
Not every element within the list needs to be the same type, either. For example, you can store first name, last name, and the player's score with a mix of string and number data types. You can even store a list within another list!
Let's say you need to store five different color names in your program. Without lists, you would have to store each value in five different variables, like this.
This works well enough when you only need to store a few values, but what if you needed to store hundreds or even thousands of values? You would have to create many, many variables, and your code would become difficult to change or debug.
The solution to this issue is to use a list.
You need to use an index in order to access the elements inside the list. An index is an int that refers to the relative position of each element in the list. (You cannot use a float as a list index!)
In Python, indexes are "zero-based" which means the first element is at index 0, rather than 1. That means that the second element is at index 1, the third element is at index 2,..., and the nth item is at index n-1.
To access an element of the list, you write:
For example, let's say you wanted to access the third element of the colors list, and store it in a new variable called color_yellow.
You can also update an item in the list using its index. For example, to change "yellow" to "violet" in our colors list, we'd write:
This changes the third list item.
You can use the same len() method to get the length of a list as you did with a string.
For example,
Create a list of items and practice manipulating its item with indexes.
Let's review what you've learned so far about variables.
In programming, variables are used to store data.
Let's look at the syntax for creating a variable called my_variable:
The value on the right is stored in the variable on the left. You can change the value of your variable at any time, and Python will keep track of it for you!
In these examples, x will have the value 7 and y will have the value 8.
Variables allow you to access the same value in multiple instructions, making it easier to change the information your program uses.
When a variable is reassigned to a new value, the old value is discarded and replaced with a new one.
To define multiple variables in a single statement, separate the variables you want to define with a comma ,. Then put a = operator and the values you want to assign to the variables in corresponding order, also separated by commas. The values assigned can have different types.
You can join variables with literal strings to add labels or additional characters around the variable's value.
In Python, we use strings to store text. Strings are enclosed within quotes. You can use a single quote ' or a double quote ".
The Python syntax for declaring strings is as follows:
The string data type has many methods (a special kind of function) that can be used to access and manipulate the data.
| Method | Description |
|---|---|
len(str) |
This function returns the length of the string (how many characters it uses). |
str.index(" text") |
This method returns the starting index position of the first occurrence of a specific text, specified by the parameter text, inside the string. |
str[ start:end] |
This method is used to extract a portion of the string. The first parameter start is the starting index position for the extraction while the second parameter end specifies the end of the string to extract. |
str.lower() |
This method converts the string to lower case. |
str.upper() |
This method converts the string to upper case. |
Let's review what you've learned about expressions and lists in this lesson.
Python has separate data types for different kinds of numbers. In Python, integers are values with type int, and floating-point numbers are values with type float.
You can use int(), float(), and str() functions to convert between datatypes, to perform calculations, or display numbers as text, as needed.
An expression is any valid combination of variables, literals, operators, and function calls that compute to a single value.
Operators such as +, *, and = can be used within expressions.
Expressions can assign a value to a variable. For example, the expression:
assigns the literal value of 10 to the variable x.
Some expressions don't assign but simply evaluate to a value. Some examples below:
An expression can return a string, boolean, or number.
Arithmetic expressions evaluate to a number and use arithmetic operators such as +, -, *, /, % .
Logical expressions evaluate to a true or false and use logical operators like not, and, or.
String expressions evaluate to a character or string and use string operators like concatenation + and assignment operators like +=.
Operator precedence is the order in which the operators in an expression are evaluated to get the expression's value. You can use parentheses to override precedence of operators.
| Type | Operators |
|---|---|
| parentheses | () |
| exponent | ** |
| multiply/divide | *, /, % |
| addition/subtraction | +, - |
| comparison | <, <=, >, >=, ==, != |
| negation | not |
| logical-and | and |
| logical-or | or |
| assignment | =, +=, -=, *=, /=, %= |
Lists are used to store lots of data in one variable. The Python syntax for defining a list is:
item1, item2 , and so on are the elements of the list. The elements in a list can be of any data type: numbers, strings, booleans, or even other lists. The items in the list are separated by commas.
To declare an empty list, simply use the square brackets without any items in it.
In Python, while defining a list, any spaces and line breaks are ignored, so your list definition can span multiple lines.
You can access specific items in the list using an index. An index is an integer that refers to the relative position of each element in the list. You cannot use a float as a list index!
You can use the len() method to get the length of a list in the same way that you did with a string.