Variables are containers in which data values can be stored within the computer’s memory. They have a name, which is also referred to as an address.
|This is a box / container.
In variable terms, we can give it a name/address called box.
We can put things in the box. In programming, these things are called data values.
We can assign the data value books into the variable called box.
We use assignment operator = to assign the data value to the variable.
After assigning, we will have a box containing books.
By assigning a value into the box (variable), we can use the value multiple times by calling the box (variable), instead of retyping "books" (value).
|box = "books"||The string value "books" is assigned to the variable box|
|block_number = 72||The number value 72 is assigned to (=) the variable block_number|
|street_01 = ‘Nanyang Ave’||The string value ‘Nanyang Ave’ is assigned to the variable street_01|
|myList = ["apples", "bananas", "cherries"]||The list of fruits are assigned to the bariable myList.|
Tip! - It is good practice to choose meaningful / descriptive names that reflect the variable’s content for easier identification when you or someone else revisits your codes. Which variable names would you choose?
1. Must start with a letter, or the underscore character.
2. Can only contain alpha-numeric characters and underscores.
4. Cannot contain hyphens.
5. Cannot start with a number.
6. Cannot use Python reserved words – these mean something in Python
1. Create a variable called fruit, and store "apple" into the variable you created and print.
2. Are you able to print the following? Try it in your IDE.
|Questions||Can it run?||Changes|
|YEAR = 1995||Yes||Nil|
|course_code = "DSE2020"||Yes||Nil|
|01_street = ‘Nanyang Ave’||No, variable names cannot begin with a number||street_01 = 'Nanyang Ave'|
|my-birth-year = 1982||No, variable names cannot contain hyphens||my_birth_year = 1982|