Variables

Variables are a way to store and use data within a program. Variables must be declared within the program and assigned to be used.

Key Points

Each variable is stored as a specific data type.

Variables can either be assigned directly or by user input.

Creating a Variable

Creating a variable is easy. The following code will create three variables; name, age and budget Each will be assigned a value.

#This assigns name to John. name is a string.
name = "John"

#This assigns age to 21. age is an integer.
age = 21

#This assigns price to 9.99. price is a float/real
price = 9.99

Creating a Variable from User Input

Variables can also be assigned directly by user input.

#This allows a user to store a name. name is still a string.
name = str(input("Please enter your name: "))

#This allows a user to enter their age. age is still an integer.
age = int(input("Please enter your age: "))

#This allows a user to store a price. price is still a float/real.
price = float(input("Please enter a price: "))

Using a Variable

With variables declared you can now use them throughout your code.

name = "John"

if name == "John":
    print("Hello John")

National 5 Requirements

You should be able to explain what a variable is.

You should be able to declare, assign and use variables within code.