Variables

Doing computation on the fly is fun and all, but suppose you want to actually store the results of a computation. This is what variables are for.

A variable is like a box where you can store numbers, strings and the other complex objects we'll learn to use going on with this tutorial.

In Python, variable names have to start with a letter (upper-case or lower-case) or an underscore and can only be made up of letters (upper-case or lower-case), underscores and digits. For example, the following are all valid variable names:

  • username
  • _password
  • article_content
  • menu_2
  • theGreatestVariableEver

This, on the contrary, are not valid names

  • is-ok? (contains a dash and a question mark)
  • 2values (doesn't begin with an underscore or a letter)

To start using a variable, you simply assign a value to it. To do so, you write the variable name, followed by an equal sign (=) and the value (or expression) you want to assign it.

>>> x = 42
>>> sum = 30 + 5

To check what's inside a variable while using the interactive interpreter, you just write the variable name and press enter.

>>> x
42
>>> sum
35

You can use variables inside expressions.

>>> sum_minus_x = sum - x
>>> sum_minus_x
-7

And you can, of course, print variables with the print function.

>>> print(sum)
35

It's a good moment to teach you about the input function. What it does is ask the user for a string and return it. Suppose, for example, you need to ask the name to the user to greet them. How would we do this?

>>> name = input("What's your name? ")
What's your name? Jane
>>> print("Hello " + name)
Hello Jane

Here the bold text is what the user entered.

There's some new stuff going on with that last snippet. Let's break it down a bit.

First of all, the input function accepts a parameter, that will be what the user will see when asked for input. In this case, we're asking for their name. Notice the white space after the question mark. If you don't put it there, the user will start typing just after the question mark, which is not nice to see.

We then want to assign the result returned by the input function (i.e. what the user typed) to the name variable. Please note that input stops reading as soon as the user presses enter but doesn't care about spaces.

Once the user presses enter, we print "Hello " followed by the name the user wrote. Notice that, when handling strings, the plus sign (+) means "give me the concatenation of these two strings". This is not the best way to compose strings to show the user. We will cover the best way to do this in another tutorial.

Let's do something else. Let's ask the user for two numbers and sum them.

>>> a = input("Write the first number: ")
Write the first number: 10
>>> b = input("Write the second number: ")
Write the second number: 23
>>> sum = a + b                             
>>> print ("Their sum is " + sum)
Their sum is 1023

Wait, what? Oh, we forgot to tell you that the input function returns strings!

There's a difference between a string and a number. The string "42" is not the same as the number 42. It's really the '4' character followed by the '2' character. The Python interpreter doesn't know what's inside a string, so it treats it exactly how it would have treated the strings "Hello" and "World", so the plus sign just concatenates them.

But don't worry, there's a function for that. It's called int. The int function takes a string as a parameter and converts it to a number.

>>> int("42")
42

Notice there are no quotes on the result. So let's amend our previous example.

>>> a = input("Write the first number: ")
Write the first number: 10
>>> b = input("Write the second number: ")
Write the second number: 23
>>> sum = int(a) + int(b)
>>> print ("Their sum is " + sum)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly

Don't worry if you don't understand what the interpreter is telling you here. We'll learn how to recognize and handle this kind of situations when we'll talk about exceptions in the next tutorial.

What's wrong this time? Well, the problem is that we can concatenate a string ("Their sum is ") and an integer. So, as we converted a string to an integer, we shall convert an integer back to a string. The function we need is called str, which takes a value and converts it to a string.

>>> a = input("Write the first number: ")
Write the first number: 10
>>> b = input("Write the second number: ")
Write the second number: 23
>>> sum = int(a) + int(b)
>>> print ("Their sum is " + str(sum))
Their sum is 33

That's more like it.

You may be wondering what happens if you pass int a string that can't be converted to a number.

>>> int("banana")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'banana'

Well, for now let's just say the interpreter didn't like it one bit. As previously stated, this will be discussed further in this series.

Document Tags and Contributors

 Contributors to this page: chrisdavidmills, klez
 Last updated by: chrisdavidmills,