Python How to Basics Pt 2

Python PictureWelcome to Part 2 of the Python How to Program series. I’m going to mainly focus on variable types specific to Python in this article. I also will go over many basic topics that make Python different than any other programming langauge.

How Python Handles White Space

If you have programmed in other languages, you are probably used to enclosing your code between brackets { }. Python instead separates it’s code segments through the use of white space. So if you where creating a function in Python you would indent all of the code that lies in that function (normally 4 spaces).

Now you don’t have to indent 4 spaces, but you must always indent using the same number of spaces, or the interpreter will throw an error. Here is an example program, in which I demonstrate the use of white space for the function called main:

#Messing around with whitespace in Python
”’ This is a multiple line
comment, for when you get kind of wordy ”’

def main():

print(“Your in the main function”)
print(“You are leaving the main function”)

if __name__ == “__main__”: main()

What Does this Program Do

If you didn’t read the previous tutorial Python How to Program Tutorial, you should probably check it out before moving on. I’ll explain every line above either way:


  • I’m assuming you will always run your Python code in a Linux, Unix, or Mac OS X terminal
  • The default location of the Python interpreter is /usr/bin/python3
  • This code tells the terminal that this code can be interpreted by the interpreter that resides at the address given

#Messing around with whitespace in Python

  • You can make a single line comment in Python by starting the comment with a hash mark #
  • You make a multiple line comment in Python with a triple quote ”’
  • It is very important for you to heavily comment your code

def main():

print(“Your in the main function”)
print(“You are leaving the main function”)

Here I’m defining a function named main. Unlike many languages, the main function holds no significance like in other languages. You define it in the same ways you create any other function. It is however common for programmers to organize a programs functionality in a function named main.

The braces () signify where you would assign variables to specific variable names, if any where passed. None are expected in this program, and I’ll talk more about functions in a future article. You then signify the beginning of the function with a colon : .

As I explained previously, every line there after that is indented, is considered to be part of function main. The print function as well will print to the screen any characters enclosed in both the braces and quotes.

Special Note: You may also have noticed that statements don’t end with a semi colon, like in most other programming languages.

How a Python Script is Processed

When a Python script is executed by the interpreter, it skips over all of the functions that are defined and goes directly to the first statement that is not indented and not a function definition. In this case it goes to the line of code here:

if __name__ == “__main__”: main()

  • This line of code tells the interpreter to run the function named main
  • Every Python module is assigned a value to a variable named __name__
  • If a program is being run on its own it is assigned the value of __main__
  • So, this line of code is saying, if this program is being run on its own then execute the function named main


Wrapping Up the Basics

Those are some of the basic differences between Python and other languages. Now I’ll get into the data types that are available in Python. Before we start I’d like to explain some jargon you may here about data types in Python.

What Does Mutable and Immutable Mean

These are big strange words that aren’t very complicated. When ever you create a variable of a specific data type in Python, it is either Mutable or Immutable. These words define how the data is stored in memory. When you assign a new value to an Immutable variable, that new value is stored in a different location in memory.

Beginning Python programmers often are confused into thinking that if a variable is Immutable that it can’t be changed. While this is technically true, in reference to how data is stored in memory, it isn’t true that you can’t assign a new value to a Immutable variable. Ex. It is completely legal to assign a new value to an integer named age, even if it had a value already.

Naming Rules for Variables

When you are naming variables in Python, follow these rules:

  • The name must begin with a letter or underscore _
  • Each character, there after, must be a letter, number or underscore _
  • Python is case sensitive (Age is not the same as age)
  • You can’t name your variables certain words that are already used in the Python language (Keywords)
  • Don’t start your variable names with two underscores __ (Not a rule, but will help eliminate errors)

The Protected Python Keywords

You cannot name your variables any of these names:

and, continue, except, global, lambda, pass, while, as, def, False, if, None, raise, with, assert, del, finally, import, nonlocal, return, yield, break, elif, for, in, not, True, class, else, from, is, or, try

Boolean Data Type

An Integer is just a number with no decimal point. There are two types of integers in Python. The integer (int) and boolean (bool). Here I’ll go over boolean variables first.

You can assign True or False to a bool. If you assign any other number to a bool, it will automatically become of whatever type that number would be. Here is some code: (type(), will tell you the data type of the variable it is passed)

a = True # a is considered a boolean type now
b = 1 # b is considered to be of type integer
print(type(a), type(b)) # The output would be, <class ‘bool’> <class ‘int’>
a = 0 # After this assignment, a is now considered to be an integer
print(type(a)) # The output would be, <class ‘int’>

You can compare boolean types with the and and or operators.

a = True

b = False

print( a and b ) # The output would be False

print ( a or b ) # The output would be True

You could also compare boolean’s with the following operator’s, which I’ll cover later: <, >, <=, >=, etc.

The Integer Type

Integers in Python can be as big as the computers memory allows. You define variables in Python based off of the value assigned. Hence with, a = 1, a becomes an integer by default. An integer could be assigned in decimal, binary, octal or hexadecimal. So as not to confuse some people, I’ll skip over this topic. It probably won’t be of interest to 95% of people reading this.

Floating Point Type

A floating point number, is just a number with a decimal value. There are 3 types of floats in Python: float, complex, and decimal. I’ll skip over complex types, since they also will be of little interest to most people.

If you assign a value to a variable, that contains a decimal, it will become of type float by default. The values assigned to a float will normally remain accurate up to 17 decimal places. This won’t be true on most machines however:

c = 1.234567891011121314
print(c) # The output on my computer is 1.23456789101 (Accuracy to 11 decimal places)

The Decimal Type

If you demand that your floating point number be more accurate than 11 spaces, define a decimal type. To use this special data type, you must import the decimal module, or library, by starting your Python program with the line import decimal. Here is how you load a value into a decimal variable

d = decimal.Decimal(“1.234567891011121314”)
print(d) # The output would be 1.234567891011121314

You must assign a decimal value by using the function decimal.Decimal(). The value inside of the brackets can be of type integer or string, but not float. After these values are assigned, you can treat them as if they were any other variable. For example:

d = decimal.Decimal(“1.234567891011121314”)
e = decimal.Decimal(“1.234567891011121314”)
print(d) # The output would be 1.234567891011121314
print(d + e) # The output would be 2.469135782022242628

The String Type

Strings contain a sequence of characters. You can assign a string value with single quotes ‘, double quotes “, or triple quotes “””. You would use the triple quotes when your string is multiple lines long. I also show another way to create multiple line strings below:

f = “””This is a multiple
line string”””
g = (“Another multiple” + ” ”
“line string”)

The Output

This is a multiple
line string
Another multiple line string

There are more ways to mess with strings, but I’ll leave that for another article.

What is a Tuple

A Tuple in Python, provides you with a way to collect multiple values in one variable. Tuples are immutable, meaning once they are created you cannot add additional values to them. You can however create an entirely new tuple and assign it to the same variable. Here is some example code:

h = (“Maine”, “Pennsylvania”, 1, 2.345)

The Output

(‘Maine’, ‘Pennsylvania’, 1, 2.345)

If you want to create a 1 item tuple, you must end that 1 item with a comma. If you don’t it will be considered a string. For example:

i = (“New York”,)

I’ll go over the many things you can do with Tuples in a future article.

What is a Python List

Lists are similar to Tuples except for the fact that they are mutable. This means you can add additional values to them after they are created. They are also created with brackets, as you can see here:

j = [1, 2, “Happy”, “Sad”] # Create a list with 4 values
j.append(“Dog”) # Add the value “Dog” to the list
print(j[0]) # Print the first item in the list
j.remove(j[1]) # Remove the item in position 1, in the list

The Output

[1, 2, ‘Happy’, ‘Sad’]
[1, 2, ‘Happy’, ‘Sad’, ‘Dog’]
[1, ‘Happy’, ‘Sad’, ‘Dog’]

Here I’m showing you how to edit values in a list. You may be a bit confused by what your seeing here? What you have to understand is that everything in Python is what we call an Object. To keep it simple, that means that every variable we create, in these examples, have access to functions that can be called by using the dot operator “.”.

So, I can perform the action of adding an item to the list named j, by just calling a function prebuilt into all list variables. That function is called append and you see how I called for it above.

If you find all of this object stuff to be confusing, don’t worry, I’ll cover it in detail later. For now, just remember how to manipulate lists.

What is a Dictionary in Python

Dictionary types, are similar to Tuples and Lists, in that they contain a collection of variables. One difference is that there is a key associated with each value in a dictionary. Here is some sample code, to help you understand:

k = ({“Age”: 35, “Height”: “6’3”, “Weight”: 170}) # Creates a dictionary, notice the key value pairs
print(k.get(“Age”)) # get() outputs the value associated with the key named “Age”
print(k.items()) # items() outputs all of the keys and values for the dictionary
print(k.copy()) # copy() outputs keys and values as well
print(k.values()) # values() only outputs the values
k.pop(“Height”) # pop() removes the value and key associated with the key “Height”

The Output

dict_items([(‘Age’, 35), (‘Weight’, 170), (‘Height’, “6’3”)])
{‘Age’: 35, ‘Weight’: 170, ‘Height’: “6’3”}
dict_values([35, 170, “6’3”])
dict_items([(‘Age’, 35), (‘Weight’, 170)])

That pretty much explains how Dictionary’s work in Python. I’ll cover them in much more detail in a future article.

That’s All Folks

I covered a bunch of things in this article. You now know a lot about the quirkiness of the Python programming language. You also know about all of the main data types available in Python. If you have any questions or comments, leave them in the comment section below.

Till Next Time

Think Tank

Leave a Reply

Your email address will not be published.