Variables: learn programming in Python

By Russell Barnes. Posted

Variables are all-purpose containers used to store data when programming in Python

If you’ve created a science project or experiment, you may have come across variables. In science, a variable is any factor that you can control, change or measure. You'll use them a lot when programming in Python.

In computer programming, variables are used to store things in your program. They could be names, numbers, labels, and tags: all the stuff your program needs.

In this article we’re going to look at how you create a program on a Raspberry Pi. We’re going to look at the following:

  • What is a Variable?
  • Create variables in Python
  • Access variables in Python
  • Different variables types and typecasting

This article is based on Beginner’s Guide to Coding in issue 53 of The MagPi. Issue 54 of The MagPi has a companion piece on learning object orientated programming with a Raspberry Pi

See also:

Using variables in Python programming

In Python, you write the name of a variable then a single equals sign and the word, number or object you want to put in it.
Enter this code directly into the Shell:

foo = 1
bar = 2
Remember: the variable name is on the left, and the thing it contains is on the right. Imagine you’ve got two plastic cups, and you’ve scrawled ‘foo’ on the first and ‘bar’ on the second. You put a number 1 in foo and a number 2 in bar. If you ever want to get the number again, you just look in the cup. You do this in Python by just using the variable name:
foo
bar

Why does Foo Bar appear a lot in Python programming?

You’ll come across ‘foo’ and ‘bar’ a lot when learning to code. These are dummy placeholders and don’t mean anything. They could be zig and zag or bim and bam. Nobody’s quite sure, but it might be related to the expression ‘fubar’ from the Vietnamese war.

You can also print out variables by passing them into a print function:

print(foo)
print(bar)

Variables can also be used to contain ‘strings’. These are groups of letters (and other characters) that form words, phrases or other text.

Creating a string variable in Python is pretty much the same as creating an integer, except you surround the text with single (' ') or double (" ") quotes.

Using double quotes makes it easier to include apostrophes, such as print("Don’t worry. Be Happy"). This line would break after ‘Don’ if you used single quotes – print('Don’t worry, be happy') – so use double quotes for now.

Why variables count in Python

Variables make it much easier to change parts of your code. Say you’ve got an excellent coding job at Nursery Rhymes Inc and you’ve written a classic:

print("Polly put the kettle on")
print("Polly put the kettle on")
print("Polly put the kettle on")
print("We’ll all have tea")

The head of marketing comes in and says “our data shows that Polly isn’t trending with the millennial demographic.” You say “Huh!” and he barks “Change Polly to Dolly.”

You now have to go through and change the variable in all three lines. What a downer! But what if you’d written thousands of lines of code and they all needed to change? You’d be there all week.

With variables, you define the variable once and then use it in your code. Then it’s ready for changing at any time:

name = "Polly"

print(name + " put the kettle on")
print(name + " put the kettle on")
print(name + " put the kettle on")
print("We’ll all have tea")

This code prints out the same classic nursery rhyme. But if you want to change the name of our character, you only have to change it in one place:

name = "Dolly"

…and the poem will update on every line.

Types in Python programs

When you create a variable in Python, it’s automatically assigned a type based on what it is. You can check this using the type() function. In the shell interface, enter:

foo = "Ten"
bar = 10

Now use the type() function to check the type of each variable:

type(foo)
type(bar)

It will say <class 'str'> for foo, and <class 'int'> for bar. This concept is important, because different types work together in a variety of ways, and they don’t always play nicely together.

For example, if you add together two strings they are combined:

name = "Harry"
job = "Wizard"
print("Yer a " + job + " " + name)

This prints the message “Yer a Wizard Harry”. The strings are concatenated (that’s a fancy programming term for ‘joined up’). Numbers, though, work completely differently. Let’s try a bit of maths:

number1 = 6
number2 = 9

print(number1 + number2)

Instead of concatenating 6 and 9 together to give 69, Python performs a bit of maths, and you get the answer ‘15’.

Type casting variables in Python

So what happens when you want to add a string and an integer together?

name = "Ben"
number = 10
print(name + number)

You’ll get an error message: ‘TypeError: Can’t convert 'int' object to str implicitly’. This error is because Python can’t add together a string and an integer, because they work differently. Ah, but not so fast! You can multiply strings and integers:

print(name * number)

It’ll print ‘Ben’ ten times: you’ll get ‘BenBenBenBenBenBenBenBenBenBen’.

If you want to print out ‘Ben10’, you’ll need to convert the integer to a string. You do this using a str() function and putting the integer inside the brackets. Here we do that, and store the result in a new variable called numberasstring:

number_as_string = str(number)
print(name + number_as_string)

This code will print out the name ‘Ben10’. This concept is known as ‘type casting’: converting a variable from one type to another.

Cast string into integers in Python

You can also cast strings into integers using the int() function.

This is particularly useful when you use input() to get a number from the user; the input is stored as a string. Let’s create a program that asks for a number and exponent and raises the number to the power of the exponent (using the ‘**’ symbol):

number = input("Enter a number: ")
exponent = input("Enter an exponent: ")
result = int(number) ** int(exponent)

Our first two variables, number and exponent, are strings, while our third, result, is an integer.

We could just print out the result:

print(result)

But if we wanted to include a message, we need to type cast result to a string:

print(number + " raised to the power
" + exponent + " is " + str(result))

Variables, types, and type casting can be a bit tricky at first. Python is a lot easier to use because it dynamically changes the type of a variable to match the thing you put in it. However, it does mean you have to be a bit careful.

From The MagPi store

Subscribe

Subscribe to the newsletter

Get every issue delivered directly to your inbox and keep up to date with the latest news, offers, events, and more.