Category Archives: Python How To

Python Programming

Python ProgrammingI have received a ton of requests to make a Python programming tutorial in which I teach pretty much everything in one video.

I’ll cover modules, comments, print, arithmetic operators, order of operation, lists, tuples, dictionaries, conditional operators, logical operators, if, else, elif, loops, for, while, break, continue, functions, return, readline(), string operators, file i/o, classes, objects and much more. Continue reading Python Programming

Python 2.7 Tutorial Pt 19

Python 2.7 TutorialWell it has been a long trip, but I’m going to wrap up the Python Tutorial here. Before I stopped I wanted to answer one question posed to me which was to create a program that automated the process of getting demographics.

I didn’t have much time to perfect this and I plan to come back, but this program will grab tons of demographics for you including:

Continue reading Python 2.7 Tutorial Pt 19

Python 2.7 Tutorial Pt 18 Chat Server

Python PictureIn this Python Tutorial I show you how to build a simple chat server. All you need to do this are the pre-installed modules: asyncore, asynchat and socket.

The code then basically does the following:

  • Assigns a special address for each person that goes to the port (Socket)
  • Listens for any messages
  • When it gets a new message it sends it through the socket and into the port
  • A dispatcher decides what code should be called based off of the message sent

Continue reading Python 2.7 Tutorial Pt 18 Chat Server

Python 2.7 Tutorial Pt 17

Python How ToIn this video tutorial I show you how to create dynamic websites with Python. This is the quickest and easiest way to start using Python in much the same way as PHP is used.

I previously taught you how to scrap websites for information in this tutorial Python Website Scraping. Here I’ll show you how to scrap and then display that information dynamically on the internet.

Leave any questions or comments below and here are all of my previous Python Video Tutorial’s:

Continue reading Python 2.7 Tutorial Pt 17

Python 2.7 Tutorial Pt 16

Python 2.7 TutorialHere I continue to teach you how to use the Tkinter GUI module built into Python. I build an application that allows you to input files, edit them and then save them. I specifically show you how to make the following GUI widgets with Tkinter:

  • Menu Bars
  • Multi-Line Editable Text Boxes
  • Drop Down Menus

If you haven’t seen the previous Tkinter tutorial you should definitely check it out below first. Otherwise this won’t make any sense.

Continue reading Python 2.7 Tutorial Pt 16

Python 2.7 Tutorial Pt 14

Python How ToIn the previous tutorial I showed you how to grab the following from any sites rss feed using Python:

  • Title of Articles
  • All the Content from the Original Article
  • Link to the Original Article

This is known as website scraping and it is the major component used by all automated website applications. One thing I didn’t cover is how to strip the html tags from those articles, so I’ll do that in this video.

Continue reading Python 2.7 Tutorial Pt 14

Python 2.7 Tutorial Pt 13 Website Scraping

Python How ToIn this video tutorial I show you how to scrap websites. I introduce 2 new modules being UrlLib and Beautiful Soup. UrlLib is preinstalled on Python, but you have to install Beautiful Soup for it to work.

Beautiful Soup is available at their website. If you are using Python versions previous to Python 3.0 get this version Beautiful Soup for Python previous to 3.0. If you are using Python 3.0 or higher get this version of Beautiful Soup.

To install it follow these steps:

Continue reading Python 2.7 Tutorial Pt 13 Website Scraping

Python 2.7 Tutorial Pt 12

Python 2.7 TutorialIn this Python Video Tutorial, I will show you how to create databases using the Python SQLite module. SQLite is great because it:

  • Provides most of the basic database structure you want
  • Doesn’t require you to have an actual database server running
  • Provides SQL querying capabilities
  • Is included with Python by default

You enter and retrieve information from an SQLite database just like you do with any other database, by using SQL. Here is a tutorial on how to program with SQL if you don’t know how SQL Statements Video Tutorial. In that tutorial I focus on MySQL, but everything a say about SQL is nearly identical.

Continue reading Python 2.7 Tutorial Pt 12

Python 2.7 Tutorial Pt 11

PythonIn this video tutorial on how to use Python, I will focus on how to use an interesting Python Module called Shelve. Shelve allows you to store data in files similar to how a database works. It is very easy to use and provides a convenient way to take advantage of the power of Python dictionaries while providing you with the ability to change the data.

I’ll continue in the next tutorial to cover another interesting Python Module called SQLite. It is a Module that can be used as if it was a database meaning:

  • You can run SQL queries on it
  • Information is stored logically

Continue reading Python 2.7 Tutorial Pt 11

Python 2.7 Tutorial Pt 8

Python 2.7 TutorialIn this tutorial, I continue to explain how Object Oriented Programming is used with Python 2.7. I cover some of the more complicated subjects including how to:

  • Allow the user to define an infinite number of attributes
  • Use Inheritance and what it is
  • Override Methods
  • Use Polymorphism and what it is
  • Inherit from 2 more more classes
  • Use many of the built in object methods in Python

If you don’t completely understand Object Oriented Programming after this and the first part of this tutorial Python Object Oriented Programming. Please leave a comment below and I’ll do whatever I can to explain this important subject.

Like always, a lot of code follows the video. If you have any questions or comments leave them below. And, if you missed my other Python Tutorials they are available here:

Here is All the Code from the Video

Note: You have to insert the white space and everything will work. I could have styled it with HTML, but that would have required you to erase all of the tags. Hope this helps?

#! /usr/bin/python

__metaclass__ = type

class Animal:

__name = “No Name”
__owner = “No Owner”

def __init__(self, **kvargs): # The constructor function called when object is created
self._attributes = kvargs

# There is a function called a destructor __del__, but its best to avoid it

def set_attributes(self, key, value): # Accessor Method
self._attributes[key] = value
return

def get_attributes(self, key):
return self._attributes.get(key, None)

def noise(self): # self is a reference to the object
print(‘errr’) # You use self so you can access attributes of the object
return

def move(self):
print(‘The animal moves forward’)
return

def eat(self):
print(‘Crunch, crunch’)
return

def __hiddenMethod(self): # A hidden method
print “Hard to Find”
return

class Dog(Animal):

def __init__(self, **kvargs):   # Not needed unless you plan to override the super
super(Dog, self).__init__() # This wouldn’t work without the second line
self._attributes = kvargs

def noise(self):        # Overriding the Animal noise function
print(‘Woof, woof’)
Animal.noise(self)
return

class Cat(Animal):

def __init__(self, **kvargs):  # Not needed unless you plan to override the super
super(Cat, self).__init__()
self._attributes = kvargs

def noise(self):
print(‘Meow’)
return

def noise2(self):
print(‘Purrrrr’)
return

class Dat(Cat,Dog):

def __init__(self, **kvargs):  # Not needed unless you plan to override the super
super(Dat, self).__init__()
self._attributes = kvargs

def move(self):
print(‘Chases Tail’)
return

def playWithAnimal(Animal): # This is polymorphism
Animal.noise()
Animal.eat() # Works even if the method isn’t in Cat because Cat is an Animal
Animal.move()
print(Animal.get_attributes(‘__name’))
print(Animal.get_attributes(‘__owner’))
print ‘\n’
Animal.set_attributes(‘clean’,”Yes”)
print(Animal.get_attributes(‘clean’))

jake = Dog(__name = ‘Jake’, __owner = ‘Paul’)
sophie = Cat(__name = ‘Sophie’, __owner = ‘Sue’)
playWithAnimal(sophie)
playWithAnimal(jake)

# print sophie.__hiddenMethod() Demonstrating private methods

print issubclass(Cat, Animal) # Checks if Cat is a subclass of Animal
print Cat.__bases__           # Prints out the base class of a class
print sophie.__class__        # Prints the objects class
print sophie.__dict__         # Prints all of an objects attributes

japhie = Dat(__name = ‘Japhie’, __owner = ‘Sue’)
japhie.move()
print japhie.get_attributes(‘__name’)

Python 2.7 Tutorial Pt 7

PythonIn this video, I will explain the basics of Object Oriented Programming with Python. Understand that a Class is the blue print that defines what Attributes (variables) and Methods (functions), each object it builds must have.

Each Object that is created is said to be an Instance of the Class that built it. I’ll also go over what Encapsulation is.  Encapsulation is how you hide information  and constrain a user of your class to use it in the way you define. And, finally I teach you how to enforce Encapsulation by making your Attributes and Methods private.

Like always, a lot of code follows the video. If you have any questions or comments leave them below. And, if you missed my other Python Tutorials they are available here:

Continue reading Python 2.7 Tutorial Pt 7

Python 2.7 Tutorial Pt 6

Python PictureIn this video I’ll explain how to use functions in Python 2.5 through 2.7. I’m going to cover how to:

  • Create Functions
  • Pass Values to Functions
  • Create Default Values
  • Except Unlimited Arguments
  • Except Unlimited Key Value Pairs
  • Use Recursion
  • and more…

Like always, the code follows the video. If you have any questions or comments leave them below. And, if you missed my other Python Tutorials they are available here:

Here is Some Code that Demonstrates using Python Functions

#! /usr/bin/python

# Define a docstring a special function attribute
globalVariable = 10

def addNumbers(NumOne=1,NumTwo=1):
‘Adds the numbers passed to it’
return NumOne + NumTwo

def addUndefNums(NumOne=1,NumTwo=1,*args):
‘Adds the numbers passed to it’
finalValue = NumOne + NumTwo
if args:
for i in args:
finalValue += i
return finalValue
else:
return finalValue

def scopeFunction():
mainNumber = 10
print id(mainNumber)
print “mainNumber equals”, mainNumber, “in function scopeFunction”
return

def changeGlobal():
globals()[‘globalVariable’] = 20
return

def createDict(**kvargs):
for i in kvargs:
print i, kvargs[i]
print type(kvargs[i])

print type(kvargs)
print kvargs
return

def factorial(num):
if num == 1:
return 1
else:
return num * factorial(num – 1)

def printNames(first,last):
pass

def main():

# Demonstrate difference between global & local scope
mainNumber = 5
print “mainNumber equals”, mainNumber, “in function main”
scopeFunction()
print “mainNumber equals”, mainNumber, “after scopeFunction”
print id(mainNumber)

# Force a global variable to change
print “globalVariable before changeGlobal =”, globalVariable
changeGlobal()
print “globalVariable after changeGlobal =”, globalVariable

# Create a function with a docstring
print addNumbers(1)
print addNumbers.__doc__

# Add undefined number of numbers with a tuple
print addUndefNums(1,2,3,4,5,6,7,8)

# Create a dictionary
createDict(Name=’Derek’, Age=35, YearBorn=1974)
createDict(Cust1=(‘Derek’,35,1974),Cust2=(‘Sally’,25,1984),Cust3=(‘Paul’,15,1994))

# Demonstrate Recursion
print factorial(3)

“””
Demonstrate Recursion
def factorial(3):
if 3 == 1:
return 1
else:
return 3 * factorial(2)

def factorial(2):
if 2 == 1:
return 1
else:
return 2 * factorial(1)

def factorial(1):
if 1 == 1:
return 1

“””

if __name__ == ‘__main__’: main()

Python 2.7 Tutorial Pt 5

Python How ToIn this Python Video Tutorial I focus on looping in Python 2.5 through 2.7. I explain how to use the while loop and the many ways to use the for loop.

Along the way I explain how the in operator is used in Python and the range function.

Like always, the code follows the video. If you have any questions or comments leave them below. And, if you missed my other Python Tutorials they are available here:

Continue reading Python 2.7 Tutorial Pt 5

Python 2.7 Tutorial Pt 4

Python 2.7 TutorialI continue the Python 2.7 Tutorial by explaining a couple new things. I first go over how to turn your Python code into an executable application.

I then cover Python Conditionals. Conditionals are used to perform certain actions under one condition and other actions based on other conditions. In Python you can do this either with an IF Statement, or with something called a Conditional Expression.

Like always, the code follows the video. If you have any questions or comments leave them below. And, if you missed my other Python Tutorials they are available here:

Continue reading Python 2.7 Tutorial Pt 4

Python 2.7 Tutorial Pt 3

PythonIn part 3 of my Python 2.7 Tutorial, I explain how to use the Dictionary, Print method and how to work with String methods.

If you haven’t seen part 1 or 2 definitely look at them first or you’ll be very confused Python 2.7 Tutorial Part 1 and Python 2.7 Tutorial Part 2.

All of the code I use in these tutorials follow the video and can be used however you’d like.

If you have any questions or comments leave them below.

Continue reading Python 2.7 Tutorial Pt 3

Python 2.7 Tutorial Pt 2

Python Picture

I continue with my Python 2.7 tutorial here. If you missed part one (How Dare You) you must watch it first at Python 2.7 Tutorial. Otherwise you’ll be confused. I specifically explain how to use Python Lists, Tuples and Dictionaries. These work very similar to arrays in other languages.

An array is a variable that contains multiple values. Think of an array as a box that contains many other boxes, that all contain values. These values can be a mixture of different data types (ints, floats, strings). Here is how Python Lists, Tuples, and Dictionaries differ:

Continue reading Python 2.7 Tutorial Pt 2

Python 2.7 Tutorial

Python How ToI asked you guys what video I should do next, and based on your votes you wanted a Python 2.7 Tutorial! Because of the tremendous interest, I will be rolling out a Massive tutorial for Python. I actually did one on Python 3.0 if you want that instead though. Here it is Python How to Video Part 1.

The tools I use in this tutorial include the Eclipse IDE and Pydev. I document how to install them in the video below, but also in this article Free IDE.

Now on with the video. All of this code will work with Python 2.5 thru 2.7. The code will follow the video. If you have any questions or comments leave them below. Here is all the code from the entire tutorial in a zip archive.

Continue reading Python 2.7 Tutorial