Lesson 4. Variables

Variables in Python are fun.

Variables are data in programs that either change on the fly or are used to represent some value that you set once, and then use the variable in your code in place of that value.

Clearly variables are what make your program work.

Python is a strong and dynamically typed language. That is computer science talk for a language where the data types of variables do not change without explicit conversion (strongly typed), and that data type is decided at runtime (dynamically typed).

That is all well and good, but what all that really means is that you do not have to specify a data type for a variable when you declare it.

However, you do have to assign a variable a value when you create one. That initial variable definition is what decides the data type of the variable.


Simple Variable Declaration

cookies = 'nom nom nom'


Using A Variable To Simplify Code

It is often the case that variables hold values that can be a bit unwieldy like file paths or URLs. In this case, we create a variable and assign it the unwieldy value so later in our code, we can use the simpler representation of the value.

import os

script_dir = os.getcwd()
rel_path = "data\\Eurostat.zip"
abs_file_path = os.path.join(script_dir, rel_path)


Changing The Value Of A Variable

Here is an example of changing the value of a variable.

i = 1

i = i + 1


Now you try it!

Don't copy and past. Type the code yourself!

Last updated