Python fundamentals (3) — handling variables

Written by sltrask | Published 2018/11/03
Tech Story Tags: programming | python | python3 | coding | edtech

TLDRvia the TL;DR App

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!


Published by HackerNoon on 2018/11/03