Skip main navigation

Python Variables

Python variables are simply containers for storing data values. Unlike other languages, such as Java, Python has no command for declaring a variable, so you create one the moment you first assign a value to it.

Python variables are simply containers for storing data values. Unlike other languages, such as Java, Python has no command for declaring a variable, so you create one the moment you first assign a value to it.

First, let’s define a variable. A variable is a placeholder for information you want Python to recall later in the coding process when you need to complete an action. Technically, the variable acts as an address for where the data is stored in memory. A Python variable may be assigned a value of one type and then later re-assigned a value of a different type. For example, x = "apples" can later be x = 5.

 

Variables in programming are similar to variables that you might have encountered while learning algebra. Like in an algebraic equation, variables allow you to write programs that process information without having all the values up front. Unlike algebraic variables, however, programming variables can represent a much wider variety of information.

Python data types

Let’s explore some detailed examples of the different data types you can find in Python. Remember to practise your coding skills by writing and running the examples in PyCharm.

 

Strings

 

String is a text data type. Python has powerful and flexible built-in string (str) processing capabilities. The value of a str object is a sequence of characters. You can delimit string values with either single quotes (' ') or double quotes (" "). All the characters between the opening and closing delimiter are part of the string.

 

Try these examples in PyCharm:

 

Code:

 

sentence = 'This is a string in single quotes' 
print(sentence)

 

Output:

 

This is a string in single quotes 

 

Code:

 

sentence = "This is a string in double quotes" 
print(sentence)

 

Output:

 

This is a string in double quotes 

 

For multi-line strings with line breaks, you can use triple quotes. Try these examples:

 

Code:

 

str_a = """This is a multiline string 
Line 1 added 
Line 2 added 
Line 3 added
"""
print(str_a)

 

Output:

 

This is a multiline string 
Line 1 added 
Line 2 added 
Line 3 added 

 

Code:

 

str_b = '''This is a multiline string using triple quote notation with single quote 
Line 1 added 
Line 2 added 
Let's close this string
'''
print(str_b)

 

Output:

 

This is a multi-line string using triple quote notation with single quote 
Line 1 added 
Line 2 added 
Let's close this string 

 

You can also print selected characters from a string. Try this code example:

 

a = "This is a longer string" 
print(a[1], a[2], a[10])

 

Output:

 

h i l 

 

You printed the characters at index 1, index 2, and index 10. Note that the index count starts at 0. That is, in ‘This’, index 0 is ‘T’.

 

Python strings are immutable; that is, you cannot modify a string without creating a new string variable, or assigning a completely new string value to the variable.

 

Use this variable from a previous example in PyCharm:

 

print(str_b)

 

Output:

 

This is a multi-line string using triple quote notation with single quote 
Line 1 added 
Line 2 added 
Let's close this string 

 

Now try to modify the string in the previous example:

 

#Let's try to modify str_b now, it will give a runtime error
str_b[10]='S'

 

Output:

 

Traceback (most recent call last): 
File "<stdin>", line 2, in <module> 
TypeError: 'str' object does not support item assignment 

 

As you can see, you will get an error message when you attempt to modify a string; in this case, by changing a single character.

 

Concatenating strings

 

Concatenation means to combine two or more strings. Once you assign string values to the new variables, you can join them. To explore this concept further, follow the code:

 

first_name = 'Jane'
last_name = 'Doe'
print(first_name + last_name)

 

Output:

 

JaneDoe

 

Now, let’s adjust so that there is a space between first_name and last_name when they are concatenated:

 

first_name = 'Jane'
last_name = 'Doe'
print(first_name + ' ' + last_name)

 

Output:

 

Jane Doe

 

You had to add an empty space within quotation marks, since there was neither a space at the end of the first_name variable nor at the beginning of the last_name variable.

 

You will examine more examples related to this while learning about if/else statements later in the module.

 

Numeric types

 

Integers (int) and floats (float) are numeric types, which means they hold numbers. You can perform mathematical operations with them. The Python interpreter can then evaluate these expressions to produce numeric values.

 

You can use the type() function to return the type of a value of variable. Try this code example:

 

print(type(987653))

 

Output:

 

<class 'int'>

 

Floating Point Numbers

 

Floating point numbers (numbers containing a decimal point) are represented with the Python float type.

 

Try this example:

 

fval = 10.54
print(fval)

 

Output:

 

10.54 

 

You can also assign values to float type using scientific notations, which is useful when working with very large numbers. Try this example:

 

fval2 = 5.64e-5
print(fval2)

 

Output:

 

5.64e-05

 

In Python 3, which is the version you’re using, dividing an integer with a result that is not a whole number will always yield a floating-point number.

 

Try these examples to see for yourself:

 

Code:

 

print(4/3)

 

Output:

 

1.3333333333333333

 

Code:

 

print(type(4/3))

 

Output:

 

<class 'float'>

 

Python Booleans

 

Most objects in Python have a characteristic of True or False. Python also provides a boolean data type. Objects of this data type may have one of two values: True or False. The most common (and simplest) example of Booleans is a filter where all the records that meet a condition (True) are returned, like when using Microsoft Excel and you filter for a specific value in a field.

 

Try these code examples for yourself:

 

is_true = True
is_false= False
print(is_true, is_false) 

 

Output:

 

True False

 

Using Booleans with ‘and’ and ‘or’ keywords

 

Code:

 

is_true = True
is_false= False
print(is_true and is_false) 
print(is_true or is_false)

 

Output:

 

False
True

 

In these examples, you can see that if one of the variables is False with an and keyword, the overall result is False. In contrast, if either variable is True with an or keyword, the overall result is True. For example, if you had three brown cats and one black cat and your logic was ‘Are the cats brown?’, this would be True for three of the cats, but False for the black cat. If your logic was ‘Are there cats that are brown and black?’ this would return as False as there are no cats that are both black and brown. If your logic was ‘Are there cats that are brown or black?’ this would return as True for all four cats.

Try changing the initial values in previous examples and see how the outputs changes.

This article is from the free online

Introduction to Programming with Python

Created by
FutureLearn - Learning For Life

Our purpose is to transform access to education.

We offer a diverse selection of courses from leading universities and cultural institutions from around the world. These are delivered one step at a time, and are accessible on mobile, tablet and desktop, so you can fit learning around your life.

We believe learning should be an enjoyable, social experience, so our courses offer the opportunity to discuss what you’re learning with others as you go, helping you make fresh discoveries and form new ideas.
You can unlock new opportunities with unlimited access to hundreds of online short courses for a year by subscribing to our Unlimited package. Build your knowledge with top universities and organisations.

Learn more about how FutureLearn is transforming access to education