Loops and Logic

Published May 19, 2020, 1:18 p.m.

I think we are ready to make our first program.  Loops and logic are are the core of every program.  Machines make light work of repetative tasks.  In a real program that uses loops, effort goes into designing a routine that can be repeated efficiently.  Always remember that programs do what you tell them to do; not what you want them to do.  They do what you want them to do only if you tell them precicsely what you want them to do and tell them in the way that they are designed to be told. 

Loops are great, but logic is how you can get something meaningful out of your program.   You can write a loop to spit out a ton of data at you, but you can use logic to have the computer give you only what you want. 

The program that we are writing here is a trivial program to print names and numbers on a screen. 

First you will want to get a text editor in which to write your program.  I like Notepad++ because it is free and it sets out a fairly nice display for lots of different types of code including python.  It color codes your program so you can easily identify areas with comments (non-code sections) and it highlights in bold blue text common key words in python syntax (or whatever the programming language).

Once you have the editor, you should save an empty file in the location in which you want to run your programs.  I called mine: myprogram.py.

Python programs generally have the '*.py' extension.

In almost all of my programs, I start off with an import section.  Though we won't use any imported features, we will import some standard modules that are commonly used.

import sys
import os

It is accepted as good practice to have your imports at the top of your code.  Technically you only need to import them before you want to use them.  In future tutorials I will show that you can bits and pieces from modules and rename them but for now, we will just import these two.

The next thing we will want to do is to define some data.  Python was designed with an emphasis on code-readabililty.  With that in mind we will extend that practice as we write programs.  I will define a list of names and give it a descriptive name:

list_of_names = [
				'Bob',
				'Jim',
				'Frank',
				]

or

list_of_names = ['Bob','Jim','Frank']

Note here that when you define a container (list, tuple, dictionary) in python, once you start the left side of the container, python keeps interpreting code as input into the contianer until you close it off with the right-side counterpart.  In python you can do it in one line or on multiple lines.  Python ignores tabs and spaces in this case (unless they are in quotes).

Let's make our first loop!  To loop through this list we will write the following:

for name in list_of_names:
	print(name)

Notice here that spacing is important.  Python doesn't use containers for sections of code, however, it adheres to strict spacing rules.  When you start a for loop how does python know what is in the loop and what is not?  The answer is spaces (or tabs).  I always like to use tabs.  Many people use 4 spaces.  Either is fine.  However, you can't mix them. Use one or the other.  Just be consistent.  That is what python is looking for; consistency in spacing.

To execute the code, save the file and at the command prompt (in the same folder as the file) type:

C:\PythonProject>python myprogram.py

See that my command window is navigated to C:\PythonProject.  That is the folder where my program file is located.

Executing that command should produce:

Bob
Jim
Frank

as output on the screen at the command line.

Now let's say that we need to add a name to the list.  In our program we want to append data to the list before our loop to print.  the whole code (so far) should look like the following:

import sys
import os

list_of_names = [
				'Bob',
				'Jim',
				'Frank',
				]

list_of_names.append("Steve")

for name in list_of_names:
	print(name)

If we execute again, it prints Steve as part of the list.

Now let us consider introducing a few more print statements and some logic.   Logic generally runs on "if" statements that look for some bool value (True or False).  When adding if statements, the same rules for spacing apply.  What you will end up with in your code is compounding spacing as loops and logic go deeper.  To start we will now print our name from the list twice and in between the name we will have python print the index of the name in the list.

for name in list_of_names:
	print(name)
	print(list_of_names.index(name))
	print(name)

The output is a loop of name, index, name again (for all the names):

C:\PythonProject>python myprogram.py
Bob
0
Bob
Jim
1
Jim
Frank
2
Frank
Steve
3
Steve

Now we will throw in some logic.  First we will define a variable 'idx' to be the current index of the name. 

idx = list_of_names.index(name)

at the top of our loop.  Then we can add a logic statement that if the index is 2, then print a special message. The for loop should look like:

for name in list_of_names:
	idx = list_of_names.index(name)
	if idx == 2:
		print("THIS IS INDEX 2")
	print(name)
	print(list_of_names.index(name))
	print(name)

At this point.   When executed the output is:

C:\PythonProject>python myprogram.py
Bob
0
Bob
Jim
1
Jim
THIS IS INDEX 2
Frank
2
Frank
Steve
3
Steve

In addition to the 'if' statement, we may want to do something for all the other cases (when the index is not equal 2).  Adding an 'else' to the if:

for name in list_of_names:
	idx = list_of_names.index(name)
	if idx == 2:
		print("THIS IS INDEX 2")
	else:
		print("Not Index 2")
	print(name)
	print(list_of_names.index(name))
	print(name)

and executing yields:

C:\PythonProject>python myprogram.py
Not Index 2
Bob
0
Bob
Not Index 2
Jim
1
Jim
THIS IS INDEX 2
Frank
2
Frank
Not Index 2
Steve
3
Steve

Now programmers are not known for knowing when to leave well enough alone.  In that spirit I will show you a second way to processes loops.  Rest assured that there are probably dozens of ways to loop through data.  These two ways should be more than sufficient for this tutorial. 

First I will 'comment' out the portion of the code that we just ran.

# for name in list_of_names:
	# idx = list_of_names.index(name)
	# if idx == 2:
		# print("THIS IS INDEX 2")
	# else:
		# print("Not Index 2")
	# print(name)
	# print(list_of_names.index(name))
	# print(name)

In python, anything following a '#' character is considered a comment and ignored by the code.

In the first loop that we executed, we derived the index from the name in the list inside the loop.  Now I will introduce two embedded python functions:  range() and len().  You will also see a bit of code that some call "pythonic" as well as some more standard python syntax.

The range function in python has some default behavior but as we will see it is customizable.  The range function is its own python class.  If given an interger argument it presume that a sequence starting from 0 and equal in length to the integer is desired (0 to n-1).  the range function is used with the python keyword 'in'-- often in a for loop.  The for loop needs spme iterable sequence to loop through.  In python the following code:

[i for i in range(4)]

Is a pythonic way of making a list of integers from 0 to 3. The range output can be customized a little bit. 

Here is the range function used in a loop:

for i in range(len(list_of_names)):
	if i == 2:
		print(list_of_names[i])

Here we have used another python function: len()

the len() function takes a list as input and returns the length of the list.  The length of the list of names is 4.  Therefore the line is the equivalent of having 'for i in range(4):' in the code.  The nice thing about using the len function is that it changes with our list.  If we add or take away from the list the len function always gets it right on the fly.

So this loop will only print when i is 2, so it should only print Frank.

Back to the range function for a second...

If given two integer parameters, it assumes you want to start with the first one and end before the last one.  If given a third integer parameter, it assume that the last integer is the step size.  That is instead of a step size of 1, step by some other amount.  The step amount can be negative if desired.  Here is an example of the range function with three integer parameters:

print([i for i in range(4)])
print([i for i in range(1,11,2)])

The second statement prints 1,3,5,7,9. Why doesn't it print 11?  because 11 is our "stop" value and is not included.

Now we can continue to add loops or logical statements within our new loop as long as we properly indent the code:

for i in range(len(list_of_names)):
	if i == 2:
		print(list_of_names[i])
		if list_of_names[i] == "Frank":
			print("yes!")
	elif list_of_names[i] == "Bob":
		print("It was Bob!")

This code loops the the list of names and performs logic to make print statements.  In what order will it print them?

It was Bob!
Frank
yes!

Does it print in the order you expect?  If not, look at it and work it out until it prints the way you think it should.

Thanks for watching.  Now its time to move on to bigger and better things!  See you in the next tutorial series!

  • Download Python!

  • Python Interactive Session

  • Python Data Types

  • Python Containers

  • Loops and Logic
    (currently viewing)