What is a Variable?
A variable is a space in memory which allows you to store data. This of it as a box in which you could store a value.
In Python to create a variable give it a name and assign a value: x = 42 It is important to name variables sensibly. They should be named with a noun to describe the variable's contents. |
Data Types
Booleans.. True or False?
The data type bool allows you to store the values true or false. There are many instances where a boolean is useful. For example in deciding when to terminate a while loop.
|
Casting: Converting between Data Types
You may need to convert from one simple data type to another. This is called casting.
The following code will print "12" because a and b are both strings:
a = "1"
b = "2"
print(a+b)
#outputs 12
The following code casts the variables a and b to integers and stores the new values in the variable x and y. The variables x and y will add to 3 which will be displayed.
x = int(a)
y = int(b)
print(x+y)
#outputs 3
The following code will print "12" because a and b are both strings:
a = "1"
b = "2"
print(a+b)
#outputs 12
The following code casts the variables a and b to integers and stores the new values in the variable x and y. The variables x and y will add to 3 which will be displayed.
x = int(a)
y = int(b)
print(x+y)
#outputs 3
Scope: Global vs Local Variables
Variable scope means where can the variable "be seen." A global variable can be seen everywhere, so you can use it everywhere. A local variable is one which has been created within a block of code. This means that the variable can only be seen within that block of code. If you try to refer to it before or after you will get a syntax error.
Variables created within a function are local to that function and not accessible outside. However, you can pass in data via a parameter variable and assign it to the local variable. You can also pass out the value of the local variable by returning it from the function. |
Operators
If you're storing lots of numbers it's likely that you will want to do some calculations. So you will need to understand operators.
Arrays
Variables store one piece of data e.g. a name. What if you want to store lots of similar data together. For example: The names of all students in a class. Use an array.