How To Assign a Value to a Variable in Python
What are variables?
Remember that in math you did if x=2 then 2x+1 is 5. In programming, there is something called variables, and they act like x acting on the equation, but instead of having only numbers ‘stored’ by x, we can install different types of data.
And variables in programming basically refer to different memory locations in the computer, and when the python interpreter gets a variable, it stores the data in the memory, and store the memory locations in the variable, and when you use a variable you are giving the interpreter memory locations that it can use in order to use the values in the memory locations.
How do you use it? In python it is pretty straight forward to use variables, the basics are as follows:
1 2 3 4 5 6 | variable_a = 53 print variable_a #output: 53 variable_b = 'Mr Awesome!' print (variable_b) #output: Mr Awesome |
You should have noticed that above statements, when we are stating an integer then we do not need to use apostrophes, while if you are stating a string (that is what is called), then you need to start and end it with an apostrophe, without the apostrophes it will not work.
A variable should have a name that is alphanumeric, with the exception of ‘_’, and variables names are case sensitive, here are some demonstrations of what will work and what will not work:
1 2 3 4 5 6 7 8 9 10 11 | my age = 20 # not gonna work, however my_age = 20 will work #(Incidentally, i am not 20 years old!) my * name = 'Mr. Awesome' ; #not gonna work, however my2name='Mr. Awesome'; myCar = 'BMW' ; mycar = 'Toyota' ; print (myCar) # output: BMW print (mycar) # output: Toyota |
There are also keywords that you cannot use as variables, here is a list of keywords as of python 3:
and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
Sometimes as a programmer you will need to join two different strings into a single one, in programming this is called concatenation, this is can be done as simply as:
varA
=
'I love'
;
varB
=
' Python'
;
# now in variable varC we concatenate it:
varC
=
varA
+
varB;
print
(varC);
#output: I love Python
varD
=
2
;
varE
=
3
;
varF
=
varD
+
varE;
print
(varE);
#output: 5
Why? simply because you are adding two integers, if however, you want to get the result of getting “23″ then you are going to have to get it as a sting, and varF will have to be a string, this can be done by adding a quote containing nothing, like this:
varD
=
2
;
varE
=
3
;
varF
=
varD
+
varE
+
"";
print
(varE);
#output:23
Post A Comment:
0 comments: