9 - Variables-I
9 - Variables-I
What is a variable?
In simple words, a variable is a place where you can store information in
Python. It's like a box that you can put things in. You can give the variable a
name, and then you can use that name to access the information that's
stored in the box.
You can look to variables as something that holds a value, think of x and y in
math.
Declaring a variable
In python, declaring a variable is pretty straightforward. Look at the
following example:
The above code simply declares a variable called myname, which has the
value "Omar". This means, that whenever I use the variable myname, I will be
using the name Omar.
Declaring a variable
Examples on Variables
Assignment Operator
Assignment operator works as follows, we assign the value on the right to the
variable on the left. And now, whenever we use the variable, we will get that
value.
Assignment Operator
Note:
= in python is not the same as = in maths.
For example, in math when we say x = y, y = x.
Both expressions have the same meaning, which is that both x and y are equal to each
other.
However, in python this is not the case. In python x = y means whatever the value
that y holds is, get that value and assign it to x. However, y = x, means the opposite. It
means take the value that is stored in x and assign that to y.
Assignment Operator
Question Time
What do you think will happen when we run the following code?
Answer
Naming Rules
Variable names must start with a letter or the underscore character.
Variable names cannot start with a number.
Variable names can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different
variables)
Variables names cannot be reserved keywords, like print(), from, in. Here is
a list of the reserved keywords in python.
Naming Rules
Here are some examples of valid variable names:
my_var
_my_var
myVar
MYVAR
myvar2
Naming Rules
Here are some examples of invalid variable names:
2myvar
my-var
my var
my$var
Naming Rules
Good Practice:
Use descriptive variable names. This will make your code easier to understand
and maintain. For example, instead of using the variable name "x", you could
use the variable name "total_price".
Naming Rules
into this:
Updating Variables
This works also with the decrement operator.