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.


Learn Advanced JavaScript Features

If you are a budding web developer, you will need to learn advanced JavaScript features, such as changing the functionality of elements as you interact with them, and passing functions into other functions. In other words, as interacting with the web page evolves, the functionality has to evolve with it.

Breakdown the following JavaScript / jQuery to grasp this concept:

$(“#title”).click(function() {

  • $(“#title”) grabs the element you want to work with.
  • .click changes the onclick function. This allows you to change the interactivity of onclick as your page evolves.
  • (function() passes in an anonymous function. It does not need to have a name, nor does it need arguments.


  • The code above is what you see inside the curly brackets. These are the arguments of .click. This type of programming would seem very odd to someone with a background in Java, but this is an example of how JavaScript is different from Java.}); These last three pieces of syntax close the function, end the .click arguments, and end the line.

You can put this code in the context of an HTML page as follows:

<script src=””></script>

<h1 id =”title” onclick=”sayGoodbye();”>

<script type=”text/javascript”>
function sayGoodbye() {
$(“#title”).click(function() {

So now, rather than just being able to change the text from ‘Hello’ to ‘Goodbye’, you can keep clicking on the <h1> element to switch back and forth.

While this is a simple example, it gives a nice demonstration of how the interactivity of a page can change, as the user does different things.

If you want a PHP developer job, then JavaScript would be a nice to tool to add to your skill set. It will empower you to build pages that are interactive for the user.

Complex JavaScript – Keep Code Clean

complex javascriptThere are standard coding practices to adhere to when coding more complex JavaScript. The underlying concept is to seperate JavaScript from the HTML document.

Look at this line of code for example.

<h1 id=”title” onclick=”alert(‘hello’);”>Hello</h1>


In this instance there is one bit of JavaScript after the onclick attribute. There certainly could be much more JavaScript after the onclick attribute, but that is considered bad form to write many lines of code for one attribute. There is a cleaner way to do it.

The <script> tag is used to import jQuery. A <script> tag is also used to call on custom code.

<script type=”text/javascript”>alert(‘Hello’);</script>

The above script has a type indicating that it is text consisting of JavaScript. Everything inside the script tags is the JavaScript.

Take one step further and put the JavaScript inside a function named sayHello().

function sayHello() {

And one more step by simply placing the function inside the <script> tag.

<script type=”text/javascript”>
function sayHello() {


This might have been lots of work for a simple JavaScript function, but consider if the function is 500 lines of JavaScript, and is easy to see why doing it this way makes sense.

Now you can look at everything in the context of a web page.

++<h1 id =”title” onclick=”sayHello()”>
<script type=”text/javascript”>
function sayHello() {

This can be taken one step further with a separate JavaScript file. Similar to a CSS file, a JavaScript file can be used to affect multiple HTML pages.

To do this, paste all the JavaScript code in a separate file with a name like scripts.js. Do not include the <script> tags in this document. In the HTML files, simply link the JavaScript file with <script src="scripts.js"> </script>. The way JavaScript functions are invoked from HTML elements does not change.

Look at jQuery for JavaScript

After gaining a basic understanding of JavaScript, the natural progression would be to look at jQuery for JavaScript.

The previous post demonstrated a simple web page that displayed the heading “Hello”, and it would log the same to the console each time a user clicked on the heading.

This next bit of code is rather simple, but it takes a huge leap forward in terms of capability. It introduces the concept of page interactivity. In other words, a page can have dynamics based on how the user interacts.

++<script src=””></script>

++<h1 id =”title” onclick=”$(‘#title’).html(‘Goodbye’);”>


The src attribute inside the <script> tag links the HTML document to the jQuery library. jQuery is a library of built-in JavaScript functions that makes using JavaScript faster and easier. Much like Bootstrap is a CSS library built for CSS3 that does lots of the heavy lifting for page styling, jQuery works in a similar way by making it easier to manipulate pages using JavaScript.

Breaking Down jQuery for JavaScript

In the above example, look at the code after the onclick attribute. It can broken down as follows:

  • The dollar sign $, calls on the jQuery library.
  • The argument ‘#title’, is a CSS selector that indicates selection of an HTML element by its id. In this case, the id is “title”. While elements can be selected by tag or class, id is normally used to select exactly one element.
  • The .html is calling a function to change the text of the element.
  • Finally, the ‘Goodbye’ is what the heading changes to. Click on “Hello”, and it will change to “Goodbye”.

In summary, this post demonstrated a simple interactive web page. This concept can quickly be expanded to create rich, interactive web experiences.

Download the jQuery library for free.

Web Browser Console and JavaScript

The web browser console is very useful for JavaScript. To access the browser console in Chrome, open the menu, click tools, and then developer tools. There should be a tab for console in the top menu bar.

Check the documentation for other browsers on how to access the console in those browsers.

Shown below is some simple HTML code that can be used to interact with the browser console:

++<h1 id ="title" onclick="console.log('hello');">


The console will log ‘hello’ each time the <h1> element is clicked.

Think of JavaScript as having the ability to work with different ‘objects’. The console is one object. HTML tags can be other objects, and the HTML document itself is an object. Interacting with these various objects represents the vast majority of what web developers do with JavaScript.

In the above example, look at the code "console.log('hello');". The log function is being called on the console. While this code is rather simple, it’s extremely important on a conceptual level. It underscores the relationship of how to call functions on objects. The ‘.’ between ‘console’ and ‘log’ is what links the object to the function. Developers often debug or test JavaScript code by printing to the browser console.

Interactive JavaScript – The Basics

To look at a basic web page, the computer’s browser sends a URL request to a server that hosts the page to be viewed. The server finds the HTML page, and sends it back to the browser, along with CSS styling. This interaction describes web pages up through the mid to late 1990s. However, a modern web page is more interactive. Interactive JavaScript programming is a skill modern web developers must know.

How JavaScript Works with HTML5 and CSS3

A modern web page can interact with the end-user without having to load new pages. It can play a video, show drop down menus, take field input, etc. JavaScript is the language that enables this type of interactivity.

To break it down, HTML provides the structure, CSS provides the styling, and JavaScript enables interactivity. JavaScript is a high functioning language, so it will probably not be as easy to learn as HTML or CSS.

It’s important to note that JavaScript is not the same as Java. These are two completely different programming languages.

Write Your First Interactive JavaScript

<h1 id="title" onclick="alert('hello');">Hello</h1>

the above <h1> tag in HTML contains an onclick event. The onclick event attribute is when the end-user clicks on the <h1> heading. The "alert('hello');" is JavaScript that tells the browser what to do when the onclick event occurs, i.e., when the end-user clicks on the heading. Everything else is HTML, except for this little script.

In the example above, a box will pop up that says "Hello" when a user clicks on the heading. The alert is a function that tells JavaScript what to do. The ('hello') part of the script is referred to as the argument. It tells the function how to do what it has to do.

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?