Python 1c - Creating Variables

What is a Variable?

A variable represents a value that can change.

 

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

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

=

Remember to use the print command to display something to the screen.

 

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 munches a biscuit then the value of our variable changes:

=

Practice Task 1

1. On line 1 write a variable with the name Age and the value of your current age.

2. On line 2 print the variable name Age.

3. On line 3 write a variable with the name Pets and the value of how many pets you have.

4. On line 4 print the variable name Pets.

Example solution:

Variables with Strings

=

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

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

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

A variable can only have one value at a time, but it can change throughout the program. The variable name never changes.

=

Practice Task 2

1. On line 1 write a variable with the name FirstName and the value as your first name.

2. On line 2 write a variable with the name Surname and the value as your surname.

3. On line 3 print the variable name FirstName. (Use the variable name FirstName, not just your first name in speech marks)

4. On line 4 print the variable name Surname.

Example solution:

© CSNewbs 2020