Python Variables PT. 1

Variables Part 1

A variable is an object that holds information for later use. Variables in Python are not strongly typed, meaning you do not need to explicitly define a variable with the type, only a name, and its value. As an example, if I wanted an integer called var1 with a value of 7, I would use var1 = 7. In this lesson, we are going to cover integers (int), strings (str), and lists.

An Integer is just a number. Integers can be whole numbers, decimals (called floats), and either positive or negative. The next lesson will cover floats in more detail. For now, understand that an integer is often referred to as an int and can have any attributes just described.

A string is a letter or collection of letters, spaces, and special characters. In Python, there are no ‘char’ variables that are common in languages like C++, C#, Java, and other languages. If you are storing a single letter, Python still classifies that letter as a string.

Lists are a collection of values, variables, and other structures. Lists in Python can be as simple or as complicated as you want. Lists are like buckets of data that let you stack other buckets in them. You can mix types together in the same lists; meaning a list can contain any arrangement of strings, integers, and lists. For the purposes of this lesson, we will keep it simple with ints and strings. 

Each element in a list is assigned a position number starting from 0 and ending with the length of the array minus 1. You will sometimes see this referred to as 0->x-1. Most languages follow this rule. If you want to display the first item in a list called lList1, you would use lList1[0]. We will cover more of this in the I/O section.

Putting it together

As a reminder, anything behind a # symbol is seen as a comment and will not be interpreted in Python. We use comments to better explain code samples while still allowing you to copy, paste, and run code. A good coding practice is to prefix your variables with something to remind you of what type of variable it is. For this demonstration, I use i for int, s for string, and l for list.

iVar1 = 7 #This is an int
sVar2 = "I am a string" #This is a string
lVar3 = ["item 1",7,"Item 3"] #This is a list with strings and an int

Leave a Comment