Variables and data types in Python
Coding with Python
🕑 This lesson will take about 30 minutes
In the last lesson, you learned how to work with numbers and use basic mathematical expressions in Python. In this lesson, you will learn how to create and use variables. Variables are used to store and manage data in a program. Each variable that a programmer creates is given a unique name, which allows the programmer to reference and manipulate the stored data using the variable name. Variables can be quite useful for storing the results of a calculation (such as an integer or float) to use later in a program, but they can also store data of other types, such as strings (text) or booleans (True or False values).
Variables are used all the time in Python and if you have done any coding before, then you may already be familiar with variables. To create a variable, you first need to give the variable a name and then assign it a value to store (this value can then be changed later in the code if needed - that’s why they’re called variables because their value can vary).
For example, a variable might be called year and the value it stores might be 2024. A variable is unique; therefore it must be given a unique name, for example, age, year, username, firstname, lastname, score, email_address. A variableʼs name cannot contain any spaces, symbols (apart from underscores) or begin with a number.
Variable names are also case-sensitive (for example, dateOfBirth and dateofbirth would be treated as two separate variables). Variables also can’t be given the same name as an existing Python function (for example, the word print is already reserved for a function in the Python language, so you can’t use print for a variable’s name). If your variableʼs name has multiple words, you can use an underscore character between words instead of spaces (eg. date_of_birth) or you can use camel case where each new word starts with an uppercase letter (eg. dateOfBirth).
Creating variables
To create a variable and assign it a value, type in the desired name of the variable, followed by an equals (=) sign (also known as the assignment operator), followed by the value (remember, string values must be contained between quotation marks). Check out the example code below.
Sample code
Python is a dynamically typed programming language, meaning you don't need to explicitly specify the data type of a variable (unlike statically typed variables used in other programming languages where the data type must be specified when the variable is created). The interpreter (the program that executes the Python code) determines the data type of a variable based on the value that has been assigned to it.
Data types
Common data types include
integers (whole numbers eg. 3)
float (numbers with a decimal point eg. 3.5)
string (sequence of characters such as letters, punctuation, numbers eg. "120 Pitt Street, Sydney")
boolean (a value that is either True or False)
String values must be contained between quotation marks. A string is a sequence of characters. A string value may be some simple text such as someoneʼs name, an email address, a suburb, etc, or it could also contain symbols or numbers. If you have numeric values in a string value, they will not be treated as numbers but just as ordinary text (eg. 5 would be treated as a number whereas "5" would be treated as text). If you want to create variables that are going to store numbers or mathematical expressions that will be used for arithmetic, they must be in integer or float form, not a string. In the example above, numbers such as year or pi do not have quotation marks around them – they will be treated as numbers, not as strings.
Once a variable has been created, it can be used again anywhere in the program. You could modify the contents of the variable or replace its value with a new value, check the variable’s value, compare its value to another value, or use the variable in a function such as the print() function to output/display its contents.
Check out the example code below. A variable called year is created and initially given the value 2024. In the second line of code, the value is increased by 1 so the variable is now storing the value 2025, which is outputted using the print() function on line 3. Remember, variables be given a value to store (either at the time the variable is created or later in the code) or an expression (eg. 5 + 3) that will be executed and then the result of that expression will be stored.
Sample code
Concatenation
Concatenation is the process of combining two or more strings. The + operator is used to concatenate (join) strings. Here's an example:
In the example above, the variables first_name and last_name are concatenated with a space in between using the + operator. The result is stored in the variable called full_name, and then displayed using the print() function.
You can concatenate string values or variables containing string values as well as concatenating strings with other values such as integers or floats. Concatenation can be performed in a variable assignment or in a function such as the print() function. Here are some examples:
first_name = "Homer"
last_name = "Simpson"
print(first_name + " " + last_name)username = "joe"
print("Welcome back, " + username)
Keep in mind that when concatenating variables that are not strings, you may need to convert those values to strings first using the str() function (otherwise you might encounter a TypeError). Here is an example:
In this sample code above, str(score) converts the integer variable score to a string before concatenating it with the rest of the message.
f-strings in Python
F-strings (also known as formatted string literals) are a feature introduced in Python 3.6 that provides a convenient and neat way of embedding expressions inside strings. F-strings are created by prefixing a string with the letter f. Expressions can then be placed inside curly braces {} within the f-string. These expressions are evaluated, and their values are inserted into the string. F-strings can support variables, literals (data types that can hold any value type, such as strings, numbers, and. more) and expressions. This makes the code easy to write and results in clean, readable and concise string representations. Check out the example below.
In the f-string example above, the f character is placed just before the string value inside the print() function. However, this can also be done in variables which can then be outputted using the print() function or used in another function later in the code. In the example below, the variable message contains an f-string and its value is later displayed using the print() function.
As mentioned earlier, expressions (such as arithmetic) can also be placed in f-strings. The expression will be evaluated and the result will be placed in the string. Check out the example below, where some basic addition is performed and the result is placed in the f-string.
Advanced formatting with f-strings
F-strings can also include format specifiers for more advanced formatting. For example, in the sample code below, :.2f is a format specifier that specifies the number of decimal places to display the floating-point value of pi.
User input
Variables also dont just have to store data values assigned by the programmer but can have a value assigned by a user of the program. Input from the user could come from textbox in a form, or from an option they select on screen, or the result of actions they take (eg. in a game). In this example, we will just look at text-based input gathered from the user using the input() function.
In the example code below, the variable username is given the value of the users input (what the user types in using their keyboard). The input() function will take input from the user and the value they enter will be stored in the username variable. The specified message “What is your username? ” is displayed. The user can then type their username into the terminal and press the Return/Enter key. The value that the user typed in is now the value assigned to the username variable.
It’s important to know that the input() function takes a value entered by the user and represents it as a string. This means that if you want to get numeric input from the user (eg. an integer) and use that value in an expression (eg. an arithmetic expression), then you will need to convert the input value to a number. In the example code below, the user enters a number and the program displays the square root of that number. The user’s input stored in the variable number is converted to an integer using the int() function before calculating the square root. Without using the int() function, you would receive a TypeError.
Some things to remember about variables…
Think carefully about the names of your variables. They should be easy to remember and appropriate for the information stored in that variable. Be consistent with the way you name your variables (eg. using underscores, camel-case, uppercase or lowercase letters). Variables that are given clear, meaningful names contribute to code that is more readable and easier to test, debug and maintain.
Multiple assignment
Python allows you to assign a value to multiple variables at once. In this example, the variables, a, b, and c will all be assigned the value 1.
a = b = c = 1
In this example, the variable a will be assigned the value 1, the variable b will be assigned the value "cat", and the variable c will be assigned the value True.
a,b,c = 1, "cat", True
Here is the full sample code…
Next lesson: Modules and functions