Learning Management Platform for Written Tutorial Series.

Python 3 Variables - A beginners guide

Python 3 Variables - A beginners guide

Python Variables

A variable is a named memory location that is used to hold values. For examples name = 'Rodrick' defines a memory location named name that is assigned the value of Rodrick. We can then use this variable in our code to access the value Rodrick. In a nutshell that is what a variable is.

Topics to be covered

We will cover the following topics in this section.

  • How to declare variables in python
  • Python data types
  • Variable scope
  • Global variables

How to declare variables in python

Defining variables in python is very easy. We simply name the variable and assign a value to it. The declaration happens automatically at the time of assignment. The variable assumes the assigned data type as the variable type. For example, if you declare a variable name and assign the value Rodrick to it, then it will be of string type. if you assign the value 3 then it will be an int and if you assign the value 7.8 then it will be of float type and so on and so fourth.

Let's see this in action. Create a new file variables.py in our lessons folder.

Add the following code to it.

string_variable = "I'am"    # Evaluates to string based on value
int_variable    = 3         # Evaluates to int based on value
float_variable  = 0.45      # Evaluates to float based on value

print(f'The data type of string_variable is {type(string_variable)} and it has a value of [{string_variable}]')
print(f'The data type of int_variable is {type(int_variable)} and it has a value of [{int_variable}]')
print(f'The data type of float_variable is {type(float_variable)} and it has a value of [{float_variable}]')

HERE,

  • string_variable = "I'am" defines a variable named string_variable and assigns the value I'am to it.
  • int_variable = "I'am" defines a variable named int_variable and assigns the value 3 to it.
  • float_variable = "I'am" defines a variable named float_variableand assigns the value 0.45 to it.
  • print(f'The data type of string_variable is {type(string_variable)} and it has a value of [{string_variable}]') prints a formatted string in the terminal that describes the variable name, its data type once it has been declared and the value that was assigned to it. To get the data type of the variable, we used the built-in function type and passed in the parameter variable_name to the function.

Execute the above code and you should be able to get the following results.

The data type of string_variable is <class 'str'> and it has a value of [I'am]
The data type of int_variable is <class 'int'> and it has a value of [3]
The data type of float_variable is <class 'float'> and it has a value of [0.45]

Python Data Types

Python supports the following major data types.

  • Numbers - these are strictly numeric values such as 1, 1.3 etc.
  • Strings - these are alphanumeric in nature and can store a combination of numbers and other characters.
  • Lists - as the name suggests its a variable that contains a list of items that can be accessed using index numbers. Lists are defined using [] and their size and elements can be updated during the lifecycle of the list.
  • Tuples - these are similar to lists but they are defined using () and their size and values cannot be changed during the lifecycle of the variable.
  • Dictionary - these are variables can be used to store multiple values and each value is assigned a key and a value.

Let's now put this into action. We will start with numbers.

Numbers in python

Let's create a new file numbers.py

Let's take a look at strings. Create a new file strings.py

Add the following code

number = 2300
print(type(number))

number = 2300.00
print(type(number))

number = 2300j
print(type(number))

Executing the above code will produce the following results

<class 'int'>
<class 'float'>
<class 'complex'>

Strings in python

Python offers us three ways to declare strings. We can either use the single quotes, triple single quotes or double quotes. For simple strings, you can use either single or double quotes.

Let's put this into action.

Create a new file strings.py

Add the following code

first_variable = '"I am" a string'
second_variable = "'I am' a string"
third_variable = '''I 
am
a
string
'''

print(f'first variable [{first_variable}]\n')
print(f'second variable [{second_variable}]\n')
print(f'third variable [{third_variable}]\n')

HERE,

  • first_variable = '"I am" a string' declares a string that contains ". This is made possible because we are creating the string using single quotes so the double quotes don't cause an interpretation error.
  • second_variable = "'I am' a string" defines a string that contains ' quotes. This works because we are creating our string variable using double quotes.
  • third_variable = '''I am a string ''' The third variable uses triple single quotes to define our string that contains multiple lines. If you use a single or double quotes to do this then the above would produce a syntax error.

Executing the above code produces the following output.

first variable ["I am" a string]

second variable ['I am' a string]

third variable [I 
am
a
string
]

The variables that we create in python are actually objects that come with built-in functions.

Add the following code

zen = '"Stop trying to leave, and you will arrive." — Lao Tzu'

print(zen.upper())
print(zen.lower())
print(zen.title())
print(len(zen))

HERE,

  • zen = '"Stop trying to leave, and you will arrive." — Lao Tzu' defines a string variable zen that contains a quote.
  • print(zen.upper()); print(zen.lower()) calls the upper and lower built-in methods of the string object zen and prints the output in the terminal.
  • print(zen.title()) calls the title method that capitalizes each first letter of all the words in our title.
  • print(len(zen)) prints the length of the string using the len built-in function.

The above code will produce the following results.

"STOP TRYING TO LEAVE, AND YOU WILL ARRIVE." — LAO TZU
"stop trying to leave, and you will arrive." — lao tzu

Let's say that we want to get the first 5 characters of our code and display it, we can do something like this.

print(zen[0:5])

The above code produces the following results

"Stop

How it works*

  • Our string is like an array and each character is assigned an index number. The code zen[0:5] extracts characters starting from the left going 5 characters to the right. if we modify the code to zen[1:5] then the first character will be skipped.

Let's explore more methods of the string object. Suppose we want to know if our string contains a certain phrase, how can we go about it? We can do it like this?

print("Stop" in zen)

HERE,

  • the in operator checks to see if our phrase Stop is contained in zen variable. If the answer is yes then True is returned else False is returned.

Let's explore one more string example. Suppose we want to find the position of a character in our zen variable, we can do it like so.

print(zen.find('v'))

 

The above code produces 19. This is because the letter v first appears on position 19.

You can explore more methods that are available in the string object as a lesson challenge.

Python Lists

Create a new file lists.py

Add the following code

cars = ['Toyota','BMW','Benz','Ford']

print(cars)

for car in cars: 
    print(car) 

HERE,

  • cars = ['Toyota','BMW','Benz','Ford'] - defines a list variable called cars. We know its a list because we are defining it using angle brackets []
  • print(cars) prints all the values in the list
  • for car in cars: loops through all the items in the list and assigns to the variable car which we then print out using print(car.

Executing the above code produces the following results.

['Toyota', 'BMW', 'Benz', 'Ford']
Toyota
BMW
Benz
Ford

Python Tuples

Create a new file tuples.py

Add the following code

genres = ('Heavy Metal','R&B','Reggae','Afro Beats')

print(genres[1])

HERE,

  • genres = ('Heavy Metal','R&B','Reggae','Afro Beats') defines a tuple variable with items 'Heavy Metal','R&B','Reggae','Afro Beats'.
  • print(genres[1]) gets the item at index 1 and prints the value in the terminal.

The above code produces the following output

R&B

Python Dictionary

Create a new file dictionary.py

Add the following code

customer = {
    "name":"Rodrick Kazembe",
    "gender":"Male",
    "occupation":"programmer"
}

print(f'The customer name is {customer["name"]}')

HERE,

  • defines a dictionary variable customer that has three (3) keys namely name,gender and occupation.
  • print(f'The customer name is {customer["name"]}') prints the value of the key named name which in our case is the value Rodrick

Summary

Let's wrap up on what we have learnt in this lesson.

  • Variables in python are declared the moment that a value is assigned to a variable and the data type is determined by the nature of the value that has been passed in.
  • Python supports five (5) major data types namely numbers, strings, lists, tuples and dictionaries.
  • Numbers are strictly numeric in nature
  • Strings are alphanumeric in nature
  • Lists contain a number of items, are defined using angle brackets [...] and they are mutable which means the items can be changed or removed.
  • Tuples are similar to lists, are defined using parenthesis (...) and they are immutable which means once defined you cannot add, subtract or change anything. In short they are readonly.
  • Dictionary types are like lists but they use explicit key names that are paired to values.

What next?

In the next tutorial, we will look at numbers in more details and explore some of the functions that are built-in into python. If you enjoyed this lesson then show us your appreciation by creating a free accounts.


...