What is your favourite colour? red
My favourite colour is red
Variables and data types
We call variable to a symbolic name that refers to an object. They act as memory containers for storing data values and are created when you assign a value to them using the assignment operator =
. For example, x = 5
assigns the integer value 5 to the variable x
.
The value stored in a variable can change or vary throughout your program and can be any data type such as integers, strings, or lists. You will see different data types further in this section.
= "Jean Golding"
name = 27
age = 76.4 weight
Chosing the correct name for a particular variable is an important task as a non-descriptive name (or worse, an incorrect name) will be very confusing for you and anyone reading your code. For instance, for a variable which contains a number representing a distance in miles, avoid shortened names like dm
, distm
or d
and instead use a name like distance_miles
. Remember, code will be written once but read many times so make it easy to read.
Getting data into your script
So far, all the code we’ve run is somewhat static. Variables get assinged a value in the script and very time we run it, the output is always be the same. We will see a lot more of this throughout this workshop, but for now we will introduce one more function that Python provides, input
.
The print
function is how we get information out of our program, and the input
function is a way of getting data into it. The function will pause the program and wait for you to type something in followed by Enter, and assign your input to a variable on the left hand side of the =
.
colour.py
= input("What is your favourite colour?")
fav print("My favourite colour is", fav)
Now, if we run this script, it will print the message specified and wait for you to type something. If you type “red” and then press enter, it will assign “red” to the variable fav
and then use that variable in the final print
function:
Terminal/Command Prompt
python3 colour.py