Python Open Function – Read Text Files

Text files are stored in secondary memory, so you need a way that tells Python where to go look for the text file we want it to read. This is what the built-in, Python open function is for.

For example:

handle = open(readme.txt, r)

In this example we assigned a variable name of handle that we can use to manipulate the file. The first parameter inside the parenthesis is the actual file name we want to open, and the second parameter of r indicates read mode. The other option is w for write mode, but for now we will use the read mode. The mode r is chosen by default for the Python open function if left blank.

It is important to note that the variable handle is not the file itself. Rather, it is a mechanism to use the file. To keep things simple, you want your text file to be in the same folder as your Python code file.

Before moving forward, you have to understand there is a special character to use that indicates when a line ends.

The New Line Character

>>>print ‘XY’
>>>print ‘X\nY’

The \n character tells us we start on a new line.


You see that the new line character counts as only one character, even though it is technically two. Think of \n as syntax to encode a new line in a string.

You have to mentally visualize the new line character as being there at the end of lines in text files. Text editors do not show us this character when we are just looking at the text, but they are encoded there, and you have to know that.

The Efficiency of the Python Open Function

You can print every line in a file with three lines of Python code.

xfile = open(readme.txt)
for line in xfile:
++++print line

You can count the lines in a file with six lines of Python code.

xfile = open(readme.txt)
count = 0
for line in xfile:
++++count = count + 1
print ‘Line Count=’, count

Notice in these examples we used xfile instead of handle as our variable name. That is okay, it is just a variable name.

You can also read every character of a text file into one string. You would use the built-in read function.

xfile = open(readme.txt)
one_string =
print len(one_string)

This program will print the number of characters in your text file. In other words, it prints the length of one string.

You could print the first 20 characters.

print one_string[:20]

Select Only the Text You Want

Suppose you have a fairly large text file, and you only want to print only lines that start with the word ‘Time’.

xfile = open(readme.txt)
for line in xfile:
++++line = line.rstrip()
++++if line.startwith(‘Time’):
++++++++print line

You might be thinking, what is the purpose of line = line.rstrip()? Well, this bit of code strips the newline character from the text file. It is a built-in function that removes the whitespace so your program will not print blank lines.

You can skip a line by using the continue statement. The following Python code will skip every line that does not start with ‘I’.

xfile = open(readme.txt)
for line in xfile:
++++line = line.rstrip()
++++if not line.startwith(‘I’):
++++print line

You can use ‘in’ to select lines. The following Python code will only select lines containing the ‘$’ character:

xfile = open(readme.txt)
for line in xfile:
line = line.rstrip()
++++if not ‘$’ in line:
++++print line

How to Catch Bad User Input

Use this code to prompt a user for a file. This will catch a bad file if the user does not enter the file name correctly, or if the file does not exist.

xname = raw_input(‘Enter the file name: ‘)
++++xfile = open(xname)
++++print ‘File cannot be opened’

The Python String – Parse It!

A Python string is a sequence of characters. You can use single or double quotes to delimit a string.

We can look inside a Python string with the index operator. Use the square brackets for this, []. You must know that the index value is an integer and always starts at zero.

>>> creature = ‘monkey’
>>> print creature[0]

The output is m because the index value of a string always starts at zero. In other words, m is the first index value of the string ‘monkey’.

>>> x = 4
>>> print creature[x-1]

An expression can exist inside the index operator. Got it? Good!

Sometimes you need to know the length of a string.

>>> l = len(animal)
>>> print l

That’s right! The string ‘monkey’ has six characters. Note that len is a built-in function. It’s already been written for us, we just have to apply it.

You can loop through strings. The following is Python program to loop through a particular Python string.

food = ‘pizza’
for letter in food:
++++print letter

In the above program, the word letter is being used as an iteration variable.

You can write a Python program to count the occurrence of a letter in a string.

bigword = ‘supercalifragilisticexpialidocious’
count = 0
for letter in bigword:
++++if letter == ‘i’:
++++count = count + 1
++++print count

Slicing the Python String

You can slice a Python string to get a substring.

>>> bigword = ‘supercalifragilisticexpialidocious’
>>> slice = bigword[0:5]
>>> print slice

You can see that it will slice up to, but not including the second index value. The fifth index value is the letter c, but that is not include in our slice.

If you omit a the first or second index value, it will assume the beginning or end respectively.

>>> slice = bigword[:]
>>> print slice

You can look for values.

>>> ‘x’ in bigword

Yes indeed! The letter x is in supercalifragilisticexpialidocious.

There is an extensive Python string library. These are built-in functions we can invoke on strings.

>>> greet = “HOw aRe YOu?”
>>> print greet.lower()
how are you?

You can look for a character and know its index value.

>>>idea = ‘Learn Python Programming Language’
>>>print idea.find(‘Python’)

Correct! Python start at the sixth index value of the string. Remember, index values start a zero!

Stripping Whitespace

You need to know how to remove whitespace at the beginning or end of strings. These are lstrip, rstrip, and strip. They remove whitespace from the left, right, and both sides respectively.

>>> color = ‘ blue’
>>> print color
>>> print color.lstrip()

See how that works? Great!

Sometimes you need to extract lines that begin with a certain string.

>>> line = ‘Email message sent at….’
>>> line.startswith(‘Email’)

These examples show how Python is really good at parsing data.

Python Loop – Simple Examples to Learn

A Python loop is what you can use to make computers do repeated processes that humans would quickly grow tired of. However, computers do not grow tired of repeated processes.

Python Loop
A Python loop can be used to repeat a process many times.

A Python loop usually will contain an iteration variable. This variable will change each time it goes through the loop.

Avoid an infinite loop, because those cause the CPU to crash. The iteration variable controls how many times the Python loop will run.

Beware the Infinite Python Loop

Below is an example of an infinite loop. You can see the error in logic that would cause the loop to never stop.

x = 3
while x > 0:
++++x = x + 1
++++print ‘I am going to crash!’


If you started the value of x at zero or below, then the above Python loop would never run. That would be called a zero trip loop.

How to ‘Break’ the Loop

Another way to force out of a loop is to use the Python reserved word ‘break’. Look at the example below of how this can be used. The loop will stop when the user enters ‘done’.

A Python loop with break.
User input ‘done’ will cause the loop to stop.

Skip and Continue

Another useful statement for a Python loop is ‘continue’. The continue statement stops the current iteration and jumps to the top of the loop for the next iteration. Thus, ‘continue’ does not stop a loop, it just allows you to skip certain iterations.

while True:
++++word = raw_input(‘ ‘)
++++if word == ‘skip’:
++++if word == ‘done’:
++++print word
print ‘Done!’


The above example demonstrates a Python loop that will skip an iteration if the user enters the word ‘skip’.

From the Indefinite to the Definite Python Loop

These examples thus far of ‘while’ loops are often called indefinite loops. They will run until a logical condition becomes false. The examples here have been simple, but with more complex code comes the need for extra precaution. At some point the condition must become false, or else the loop will be infinite.

A definite loop is a type of loop that will iterate a finite number of times. The Python reserved word used to construct an infinite loop is ‘for’.

Python For Loop
Another Screenshot from Dr. Chuck’s Python Course at Coursera

A for loop does not just have to iterate through a set of numbers. It can iterate through a set of strings as well.

cities = [‘Los Angeles’, ‘Dallas’, ‘New York’, ‘Rome’]
for city in cities:
++++print city, “is a famous city.”


A for Python loop takes on the responsiblity of advancing the iteration variable. In essence, the iteration variable moves through all the values in the sequence.

Give Your Loop Intelligence

Loop idioms are how you construct a loop. The idea is to give the loop intelligence. Start by knowing what the Python loop wants, and then approach that by writing one line of code at a time. Think of this process in three steps.

  1. Set some variables for the loop.
  2. Do something to each variable.
  3. Return a result.

Imagine you have a list of 100,000 numbers, and you need to find the largest number. The example below demonstrates with a small set of numbers, but the same loop would apply no matter the size of the number set.

Find the Largest Value Loop
A Python loop for finding the largest value from a list.

Finding the average of a list of numbers is a classic programming problem. To accomplish this, you need to introduce a count variable. The count variable will keep track of the amount of members in a set. Look at the following example.

count = 0
sum = 0
set = [89, 78, 90, 87, 94]
for value in set:
++++sum = sum + value
++++count = count + 1
print ‘The average is’, sum / count


Use a conditional if statement within a Python loop to filter values. For example:

for value in [89, 78, 90, 87, 94]:
++++if value >= 90:
++++++++print value, “is one of your best grades!”
print “Good Job!”


You can also search using a Boolean variable.

A_grade = False
for value in [89, 78, 90, 87, 94]:
++++if value >= 90:
++++++++A_grade = True
++++++++print “You got an A!”


In the above example, the condition will change to true on the third iteration. The break statement will then prematurely stop iterating through the list.

It is easy to see that a loop could be integral to many types of Python functions.

Do you have what it takes to learn Python? Boost your career potential, and get on the Python specialization track at Coursera. Financial aid may be available to those who qualify.


Python Functions – Store and Reuse Your Code

Python Functions Example
Understand the output.

Python functions can be very useful. Python functions store logical steps that can be reused.

The advantage with a function is it can be invoked, rather than having to always retype the lines of code that consist of the function.

The Python reserved word to store a Python function is ‘def’. If you start a line of code with ‘def’, it tells Python to store the function, but to only run it if it is called on later.

Python Functions Examples

def hello():
++++print ‘Hello’

The first two lines in this example are the Python function. The last line below it invokes the function. The Python function will not execute until it is invoked.

Invoking a Built-In Python Function

A Python function could be built-in, so all you have to do is invoke it.

>>> big = max(‘Hello World’)
>>> print big

In the above example, ‘max’ is the built-in Python function. The string inside the parenthesis is called the argument. The argument passes through the function. The ‘max’ function then returns the highest character of a string.

Other common built-in functions are ‘float’, and ‘int’. There are many built-in Python functions. However, A Python function you write yourself is called a user defined function.

A Python Function with Arguments

Look at the following Python function:

def addition(x, y):
++++sum = x + y
++++print sum


Now you can invoke the function with two function arguments, as follows:

addition(5, 3)


Invoking this function should cause ‘8’ to be printed.

Now look at a slightly modified version of the addition function:

def addition(x, y):
++++sum = x + y
++++return sum


Notice the word ‘return’ was used. This gives you a return value, and it terminates the function. However, it does not print the value. You control where it prints, such as:

print addition(1, 2)


The number ‘3’ would be printed because that would be the return value.

You will not always need to write a Python function in your program, but if you catch yourself reusing code, it might be best to put that code in a Python function that can simply be invoked when you want to execute it.

Get started with interactive Python practice at Codecademy. You will start with the basics, and quickly ramp up to writing your own functions.


Python Conditional Execution Explained

A Python conditional may involve steps in a program that may or may not be executed.

Look at the following Python conditional program:

x = 0
if x == 0:
++++print x, ‘is nothing.’
++++print x, ‘is something’


Think of the word ‘if’ as asking a question. The above Python conditional is asking if x is equal to zero. In this case it is, so the indented statement directly under the ‘if’ question gets executed. Consequently, the ‘else’ is ignored. The opposite would be true if x was any other value.

Know The Python Conditional Comparison Operators

You will need to be familiar with all the comparison operators to be proficient with Python conditional logic.

Python Conditional Comparison Operators
Take a moment to study these comparison operators.

Look at how to modify the above program to effectively do the same thing.

x = 0
if x != 0:
++++print x, ‘is something’
++++print x, ‘is nothing.’


Remember that comparison operators only look at a value, they do not change it. Hence, there is a difference between ‘=’ and ‘==’. The first assigns a value, and the latter looks at a value.

Boolean expressions use comparison operators to evaluate to ‘True’ or ‘False’.

smart = True
if smart:
++++print ‘Congratulations!’


Indentation is very important for a Python conditional to execute properly. The convention is four spaces, but that’s not a hard fast rule. All lines that are part of a conditional should be indented. De-indenting ends the conditional.

x = 0
if x == 0:
++++print x, ‘is nothing.’
++++print ‘sorry’ ,x
++++print x, ‘is something’
++++print ‘way to go’, x,


Warning! Your text editor may see indenting with a tab differently than indenting with spaces. Use spaces to indent for Python. The alternative is to go into the properties of the text editor, and change the tab settings to be seen as spaces.

Using Python Conditional Logic for Nested Decisions

A Python Conditional can be nested inside other conditionals.

x = -1
if (x > 0):
++++print x, ‘is not negative’
++++if (x > 1000000):
++++++++print x, ‘is quite large’


In the above program, None of the conditionals will execute, because x is negative. If x is 100, then only the first conditional executes. If x is 1000001, then both conditionals execute.

A Python Conditional for Multi-Way Decisions

You can also write conditionals that involve multi-way decisions. Use the Python reserved word, ‘elif’. It means else if. Look at the following program:

x = 3
if (x < 3):
++++print ‘Small’
elif (x < 7):
++++print ‘Medium’
++++print ‘Large’


In the above program, x would be medium. Many ‘elif’ statements maybe be used. Only one ‘else’ statement can be used.

Look at the following puzzles, and try to identify the defective line in each program. Both the left and right side programs have a defective Python conditional.

Python Conditional Multi-Way Puzzles
Look for the Python Conditionals that will never execute.

The ‘try’ and ‘except’ Special Python Conditional

The ‘try’ and ‘except’ conditional has limited use, but can be handy when building a program with some dangerous code.

This concept might be hard to imagine, so take a look at the example, for conceptual purposes.

my_string = ‘nine’
++++my_number = int(my_string)
++++my_number = 9


The code ‘my_number = int(my_string)’, is the dangerous code. It is going to blow-up the program because you can not use ‘int’ on a string. However, the program is rescued by the two lines that come below that.

This special Python conditional could be useful for controlling user input, for example. Sometimes users will make mistakes when giving input. A good program can work around user mistakes. Use the special conditional as a work around while building new programs.

Here is a solution to the classic calculate pay problem. In this problem you have to use a conditional to calculate pay because there are two pay scales – regular and overtime. How might you solve this problem with your own Python program?


Python Variables and Operators

Python Variables

Using variables is one of the most powerful features in Python. Use assignment statements to create variables and give them values.

From the chevron prompt in the Python interpreter:

>>> x = 12
>>> message = “You are doing a good job!”


In the code samples above, two variables were created. Now you could tell Python:

>>> print x
>>> print message
“You are doing a good job!”


You can name variables with almost whatever you want, but it is good practice to give them a name that is meaningful.

The two main rules for naming variables are:

Python Operators

You need to know how to use operators ‘+, -, *, /, and **’. The operator ‘**’ is for exponentiation.

The order of operations follows the same PEMDAS rules. For example:

>>> x = 2 + 3 * 5
>>> print x


Beware of the Division Operator

The division operator might not do what you expect.

>>> y = 1 / 2
>>> print y

Why zero? When both operands are integers, the result is an integer. In other words, the decimal part gets chopped off. To solve this you have to use float types.

>>> y = float(1) / float(2)


One other operator, that is surprising useful, is ‘%’, the modulus operator. It yields the remainder.

>>> y = 5 % 2
>>> print y


Finally, use the ‘+’ operator for concatenation. That is, joining strings together.

>>> print ‘Hello,’ + ‘ World!’
Hello, World!


Python Values – Know the Type

Python values are basic things the language works with. Python values belong to different types. Use the Python interpreter to ask for the type of a given Python value.

Below are examples of input and output from asking Python for types of various Python values. The chevron prompt “>>>” is input for Python, and the line below is output from Python.

>>> type('Cookies')
<type 'str'>

>>> type(3)
<type 'int'>

>>> type(3.0)
<type 'float'>

<type 'str'>


The first type means string. After that it’s, integer, floating number, and string. Notice that if you put quotations around a number, it becomes a string.

While it might be habit, refrain from using commas with large numbers. It will cause a semantic error, because Python would interpret it as a comma separated sequence of numbers.

Write a Simple Python Program

Download Python for free, and write a simple Python program. The examples in this blog will use Python 2. It is okay to learn either 2 or 3. They are similar, but definitely have differences.

Your First, Simple Python Program

Open a text editor and write the classic “Hello World!” program. Simply type as follows:

print 'Hello World!'


Save the file with a .py extension. Name the file

Execute the script then you will see “Hello World!” as the output.

Yes, it is a trivial program with almost zero practical use, but by definition, it is a program.

A good resource for understainding Python is Dr. Charles Severance’s free Python for Informatics book.

If you are interested in learning Python, and need to start at the basics, take a look at the Python for Everybody Specialization offered through Coursera.

Python Reserved Words to Know

This post is as a reference for Python reserved words.

Python reserved words have special meaning, and must only be used in regard to their special meaning. They include:

and not as
global assert del
while elif or
else from with
if pass break
import class raise
continue return def
lambda yield except
print exec finally
for try in

You must not use these words as variables, because they already have a special command meaning for Python.

Python understands these commands like a trained dog understands “sit”. So again, you must not use Python reserved words as variables.

Program with Python Reserved Words

You can use one of these Python reserved words to write your first Python program.

print 'Hello World!'


This, of course, is the classic ‘Hello World!’ program, written in Python.

Computer Hardware Architecture Basics

Before learning how to program computers, take a moment to understand the computer hardware architecture basics.

The Central Processing Unit

The CPU can execute commands extremely fast. The catch is, it has to be told what to do, or it won’t do anything.

The Main Memory

The main memory stores information that the CPU can retrieve extremely fast. Anything stored here will vanish when the computer is turned off.

The Secondary Memory

This stores memory but it is very slow. We need it because it can store memory even without power. Examples of this are a hard drive, USB stick, or disk drives.

The Network

The network can serve as remote secondary memory, because information is stored over the network that you can retrieve.

The Input and Output Devices

This could be a mouse, keyboard, monitor, speaker, joystick, etc. You use these to interact with your computer.