2. Variables#

A variable is a container for storing values. Each variable has a name, a value, and a data type.

2.1. Declaration and Usage#

In python creating (declaring) a variable is very simply: you simply state its name, e.g. age, and assign it the value you want, e.g. 25, by using an equal sign = : age = 25. You do not need to explicitly declare the type — you simply assign a value, and Python determines the type automatically.

To access the value that is stored in the variable, just state the name of the variable. So for example if you write print(age) it will output 25.

You can change (reassign) the values of the variables at any time. Simply assign a new value to the name the same way the variable was declared.

# Create information about a patient by assigning values to variables
age = 25
name = "Alice"
height = 5.7
vegetarian = True

# Printing the values of the variables
print('Patient Information:')

print("Age:", age)
print("Name:", name)
print("Height:", height)
print("Vegetarian:", vegetarian)

# Update patient information after a year
age = 26
vegetarian = False

#printing the updated values
print()#create empty line for better readability

print('Updated Patient Information:')

print("Age:", age)
print("Name:", name)
print("Height:", height)
print("Vegetarian:", vegetarian)
Patient Information:
Age: 25
Name: Alice
Height: 5.7
Vegetarian: True

Updated Patient Information:
Age: 26
Name: Alice
Height: 5.7
Vegetarian: False

2.2. Variable names#

Variable names must start with a letter or an underscore (_) and cannot contain spaces or special punctuation (other than underscores). Python is case-sensitive. This means that myVariable and myvariable would be treated as two different names / variables.

It is good practice to stick to one consistent naming style. In Python, the most common style is snake_case, where words are separated by underscores, for example: my_variable. A different style that is often used and you might come across is camelCase, where words are not separated and each word but the first is capitalised: myVariable.

The same way comments are useful for understanding your code, you should also give your variables informative names about what they store/ what their purpose is. For instance, someone seeing the variables variable_one and variable_two will be a lot more confused about what they are used for than someone seeing patients_age and patients_height.

2.3. Data Types#

Here are some of the most common built-in data types in Python:

  1. Integer: Numeric type - Whole numbers, e.g., 42, -3.

  2. Float: Numeric type - Numbers with a decimal point, e.g., 3.14, -0.001.

  3. String: Text type - Sequences of characters, written inside quotes, e.g., "Hello, Python!".

  4. Boolean: Boolean type - Values representing True or False.

  5. NoneType: None type - Represented by None, means “no value” or “nothing here yet”.

  6. List: Sequence type - A list of various values where each value can have any data type, e.g. [3,'Hi',True]

Data types define what one can do with a variable, e.g. how you can manipulate them and what functions you can use on them. For instance, while you could multiply two integer variables, i.e. variables which values have the data type integer, you would get a type error if you tried the same with two string variables.

If you do not know what type your variable has, you can simply use the function type() with the variable name being the argument (what you write inside the brackets) and its type being the output (the value you would get back from the function which you can print directly or save to a new variable).

Over the next few chapters you will get introduced in more detail to each of these Data types (and other ones) and how you can manipulate them / work with them. We will start in the next chapter with Numeric types (integer, float) before moving on to strings and more complex types such as sequence types.

# Integers, floats, strings, booleans, and None
my_int = 10
my_float = 3.14
my_str = "Python"
my_bool = True
my_none = None

#Identifying the types of the variables
print(type(my_int)) # <class 'int'>
print(type(my_float)) # <class 'float'>
print(type(my_str)) # <class 'str'>
print(type(my_bool)) # <class 'bool'>
print(type(my_none)) # <class 'NoneType'>

#save the type of a variable in another variable
my_int_type = type(my_int)
print('Type of my_int:', my_int_type) # <class 'int'>

# Try manipulating the variables with different types
print('Multiplying my_int with it self:', my_int * my_int) # 100
print('Multiplying my_str with it self:', my_str * my_str) # Error    
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'NoneType'>
Type of my_int: <class 'int'>
Multiplying my_int with it self: 100
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[2], line 21
     19 # Try manipulating the variables with different types
     20 print('Multiplying my_int with it self:', my_int * my_int) # 100
---> 21 print('Multiplying my_str with it self:', my_str * my_str) # Error    

TypeError: can't multiply sequence by non-int of type 'str'

2.4. Quick Practice#

Try these simple challenges:

  • Create a variable called city and assign your favourite city name as a string.

  • Create a variable called temperature and assign a decimal number (float).

  • Create a variable called is_raining and assign either True or False.

  • Print the values and types of all your variables using the print() function!

  • Reassign the value of temperature and reprint it

# Put your code here
💡 Solution
#Defining our variables
city = "Edinburgh"
temperature = 18.5
is_raining = True

#Print their values and types
print("City value:", city, "City type:", type(city))
print("Temperature value:", temperature, "Temperature type:", type(temperature))
print("Is it raining?", is_raining, "Is_raining type:", type(is_raining))

#Change the temperature value
temperature = 15.25

print("New Temperature value:", temperature)