In this tutorial you will learn about Python variables. So far you used constant numbers or literal numbers.

>>> print(3.3)
3.3

This is fine for small calculations, but for programs you’ll need variables.

Related Course: Complete Python Programming Course & Exercises

Variable assignment

You can think of a variable as a name with a value attached. To create a variable, just assign a value.

To do assignment, use the equal sign (=).

x = 3

You can read this as ‘x is assigned the value 3’. Once assigned, the variable can be used anywhere in the program.

print(x)

If you use the REPL shell, it will output the value directly.

>>> x
3

You can change the value of x anywhere in the program.

x = 4

Then if you want to use x again, you’ll see the value has changed.

print(x)
4

python variable

Related Course: Complete Python Programming Course & Exercises

Variable Types in Python

Python doesn’t require the type of variable to be defined in advance, this is called statically typed.

In Python, you can just assign a value and Python figures out the type. They can also be redefined.

>>> y = "hello"
>>> print(y)
'hello'

>>> # redefine y
>>> y = 2
>>> print(y)

The type changed here, let’s see that again.

You can get the type by calling the function type().

>>> y = "hello"
>>> type(y)
<class 'str'>
>>>
>>> y = 3
>>> type(y)
<class 'int'>
>>>

In this example, the variable changed from type str (string) to the type int (integer).

  • A string type is any text content, from single character to paragraph.
  • An integer type is any whole number (1,2,3…)

Python figures out the type on it’s own.

>>> x = 3
>>> price = 5.50
>>> word = "hello"

In the example above, we have three variables: x, price and word.

You can get the type that belongs to each variable by calling type():

>>> type(x)
<class 'int'>
>>> type(price)
<class 'float'>
>>> type(word)
<class 'str'>
>>>

The new type you see here is float, that is any real number (1.333, 2.6)

Related Course: Complete Python Programming Course & Exercises

Variable names

The variable we used before are short (x,y,price,word).
That’s okay, but variable names can be any length and have uppercase, lowercase letters, underscore and digits.

But, variable names may not contain spaces or special characters ([email protected]#$%^&*)

For example, these are valid variable names:

>>> name = "Alice"
>>> age = 21
>>> livesInWashington = True
>>> print(name, age, livesInWashington)
Alice 21 True
>>>

But this is not:

>>> 21_Alice = "Alice"
^
SyntaxError: invalid token

That’s because a variable name cannot start with a digit.

In Python variable names are case sensitive, so these are not the same variable:

>>> name = "Alice"
>>> Name = "Bob"
>>> NAME = "Warren"
>>> print(name, Name, NAME)
Alice Bob Warren
>>>

That’s technically fine, but this can get very confusing. Explicit variable naming is better than implicit. For example,

>>> Name = "Alice"
>>> NameOfFriend = "Bob"
>>> NameOfDad = "Warren"

In this example camel casing is used, because a space is not allowed in a variable name. In camel casing style, each word starts with an uppercase letter.

However, camel case is not the only naming convention. The example below shows different styles:

>>> # camel case
>>> MyName = "Alice"

>>> # snake case
>>> my_name = "alice"

>>> # pascal case
>>> myName = "Alice"

Pascal case is similar to camel case, with the difference that the first letter is lower case.

Any of these naming styles is fine, it’s a matter of personal preference or company policy. Camel case is the most popular style, as it’s often used in Java and C++.

Reserved words

Python has reserved words, those can not be used as variable names. There is a total of 33 reserved words.

If you type help("keywords") it shows you all words you can’t use as variable names.

>>> help("keywords")

Here is a list of the Python keywords. Enter any keyword to get more help.

False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not

>>>

String variables

You have already seen the string type. If a variable is of the string type, it contains text.
There are 3 ways to define a variable of the string type:

word = 'Hello world'
word = "Hello world"
word = '''Hello world'''

Any of these are OK, but the double quote (“) is te most common.

Operators

After assignment of variables, you can use them throughout your program. But you can also replace or modify their contents.

The program below assigns variable x, then modifies it and finally replaces its value.

x = 2

# increase x by one
x = x + 1

# replace x
x = 5

Python supports the operators plus +, minus -, divide / and multiplication * as well as brackets.

python variable

Formatted strings

Variables may be shown on the screen using the print() function. The first output of the program above is simply the raw value of the variables.

x = 5
print(x)

y = 3 * x
print(y)

To output more details, you can use formatted strings.

To create a formatted string, put f in front of the string. By using brackets {} you can print variables along with text.

# more detailed output
print(f"x = {x}")
print(f"y = {y}")

python variable formatted string

The screenshot shows the output of both default strings and formatted strings.

If you are a Python beginner, then I highly recommend this book.

Download exercises