top of page
top

Python 1c - Creating Variables

noun-code-2821463-FFFFFF.png

What is a Variable?

A variable represents a value that can change as a program is running.

 

The two parts of a variable are the name (e.g. sweets) and the value (e.g. 8).

sweets = 8

print(sweets)

=

8

amount of sweets = 8

8sweets = 8

sweets

A variable can't contain spaces, it must start with a letter, and you must declare its value before you can use or print it.

You always need to print the variable name (e.g. biscuits), not the value (20) as the value can change.


Important – When writing variable names, we do not need speech marks. (e.g. type biscuits, not “biscuits”)

We use variables because the value of something might change as the program is executed.

 

For example, if someone eats a sweet then the value of our variable changes:

sweets = 8

print(sweets)

sweets = 7

print(sweets)

=

8

7

sweets = 8

print(Sweets)

You must be consistent with capital letters when writing variable names.

sweets and Sweets are treated as two different variables.

Creating Variables Task 1 (Age & Pets)

Make a variable named age and set it to your current age. On the next line print age.

Make another variable named pets and set it to how many pets you have. On the next line print pets.

Example solution:

14

2

Variables with Strings (Text)

In programming, a collection of alphanumeric characters (letters, numbers and punctuation) is called a string. "Pikachu" is a string.

In the example below, pokemon is the variable name that represents the variable value "Pikachu".

noun-pikachu-1074643-E8AD2E.png

pokemon = "Pikachu"

print(pokemon)

=

Pikachu

To create a string, we use "speech marks". Numbers by themselves and variable names do not use speech marks.  

Each variable can only have one value at a time, but it can change throughout the program.

noun-squirtle-1074642-E8AD2E.png

pokemon = "Pikachu"

print(pokemon)

pokemon = "Squirtle"

print(pokemon)

=

Pikachu

Squirtle

Creating Variables Task 2 (Superhero & Colour)

Make a variable named superhero and set it to any of your choice, such as "Spider-Man". Print the superhero variable on the next line.

Make another variable named colour and set it to the colour related to your chosen superhero. Print the colour variable on the next line.

Example solutions:

Spider-Man

Red

The Hulk

Green

bottom of page