Skip to main content

Section 1.6 Variables

90 minutes
Variables are named memory locations that store values used by a program. These values can change or vary as the program runs. A variable is like a box with a label where different values can be put into the box. For example, when you interact with an app or game, there may be variables that store your name or your score, and these variables can be used by the app to customize how it behaves or the information it displays. In this section, you will learn how to identify variables in apps and how to use them in Python print and input statements.

Subsection 1.6.1 Identifying Variables in Apps

Try the following pizza web app by typing in your name and choosing different options. Think about the inputs and outputs to the app. When you type in your name and other inputs, your information gets saved in variables in the program. These values can then be used in the outputs of the app.

Activity 1.6.1.

Interact with the pizza app above. Which of the following are variables that the app above might use to store information about the user.
  • name
  • The app needs to store the user’s name to display it in the output.
  • favoriteColor
  • The app needs the favorite color to change the background to that color.
  • address
  • The app does not need the user’s address to function, so it would not use a variable to store this information.
  • age
  • The app needs to store the user’s age to display it in the output.
  • temperature
  • The app does not need to know the temperature to function, so it would not use a variable to store this information.
  • likesPizza
  • The app needs to store whether the user likes pizza to display it and pizza images in the output.
Some video games keep a list of players with the highest scores in the game. Each entry in the list a snapshot of the program state at a certain time. For example, the player with the name or initials "AKI" had a score of 12,000 at a certain point.

Activity 1.6.2.

Subsection 1.6.2 Variables in Python

Variables are names for memory locations that store values used in a program. In Python, a variable is created when a value is assigned to it. For example, the following code creates a variable named name and assigns the value "Dani" to it and a variable named age with the value 16. Note that text values like "Dani" are placed in quotes (""), but numbers like 16 are not.
# variable = value
name = "Dani"
age = 16
In Python, multiple values can be printed out separated by commas. The variables, name and age, are never put inside quotes because we do not want to literally print the variable names; we want to print the values stored in the variables.
print("Hello", name, "you are", age, "years old")

Activity 1.6.3.

Run the following code. Change the variable values and run again.

Activity 1.6.4.

Drag or click on the blocks you need to move them from the top section into the yellow area to create a print statement with the variable name. For example, if name = "Alex", it will print "Hello Alex!". There are extra blocks that you don’t need.

Subsection 1.6.3 Data Types

The pizza app above stores lots of different types of data: the user’s name, their age, their favorite color, and whether they like pizza. The user’s name is text (which is called a string in coding, but the age is a number. Whether they like pizza or not could be stored as a Boolean value of true or false (the type Boolean is named after the mathematician George Boole who invented symbolic logic). These are all different data types.
In some languages, you have to declare the data type of a variable, but in Python, the data type is assigned automatically depending on its value during run time. Python has several built-in data types, including:
  • int - for integers (whole numbers)
  • float - for floating-point numbers (decimals)
  • str - for strings (text)
  • bool - for boolean values (True or False)
name = "Dani"   # type string
age = 16        # type int
You can check the data type of a variable using the type() function. For example:
print(type(name)) # This will print str, for a string or text data type
print(type(age)) # This will print int for an integer whole number

Activity 1.6.5.

Run the following code to see the data types of the variables. Add another print to see the type of the last variable which is a number inside quotes. You’ll see that anything in quotes is a string, even if it is a number inside.

Subsection 1.6.4 Naming variables

Although you can name a variable almost anything you want, there are some rules and conventions to follow. In Python, variable names must follow these rules:
  • It must start with a letter or an underscore _.
  • It can contain digits, like 1 or 9, but not as the first character.
  • It cannot have spaces, or special symbols other than _
  • It cannot be a Python keyword. Keywords are words that have special meaning in the language(see below for examples).
  • Case matters. A variable named result is not the same as one named Result.
  • Use meaningful variable names that describe what the variable holds, not letters like x,y,z.
Python has a few dozen keywords that you can’t use as variable names. Here is a list of the most common ones. If you ever have an error based on one of your variable names and do not know why, compare your name to this list to make sure you are not using a keyword as your variable name.
Table 1.6.1. Python keywords
and as assert break class continue
def del elif else except exec
finally for from global if import
in is lambda nonlocal not or
pass raise return try while with
yield True False None

Activity 1.6.6.

Which of the following is not a legal variable name in Python?
  • my name
  • Right, you can’t have a space in a variable name.
  • my_name
  • You can use an underscore between words in a variable name.
  • _a1
  • Although it is not very common, you can use an underscore as the first character in a variable name
  • amountOfStuff
  • You can use both uppercase and lowercase letters in a variable name.
  • 1A
  • Correct, you can’t use a digit as the first letter in a variable name.

Subsection 1.6.5 Variables and Assignment

An assignment statement assigns a value to a variable using the assignment operator =. The first assignment to a variable initializes the variable to its first value. It can then be changed with other assignment statements. For example, the variable score is initialized to 0 and then changes to 50 below. Note that the variable name must match exactly with the same capitalization and spelling to have it refer to the same variable.
score = 0
score = 50

Activity 1.6.7.

Python variables are case sensitive so gameScore and gamescore are not the same. Run and fix the code below to use the right variable name.

Activity 1.6.8.

Subsection 1.6.6 Strings

In coding, a string is a sequence of characters surrounded by quotes (""). Imagine strings with lined up letter beads like below.
In the web app above, the text that the use types in like name was probably saved as strings.
Variables can be assigned values or an empty string "" that will be filled in later. Python allows double quotes "" or single quotes ’ for string values.
name = "Sam"                 # double quotes
email = '[email protected]'      # single quotes
message = ""                 # empty string
We can concatenate or append or add strings in Python using the operator +, which can be used to add numbers or strings. Blank spaces are not automatically added when you use + (unlike ,), so if you want a blank space, you need to type it inside the quotes or add in a string with just a space in it " " as shown below.
name = "Sam"
message = "Hello " + name     # note the space after Hello
print(message)

Activity 1.6.9.

Run the following code to see the smushed output. Fix the error by putting in an extra space and concatenate an ! at the end.
Since the operator + is used to add numbers or concatenate strings in Python, the interpreter will get confused and show an error if you use it to concatenate a string with a number. To concatenate the number with a string we need to convert the number into a string first. The str(num) function will convert a number into a string. Another option is to use the , instead of + in print statements because that will print different data types with no problem, but it can only be used in print statements.

Activity 1.6.10.

Run the following code to see the error. Fix the error by using str to convert the number.
In Python, every character in a string is associated with an index starting with 0. Square brackets and an index can pull out any character from a string.
Python has a special slicing operator to pull out a substring from a start index up to an end index (but not including the end index), message[start:end].
message = "Python is fun!"
letter = message[0]          # pull out 0th letter P
substring = message[0:6]     # substring "Python" from index 0 up to index 6

Activity 1.6.11.

Run the following code to see examples of slicing. Add to the code to print another substring of message that uses slicing to pull out the word "fun".

Activity 1.6.12.

Subsection 1.6.7 Input

Python has an input function that can be used to get input typed in by user. This input must be saved into a variable. This is another way to initialize or assign to a variable. The syntax for an input statement is:
variable_name = input("Input prompt or question? ")
The following code will ask the user for their name and then print out a greeting. Try it out by clicking the "Run" button. Run it twice and put in different names! Does it work? Yes, that is the power of abstraction! Our code is now more general or abstract and can work for any name! The input variable is an abstraction that can hold any name.

Activity 1.6.13.

Run the following code. Enter your name in the pop up input box and then scroll down to see the output.

Activity 1.6.14.

Drag or click on the blocks you need to move them from the top section into the yellow area to create an input statement that will ask for the user’s age. There are extra blocks that you don’t need.
The input() function in Python always returns a string, even if the user enters a number. For example, if the user enters "25", the variable will store the string "25", not the integer number 25. However, to do math with a number, as we will see in the next lesson, we need to store the value as a number rather than a string.
To convert a string to an integer whole number or a floating point decimal number, use the int() or float() functions. We will use these functions in the next lesson when performing calculations and making comparisons with user input. For example:
ageStr = input("Enter your age: ")
age = int(ageStr) # Convert the string to an integer
To convert a number back into a string, you can use the str() function. For example:
ageString = str(age) # Convert the integer back to a string

Activity 1.6.15.

Run the following code to see that there are some errors caused by the data types. Try using int or str functions to convert the variables to the correct data type.

Subsection 1.6.8 Coding Challenge: Story Project

Let’s make a poem or a story using input and variables in Python. Ask the user to input different nouns and verbs, and weave together a story.

Project 1.6.16. Story.

Finish the input statements below to ask the user for 2 colors and a food item. Run to see the silly poem. Then, ask the user for more input words and create your own poem or story using the variables in print statements.

Activity 1.6.17.

Is the variable color1 in line 5 of the code above used to store input or output?
  • input
  • Correct! The variable color1 is used to store user input.
  • output
  • Although the variable color1 is printed out, it is used to store user input, not output.

Activity 1.6.18.

What is the data type of the variable color1 in the code above?
  • int
  • Sorry, it is not an integer number.
  • float
  • Sorry, it is not a floating point decimal number.
  • string
  • Correct!
  • Boolean
  • Sorry, it is not a true or false value.

Activity 1.6.19. Project Reflection.

Identify an input and an output for your program above.

Subsection 1.6.9 Vocabulary Review

Activity 1.6.20.

Subsection 1.6.10 App Inventor Project (Optional)

If your class wants to create mobile apps using MIT’s App Inventor. do Paint Pot Tutorial Part 1.
You have attempted of activities on this page.