paint-brush
Python fundamentals (3) — handling variablesby@sltrask
422 reads
422 reads

Python fundamentals (3) — handling variables

by Mr TraskNovember 3rd, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

There are many metaphors for variables in Python. One could view a <strong>variable </strong>as something like a bucket, into which you can place data. So the bucket called <strong>age</strong> could have the value of <strong>12</strong> — but, crucially, because it is a variable, it’s value can change to <strong>13</strong> or any other number at any point.
featured image - Python fundamentals (3) — handling variables
Mr Trask HackerNoon profile picture

There are many metaphors for variables in Python. One could view a variable as something like a bucket, into which you can place data. So the bucket called age could have the value of 12 — but, crucially, because it is a variable, it’s value can change to 13 or any other number at any point.

In truth, most quantities that we use in a programming language can have values that change, and these quantities are variables (the opposite of which is a constant, but more on that another time). A variable in Python has an identifier, and the Pythonesque way of thinking of this is (note the lower case):

identifier = value

So for example: age = 13

…has age as the identifier, in this case a variable, and 13 as the value. Another example:

name = input (“What is your name?”)

Here, the identifier (variable) is name, and the value that has been assigned to this variable is…ah, well, that is in fact another command within Python called input. The input command asks Python to issue the user with some text, such as “What is your name?”, and to await a response that the user types in on the keyboard. So in this case, the text that the user types in will be assigned to the variable called name.

Let’s flesh this out a little.

As you can see here, the first line of code simply prints “Hello, world.”. The name = input line displays the message “Please enter your name”), then stores what the user types. It then assigns this thing that it has stored to the variable name. In this case it stored the word ‘Steve’ and assigned it to the variable. Just for good measure, it then printed what is inside the variable (the word ‘Steve’), and then it strung together a message to the user, by using a + operator. This is something called concatenation and will be explored next. Simple really!