10+ Python programs and tips you have already known

Our Own Score

If you are a python application developer then this post is just for fun as I put together all my previous python programming articles to create one single python programming article in order to save space for my blog. I hope you do enjoy it and do provide this article with star rating at the end of this post. All right let get started.

Before we go deeper I would like to greet you all with one line of python code which is the traditional greeting method for all programming languages.

print("Hello World")

Now let us begin with our first python tip.

How to set up python platform in NetBeans

First open up NetBeans then Tools->Plugins then type in ‘python’ to the search box and checked on ‘python’ when the name of this plugin shows up on the left hand pane, finally click on the Install button to complete the plugin installation process. NetBeans will recommend extra plugins that you will need to run the python program besides the python plugin if you have not yet selected them, select those plugins as well before downloading the entire python platform package!

After you have installed those plugins, restart the NetBeans IDE and go to File->New Project and select Python->Python Project – Ant then click Next. In the next page fill in the Project Name as well as fill in the path to the main folder in which you would like to keep all your project folders, select your python platform (Python 2 or 3) and leave the rest as default then click on Finish to create your very first python project.

Select Python Platform
Select Python Ant Platform
Create New Python Project
Create New Python Project

I have just entered below code into the python code editor, then select Run->Run Project to run the project on the python 3 platform and see the outcome in the output pane below the code editor.

Python 3 Array
Python 3 Array
Output Pane
Output Pane

NetBeans is a free IDE which we can use to create project written in various programming languages and it also has lots of plugins that we can download to further helps us in our software development.

How to run python program in windows command prompt

If you prefer to run python program with windows command prompt then after you have installed python in your computer you can open up the command prompt and type in python to start the python shell, then from there you can start to type in the python script and run the program.

Lets write a simple python script to sort a list as follow, you will need to press the enter key each time you have completed a line.

windows command prompt
windows command prompt

The script above will sort the data in ascending order.

As you see we can use windows command prompt to write and run the python script easily, but for the complicated program which requires us to debug and change the python script repeatedly then we will need to use the real IDE such as NetBeans or Eclipse.

How to create your first python module

1) First lets create a main python module folder where we can then keep all our python modules in one place. Create the main module folder either in the c or d drive of your computer, then create a folder inside that main folder to keep our new python module.

Main Module
Main module and module folder

2) Next create a new python project in NetBeans IDE.

Create a new module
Create a new module

You can either delete the default .py file in the project and create a brand new empty module or turn that default file into module. In this tutorial I will delete the default file and create an empty python module. Right click on summation.py then delete then right click on the project folder and select New->Empty Module. Enter the module name then click on Finish. Next we will enter a few lines of code into the NetBeans editor plus a few lines of comment that explain what this module is for…

#This is the “summation.py" module, and it provides one function called
#sumUpNumber() which will sum up all the numbers you have put into it

def sumUpNumber(*args):
    #Your input will be any number, any length of parameters 
    #into this function and it will return the total
    total = 0
    for arg in args:
        total += arg
    return total

Next copy the summation.py file and paste it in PythonModule->summation folder which you have just created. Create a new file with Notepad++ Editor which is another IDE I often use to do the coding job. Enter below code into that empty file and save it in the PythonModule->summation folder as setup.py. Those code that you have entered below will become the metadata of your module distribution.


from distutils.core import setup

setup(
	name = 'summation',
	version = '1.0.0',
	py_modules = ['summation'],
	author = 'choose',
	author_email = 'youremail@hotmail.com',
	url = 'http://leftmouseclickin.com',
	description = 'Module for number summation',
)

That is it for the setup.py part! Next open up the windows command prompt and browser to the summation folder at the hard drive where those two files are located and type in below command then press enter.

distribute module
distribute module

This will create the distribution package for the summation module.

Next install the distribution into the python site-packages with this command

Install Module
Install Module

Now this module should be inside the python’s site-packages, it is time to import the module into a new python program and runs it. Create a new python project in NetBeans IDE then enter below code and Run the program!

from summation import sumUpNumber

if __name__ == "__main__":
    print(sumUpNumber(1,2,3))

It works! The outcome is as follow:-

NetBeans Output Pane
NetBeans Output Pane

So there it is, you have created your first module in python and then install it in the python’s site-packages folder so you can then import and use that module in your other python program again and again!

Next I will show you how to share your python module with the rest of the world so the other programmer can use the module you have created as well.

First of all you will need to register an account with https://pypi.python.org/pypi so you can upload your module and share it with the rest of the world. Go ahead and register with pypi with the same author name you have entered into the setup.py file of the previous module.

Next open up the windows command prompt and then browsed to the folder where you have kept the python module and type in the below command into the command prompt

python setup.py register

Select 1 after you have been presented with below screen

login to pipy
login to pypi

Enter the username and password you have just created on pypi then press enter.

Register PyPI
Register PyPI (Status of 200 means OK)

That is it! Now it is time to upload the python module to PyPI with below command.

upload module
upload module
uploading...
uploading…

Now that python module is up there for the world to use, you can start to create your own module now and share it with the rest of the world after this tutorial.

Your very first wxPython project in Python

In this tutorial I will introduce you to wxPython which is another GUI toolkit besides tkinter which you can use to create GUI for your python application. Phoenix is wxpython for python version 3.x.x which you can download through this link : https://wxpython.org/Phoenix/snapshot-builds/, remember to download the latest version of Phoenix which matches your python version (3.x.x) and your OS. I have Python 3.5.2 installs in my pc that runs on the 64bit windows 10 os so I have downloaded the wxPython_Phoenix-3.0.3.dev2421+1efd6fb-cp35-cp35m-win_amd64.whl file to my pc.

Once you have downloaded the whl file you will need to install it in the python site package folder with this command : pip3 install wxPython_Phoenix-3.0.3.dev2421+1efd6fb-cp35-cp35m-win_amd64.whl.

After you have installed the module, start a new project in NetBeans IDE and then create a new python module under the Sources folder just like before. In this new module enter below script.

# Import wxPython module and system module
import wx
import sys

# Subclass wxPython frame
class WXFRAME(wx.Frame):
    
    def __init__(self, parent, title, size=(200,100)):
        
        # Initialize super class
        wx.Frame.__init__(self, parent, title=title, size=size)
    
        # Set frame background color
        self.SetBackgroundColour('grey')

        # Create Status Bar
        self.CreateStatusBar()

        # Create the Menu
        menu= wx.Menu()
    
        # Add menu items to the menu and bind those items with event listener
        about = menu.Append(wx.ID_ABOUT, "About", "wxPython Demo")
        self.Bind(wx.EVT_MENU, self.about_, about)
        menu.AppendSeparator()
        exit = menu.Append(wx.ID_EXIT,"Exit"," Exit")
        self.Bind(wx.EVT_MENU, self.exit_, exit)
    
        # Create the menubar
        menuBar = wx.MenuBar()

        # Connect menu to menubar and set the MenuBar title
        menuBar.Append(menu,"File")

        # Connect the menubar to the frame
        self.SetMenuBar(menuBar)
    
        # Display the frame
        self.Show()
    
    # Exit function to close the program
    def exit_(self, e):
        sys.exit(0)
        
    # About function to show the about message
    def about_(self, e):
        wx.MessageBox("This is a wxPython demo...", "wxPython Demo" ,wx.OK | wx.ICON_INFORMATION)


# Create instance of wxPython application
app = wx.App()

# Ceeate the wx.Frame's instance
WXFRAME(None, "wxPython demo", (300,300))

# Run the main GUI event loop
app.MainLoop()

Run the module, click on File->About and see the below outcome…

Select the About item
Select the About item

Next click on (X) Exit to close the program.

As you can see, wxpython has almost all those features provided by tkinter and many more, you can find out how to use all the Phoenix features through this link : https://wxpython.org/Phoenix/docs/html/classic_vs_phoenix.html

How to create windows graphic user interface with tkinter

If we want to create a GUI program in Python 3 then Tkinter seems like the best choice than wxPython because tkinter module has already been included in Python 3 and thus we do not need to download and install an extra module.

This tutorial will show you how to create windows GUI with python’s tkinter module. It is very easy to create a pop up window with tk module. First start up your NetBeans IDE, then create a new project as I have shown you before in my previous tutorial. Next enter below script into the NetBeans code editor and run it!

import tkinter as tk 

win = tk.Tk() # create tk instance
win.title("tkinter GUI") # add a title

win.mainloop() # start the GUI

Basically the above python script will create an empty window with the tkinter module then start the window’s event loop by calling the mainloop method from the tk’s class instance as shown in the following graphic.

tk GUI
tk GUI

Next lets look at another example…

In this article we will create a simple python GUI with the tkinter’s IDLE GUI. With just a few lines of code, we will create a button which when we click on it the GUI will be closed!

import tkinter as tk 
from tkinter import ttk 

win = tk.Tk() 
win.title("Python GUI") 

aLabel = ttk.Label(win, text="Click the button to close") 
aLabel.grid(column=0, row=0) 

def clickMe(): 
    exit(0) #close application

# Adding a Button 
action = ttk.Button(win, text="Click!", command=clickMe) 
action.grid(column=1, row=0) 

win.mainloop() #run the main loop

This is what we got…

Click the button to close the application
Click the button to close the application

Next we’ll create a simple tkinter application that will display all the files in any directory within the application.

As always, we need to import some modules to help us write this program.

import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askdirectory
import tkinter.font as Font
import os

Next is the user interface for creating our ‘file list application’.

win = tk.Tk()
win.title("Listing File")

aLabel = ttk.Label(win, text="   Click the button to list directory items", width=33,
                  font=Font.Font(family="Helvetica", size=13)) # This is where the file list will be shown
aLabel.grid(column=0, row=1)

# The callback function of the button
def clickMe():
    # code will go here later on

# Adding a Button
action = ttk.Button(win, text="List Directory", command=clickMe)  # click on the button to open folder chooser
action.grid(column=0, row=0)

win.mainloop()  # run the main loop

Finally fill in the callback function section with the following code.

# The callback function of the button
def clickMe():

    foldername = askdirectory(title="Select folder") # open a folder selector
    file_string = ''
    fileList =  os.listdir(foldername)  # return a list of files within the directory

    for file in fileList:
        file_string += file + '\n' # create a string of file list

    aLabel.configure(text =  file_string)  # set the text in the label as file list

Now, we can select any folder which we want to display all of the files within it.

The files within any folder
Select any file

There are four files in the above folder!

We will move on by creating another tkinter application in the next tutorial.

How to create a simple text editor with tkinter

Below is the python program I have created with tkinter which allows user to input text into the textbox then saves it in the text file later on.

import tkinter as tk 
from tkinter import ttk 
from tkinter import Text

win = tk.Tk() #create instance
win.title("Write Note") #add a title

def saveFile():
    try:
        with open('note.txt', 'w') as note: #open file
            text = text_entry.get("1.0", 'end-1c') #get text entry
            note.write(text) #write text to file
    except IOError as err:
        print("File error " + str(err))
        
text_entry = Text(win,width=50,height=30) #create text editor
text_entry.grid(column=0, row=0) 

action = ttk.Button(win, text="Save", command=saveFile) #create button
action.grid(column=0, row=1)
action.config(width=66)

text_entry.focus()
win.mainloop() #start GUI

The program above will create a textbox and a button which once you have clicked on it it will call the saveFile() function to save the text into a text file (or creates the text file first if it has not been created yet).

Enter some words then press Save
Enter some words then press Save

Next lets continue with the text editor development tutorial. In the previous part I have created a text box and a save button for my text editor so we can save our work later on, however the previous interface does not look professional so I have decided to change and redo the entire GUI to make it looks better as well as prepared the text editor for the future expansion.

All right, without further talking let get started. I have broken down the python script into small parts to make it easy for you to follow my code.

1) Import a few modules into our new program.

import tkinter as tk 
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import ttk

2) Create the window object.

win = tk.Tk() #create an instance
win.title("Write Word") #add a title

3) Create the label frame to host the checkboxes

labelFrame = ttk.LabelFrame(win, text="Text Property")
labelFrame.grid(column=0, row=2, padx=30, pady=10, sticky=tk.W)

4) Create the checkboxes and hosted them in labelFrame.

#create a few checkboxes
ckValueObj1 = tk.IntVar()
ckValueObj2 = tk.IntVar()
ckValueObj3 = tk.IntVar()

chk1 = tk.Checkbutton(labelFrame, text="Highlight Text", variable=ckValueObj1, command=changeState)
chk1.deselect()
chk1.grid(column=0, row=2, sticky=tk.W)

chk2 = tk.Checkbutton(labelFrame, text="Bold Text", variable=ckValueObj2, command=changeState)
chk2.deselect()
chk2.grid(column=1, row=2, sticky=tk.W)

chk3 = tk.Checkbutton(labelFrame, text="Green Text", variable=ckValueObj3, command=changeState)
chk3.deselect()
chk3.grid(column=2, row=2, sticky=tk.W)

5) Create the function which will be called every time we checked or unchecked any checkbox.

def changeState(): # receive chackbox updates
    
    state1 = ckValueObj1.get() #use this value to highlight the background of the text with yellow color
    state2 = ckValueObj2.get() #use this value to change the text to bold
    state3 = ckValueObj3.get() #use this value to turn the text to green
    
    if state1 == 1: 
        scrollText.tag_add('highlightline', '1.0', 'end-1c')
        scrollText.tag_configure('highlightline', background='yellow', relief='raised')
    else:
        scrollText.tag_remove('highlightline', '1.0', 'end-1c')
        
    if state2 == 1:
        scrollText.tag_add('makebold', '1.0', 'end-1c')
        scrollText.tag_configure('makebold', font='helvetica 12 bold', relief='raised')
    else:
        scrollText.tag_remove('makebold', '1.0', 'end-1c')
    
    if state3 == 1:
        scrollText.tag_add('green', '1.0', 'end-1c')
        scrollText.tag_configure('green', foreground='green', relief='raised')
    else:
        scrollText.tag_remove('green', '1.0', 'end-1c')

6) Create the scroll text editor.

scrolW = 50
scrolH = 10 
scrollText = scrolledtext.ScrolledText(win, width=scrolW, height=scrolH, wrap=tk.WORD)
scrollText.grid(column=0, row= 0, columnspan=3)

7) Create the main menu items.

menuBar = Menu(win) # create menu bar
win.config(menu=menuBar) # attach menubar to window

fileMenu = Menu(menuBar, tearoff=0) # create a menu in the menu bar and remove the default dash line
fileMenu.add_command(label="Save", command=_saveFile) # create the save file sub menu
fileMenu.add_command(label="Exit", command=_closeFile) # create the close file sub menu
menuBar.add_cascade(label="File", menu=fileMenu) # create main menu

8) Create the save file function for the Save item.

def _saveFile(): #save file command
    try:
        with open('note.txt', 'w') as note:
            text = scrollText.get("1.0", 'end-1c') #get text entry
            note.write(text) #write text to file
    except IOError as err:
        print("File error " + str(err))

9) Create exit command for the Exit item.

def _closeFile(): #close file command
    win.quit()
    win.destroy()
    exit()

10) Most of the script above is self-explaining so you should understand them if you know the basic python language. The full code is as follow.

import tkinter as tk 
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import ttk

win = tk.Tk() #create instance
win.title("Write Word") #add a title

def _saveFile(): #save file command
    try:
        with open('note.txt', 'w') as note:
            text = scrollText.get("1.0", 'end-1c') #get text entry
            note.write(text) #write text to file
    except IOError as err:
        print("File error " + str(err))
        
def _closeFile(): #close file command
    win.quit()
    win.destroy()
    exit()
    
def changeState(): # receive chackbox updates
    
    state1 = ckValueObj1.get() #use this value to highlight the background of the text with yellow color
    state2 = ckValueObj2.get() #use this value to change the text to bold
    state3 = ckValueObj3.get() #use this value to turn the text to green
    
    if state1 == 1: 
        scrollText.tag_add('highlightline', '1.0', 'end-1c')
        scrollText.tag_configure('highlightline', background='yellow', relief='raised')
    else:
        scrollText.tag_remove('highlightline', '1.0', 'end-1c')
        
    if state2 == 1:
        scrollText.tag_add('makebold', '1.0', 'end-1c')
        scrollText.tag_configure('makebold', font='helvetica 12 bold', relief='raised')
    else:
        scrollText.tag_remove('makebold', '1.0', 'end-1c')
    
    if state3 == 1:
        scrollText.tag_add('green', '1.0', 'end-1c')
        scrollText.tag_configure('green', foreground='green', relief='raised')
    else:
        scrollText.tag_remove('green', '1.0', 'end-1c')
 
#create label frame to host the checkboxes    
labelFrame = ttk.LabelFrame(win, text="Text Property")
labelFrame.grid(column=0, row=2, padx=30, pady=10, sticky=tk.W)

#create a few checkboxes
ckValueObj1 = tk.IntVar()
ckValueObj2 = tk.IntVar()
ckValueObj3 = tk.IntVar()

chk1 = tk.Checkbutton(labelFrame, text="Highlight Text", variable=ckValueObj1, command=changeState)
chk1.deselect()
chk1.grid(column=0, row=2, sticky=tk.W)

chk2 = tk.Checkbutton(labelFrame, text="Bold Text", variable=ckValueObj2, command=changeState)
chk2.deselect()
chk2.grid(column=1, row=2, sticky=tk.W)

chk3 = tk.Checkbutton(labelFrame, text="Green Text", variable=ckValueObj3, command=changeState)
chk3.deselect()
chk3.grid(column=2, row=2, sticky=tk.W)

# create a scroll text editor
scrolW = 50
scrolH = 10 
scrollText = scrolledtext.ScrolledText(win, width=scrolW, height=scrolH, wrap=tk.WORD)
scrollText.grid(column=0, row= 0, columnspan=3)

# create menu items
menuBar = Menu(win) # create menu bar
win.config(menu=menuBar) # attach menubar to window

fileMenu = Menu(menuBar, tearoff=0) # create a menu in the menu bar and remove the default dash line
fileMenu.add_command(label="Save", command=_saveFile) # create the save file sub menu
fileMenu.add_command(label="Exit", command=_closeFile) # create the close file sub menu
menuBar.add_cascade(label="File", menu=fileMenu) # create main menu

scrollText.focus() #focus on the scroll text editor

win.mainloop() #start GUI

If you run the program now in NetBeans 8.1 IDE then you can check on the checkboxes below the scroll text editor to see various effects that we have included in our python script above.

Text Editor
Text Editor

You can select the save command to save your file in plain text or the exit command to terminate the program under the File’s drop down menu.

Move file from folder to folder with tkinter

In this article we will create a python application which will then help us to move a file from one directory to another. Here are the main modules or ingredients we need for our program.

1) tkinter – for creating ui
2) tkinter.filedialog – for opening file and folder
3) os – for removing old file once it has been moved to a new folder

First of all, lets import those modules we need.

import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
import tkinter.font as Font
from shutil import copyfile
import os
from os.path import basename

Next create the user interface with tkinter module

win = tk.Tk()
win.title("Copy File")

# The callback function of the button
def clickMe():
   # code will goes here

# Adding a Button
action = ttk.Button(win, text="Move File", command=clickMe)  # click on the button to open file chooser
action.grid(column=0, row=0)

win.mainloop()  # run the main loop

The user interface of the application is very simple, just a button and when it gets clicked the file and folder chooser will open up and the file moving process will take place.

# The callback function of the button
def clickMe():

    filename = askopenfilename(title="Select text file")
    foldername = askdirectory(title="Select folder")
    copyfile( filename, os.path.join(foldername, basename(filename)))
    os.remove(filename)
    exit()
Click on the button
Click on the button

Enter above code into the clickMe function which will move the file to a new location.

Next run the application, clicking on the button as shown below then pick a file and the new location to move the file to and that is it!

Open image in python with Pillow

Pillow is a great python module that we can use to open an image on our computer. In this article, we will create a tkinter user interface that will open an image file with the help of the Pillow module.

First, we need to import the modules that we need in our program, such as tkinter and Pillow.

import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
from tkinter.filedialog import askopenfilename

Next, we’ll create a simple tkinter user interface which will be used as the image file opener. We will fill in the callback function later.

win = tk.Tk()
win.title("Load Image")

# The callback function of the button
def clickMe():

# Adding a Button
action = ttk.Button(win, text="Load Image", command=clickMe)  # click on the button to open file chooser
action.grid(column=0, row=0)

win.mainloop()  # run the main loop

Next, fill in the file selector code and image processor code in the clickMe function.

# The callback function of the button
def clickMe():
    filename = askopenfilename(title="Select Image")
    img = Image.open(filename)
    img.show()

The above code will open an image file selector and then displays the selected image as shown below.

Load Image
Load Image Button
The image viewer of windows 10
The image viewer from windows 10

The above is just a short python program but of course we can further include more features, including image resizing and other features if we need to!

Create a text file reader with tkinter

In this tutorial we are going to create a text file reader which will read in words from a file and then shows them under the label of that file reader ui. First of all lets create the ui of the text file reader with the help of tkinter.

import tkinter as tk
from tkinter import ttk
import tkinter.font as Font

win = tk.Tk()
win.title("Text Reader")

aLabel = ttk.Label(win, text="   Click the button to load the greeting!", width=33,
                   font=Font.Font(family="Helvetica", size=13))  # This is where the text will be loaded
aLabel.grid(column=0, row=1)

# The callback function of the button
def clickMe():
   # empty for now

# Adding a Button
action = ttk.Button(win, text="Click!", command=clickMe)  # When the button get clicked the text will be loaded onto the label
action.grid(column=0, row=0)

win.mainloop()  # run the main loop

The above program will create the file reader ui as follows…

The UI of file reader
The UI of file reader

Next add in this import statement so we can use the askopenfilename module to create a file chooser.

from tkinter.filedialog import askopenfilename

Next we need to make thing happen, under the clickMe function add in below code which will open a file chooser so you can pick a file (after you have clicked the above button) for the program to read in that file content and displays them under the label of the file reader.

# The callback function of the button
def clickMe():
    filename = askopenfilename(title = "Select text file")
    fin = open(filename, 'rt')
    sometext = fin.read()
    fin.close()
    aLabel.configure(text=sometext)

After you have clicked the button the file chooser will open, now select a text file from the hard disk to display it’s content onto the label.

The text displays onto the label
The text displays onto the label

That is it for tkinter now lets create a python class.

Lets look at the python class

In this tutorial I am going to show you how to create a class in python and then create an instance object from that class. What we want here is to create a python class which will receive the name, job, salary and a boolean parameter which indicates whether that person has changed his or her job recently or not so the default __str__ method from that class will return different string based on that boolean value. OK let get started.

This time I will use eclipse to write the python script but you can use other IDE such as NetBeans 8.1 as well if you want to, both Eclipse and NetBeans are the top IDE I use to write the python script. Before you can create a python project in Eclipse make sure you have installed the PyDev plugin through Help->Install New Software.

Install PyDev
Install PyDev

If you have not yet installed the PyDev plugin before then click on the Add button and provide a name together with this link http://pydev.org/updates to download and install the PyDev plugin.

Once you have installed the plugin in Eclipse you can now go to File->New->PyDev project and create a new python project just like how you create other project in Eclipse.

I will leave you to create the new project with Eclipse and concentrate on the main topic which is how to create a python class.

After creating a package within that project you can now create a new module calls personaldata.py and enter the below script into it.

class PersonalData(object):

        def __init__(self, name, work, earning = 0, change = False):
            self.name = name
            self.work = work
            self.earning = earning
            self.change = change
        
        def __str__(self):
            if(self.change == False):
                return "%s works as a %s and he has a monthly income of %s" % (self.name, self.work, self.earning)
            else:
                return "%s now works as a %s and he has a monthly income of %s" % (self.name, self.work, self.earning)
        
        def changeJob(self, work, income, change = False):
            self.work = work
            self.earning = income
            self.change = change

Every python class needs to have an __init__ method where self is the first parameter which will be automatically passed into the method, self is very important because the instance of that class will use this parameter to call a method or to access a variable of that object.

The rest of the parameters will be passed in at the time you create a new instance of that class. You can also set the default value for each parameter so that instance can use any of those values if any of those values has not been passed into the class at the time you create an instance of that class. The same goes to the class’s method as well.

Now let us create the main python module which will include the PersonalData’s class instance in it. Let create a new python module and name it runmyclass.py. Now you should see those two python modules under the same package.

Folder Tree
Folder Tree

Next enter below script into the runmyclass.py module…

from personaldata import PersonalData

if __name__ == '__main__':
    
    personalData = PersonalData("John", "computer programmer","1000")
    print (personalData)
    personalData.changeJob("project manager", "3000", True)
    print (personalData)

As you can see you will need to import the PersonalData class into this module before you can use it.

If you want to run any python module then you will need this line of statement,

if __name__ == ‘__main__’

make sure you do that.

Next let create an instance of the PersonalData class and enter the second, third and fourth parameter into it, you do not need to enter the fifth parameter if you don’t want to because it already has a default boolean value which is False.

Now you can call the print method and pass in that new instance, what will happen here is this instance will call it’s own __str__ method and return a string based on the boolean value you have passed in, in this example when we first create the new instance Mr. John has not changed his job yet so change = False.  We can overwrite the __str__ method and return any string that we wish to in this program.

We then call the changeJob method and pass three parameters into that method, the last one will be used as the boolean value to decide which string should we return this time.

The program above will produce the below output.

Python Class Demo
Python Class Demo

That is it for this tutorial, as you can see creating class in python is not that hard after all, right?

Next we will create a python inner class.

Python allows us to create an inner class within a python class just like how we create any ordinary class.

In following example I have created a new class within the PersonalData class which I have created before so that new class will behave like a list which allows us to insert the previous job history of an employee into it so we can retrieve them later on.

class JobHistory(list):
        
        def __init__(self):
            list.__init__([])

As you can see we make that inner class extends the list class so it behaves just like a list. Now we can use it just like any other class by initiating that inner class and then inserted job history of an employee into it in the runmyclass.py module.

personalData = PersonalData("John", "computer programmer","1000") #create an instance of the PersonalData class
job_history = personalData.JobHistory() #create an instance of the JobHistory inner class
job_history.append('python programmer') #append history to the list
job_history.append('web developer')
job_history.append('android developer')

Print out the job history is also very simple.

print ("Before this " + personalData.name + " is a : ")
    print("")
    for job in job_history:
        print(job)

The outcome for the entire program is as follow:

John works as a computer programmer and he has a monthly income of 1000
John now works as a project manager and he has a monthly income of 3000
Before this John is a :

python programmer
web developer
android developer

Now lets create many classes within a same python module. Besides creating a class within another class we can also create many classes within the same python module. Let us take a look at how to create a python module with many classes in it.

Start a new Eclipse’s project as before then create this module :- doubleclassdemo.py and input below python script into it.

class FirstClass(object):
    
    def __init__(self, welcome = "welcome to first class server!"):
        print(welcome)
        
class SecondClass(object):

    def __init__(self, welcome = "welcome to the second class server!"):
        print(welcome)

As you can see we have created two classes in one module. Next create another python module and name it mainserver.py then enter below script into it.

import doubleclassdemo 

if __name__ == '__main__':
    print(doubleclassdemo.FirstClass())
    print(doubleclassdemo.SecondClass())

Run the mainserver.py module.

As you can see we have imported the doubleclassdemo module into this module and then create a new instance for both classes within the doubleclassdemo module inside that print method which will first call the __init__ method of each class to print out the welcome message and then will call the __str__ method to return the memory address of each class and print it out!

welcome to first class server!
<doubleclassdemo.FirstClass object at 0x00FE5C10>
welcome to the second class server!
<doubleclassdemo.SecondClass object at 0x00FE5C10>

Do you realize that both classes do share the same memory address? Hmmm…interesting.

Create a sqlite table then fill in the data

In this tutorial we will first create a sqlite table and then populated that table with few rows of data. In order to create a sqlite table we need to import the sqlite3 module into our python program. The good thing about this module is that it has already been included in python so we do not need to download it separately into our python package.

Alright, without wasting any time let get started. I am using Eclipse to create this next python project, let us create a new PyDev project in Eclipse. If you have read my previous tutorial before then you should know that we need to install the PyDev plugin in order for us to create and run our python project in Eclipse, so if you have not yet installed the plugin just go ahead and do so.

After you have installed the PyDev plugin then go ahead and follow the following instruction to create and populate the sqlite table with data.

1) Before you create this new project you will need to create the MyClassDemo project first because we will need to use it’s PersonalData class in this tutorial. You can refer to this project under the class tutorial which is above this tutorial.

2) After you have created the MyClassDemo project you can now create a new SqliteDemo project with PyDev through File->New->PyDev Project.

Fill in the project detail
Fill in the project detail
check the MyClassDemo project
Check the MyClassDemo project, you will need it to import the personaldata.py module into the SqliteDemo project

3) Next create a new package under the SqliteDemo project’s src folder through right click on the project folder->New->PyDev package.

Fill in the package name then click Finish
Fill in the package name then click Finish

3) Then create the insertEmployeeData.py module under the SqliteDemo package through right click on the package->New->PyDev Module

Fill in module name then click Finish
Fill in the module name then click Finish
Select Module Main
Select Module Main

4) Now your project should have the following file structure.

Project File Structure
Project File Structure

5) Next double click on the insertEmployeeData.py module to open it up in the code editor window.

6) In the editor window, enter the below script to import the PersonalData class from the MyClassDemo project into the insertEmployeeData.py module.

from os import path
import sys
sys.path.append(path.abspath('../MyClassDemo')) #let Eclipse knows where to find the MyClassDemo project path

from MyClass.personaldata import PersonalData 

7) Continue entering the below script under if __name__ == ‘__main__’: to gather the data of that particular employee and then create a new employee object from the PersonalData class and populate it with name, job and salary of that particular employee.

if __name__ == '__main__':
    
    name = input("Enter Employee Name")
    job = input("Enter Employee Job")
    salary = input("Enter Employee Salary")
    
    employeeObject = PersonalData(name, job, salary)

8) Next at the top of the insertEmployeeData.py module import the sqlite3 module into our program as well as provide a new name for our new sqlite3 database.

import sqlite3
db_name = 'employeedata.sqlite'

9) Now create our employee table in the employeedata.sqlite database

# connect to the employeedata.sqlite database, if the database is not there yet then create it
connection = sqlite3.connect('employeedata.sqlite')
cursor = connection.cursor()

# retrieve the employee table name which we have created
cursor.execute("""SELECT name FROM sqlite_sequence WHERE name='employee'""")
name_is_there = cursor.fetchone()[0]


# if the employee table has not been created yet then we shall create it
if name_is_there != 'employee':
    cursor.execute("""CREATE TABLE employee (
                    id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,
                    name TEXT NOT NULL,
                    job  TEXT NOT NULL,
                    salary TEXT NOT NULL) """)

10) Insert the data we have gathered at the beginning of the program into the employee table.

cursor.execute("INSERT INTO employee (name, job, salary) VALUES (?, ?, ?)", (employeeObject.name, employeeObject.work, employeeObject.earning)) # insert data into the employee table
connection.commit()
connection.close() #close the connection

11) Now run the above program (on the Eclipse’s console) and entering those information when the program asks you to do so, press the enter key on your keyboard after each answer!

Eclipse Console
Eclipse Console

12) There should be a employeedata.sqlite database file in your src folder at this moment.

employeedata.sqlite
employeedata.sqlite

13) Open it up, do you see this?

sqlite3
sqlite3

14) As you can see the file above is not meant for human to read it. We need a software which can read those information we have inserted into the employee table. Go ahead and download this powerful db browser from http://sqlitebrowser.org and then open it up once you have downloaded and installed it on your pc.

15) Now open up the sqlitebrowser then load the sqlite database you have just created through File->Open DataBase. Under the Database Structure tab there are two tables, 1) the sqlite_sequence table is use to keep all the tables of the employeedata.sqlite database, 2) the employee table is the one which we have just created.

Open the database
Open the database

16) Switch to the Browse Data tab and select the employee table under the drop down list, you should now see the data that we have inserted into this table.

The are two John here...
The are two John here…

Do you realize that there are two persons with the same name “John” in the employee table? As you can see the only data which is unique in our table is the id and the rest of the field can consist of the same repeated value because we have programmed the table in such a way.

17) There are lots of thing you can do with sqlitebrowser besides the above mentioned feature, for example you can learn sql by directly entering the sql command into the console as shown below.

Enter SQL command here
Enter SQL command here

Here is the complete script for the insertEmployeeData.py module

import sqlite3
db_name = 'employeedata.sqlite'

from os import path
import sys
sys.path.append(path.abspath('../MyClassDemo')) #let Eclipse knows where to find MyClassDemo project path

from MyClass.personaldata import PersonalData 

if __name__ == '__main__':
    
    name = input("Enter Employee Name")
    job = input("Enter Employee Job")
    salary = input("Enter Employee Salary")
    
    employeeObject = PersonalData(name, job, salary)
    
    # connect to the employeedata.sqlite database, if the database is not there yet then create it
    connection = sqlite3.connect('employeedata.sqlite')
    cursor = connection.cursor()
    
    # retrieve the employee table name which we have created
    cursor.execute("""SELECT name FROM sqlite_sequence WHERE name='employee'""")
    name_is_there = cursor.fetchone()[0]
    
    # if the employee table has not been created yet then we shall create it
    if name_is_there != 'employee':
        cursor.execute("""CREATE TABLE employee (
                        id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,
                        name TEXT NOT NULL,
                        job  TEXT NOT NULL,
                        salary TEXT NOT NULL) """)
        
    cursor.execute("INSERT INTO employee (name, job, salary) VALUES (?, ?, ?)", (employeeObject.name, employeeObject.work, employeeObject.earning)) # insert data into the employee table
    connection.commit()
    connection.close()

Iterate through array list in Python

Let see how we can iterate through an array list in Python.

There are two method we can use to iterate through a list in Python, we can either use the while loop or the for loop. First I am going to show you how to do it with the while loop.

 hello = ["Hello", "World", "!"]
 count = 0
 while(count < len(hello)):
     print(hello[count])
     count += 1

Use the while loop to iterate requires we to create an extra counter which is ‘count’ in this example.

Now lets take a look at the for loop.

 hello = ["Hello", "World", "!"]
 for item in hello:
     print(item)

The above for loop will produce the same outcome

Hello
World
!

but there is no counter involves in the for loop. Therefore I would have preferred to use the for loop instead of the while loop unless for some special reason not to use it.

If you are using NetBeans IDE 8.1 then the complete code for this program is as follow:

if __name__ == "__main__":
    hello = ["Hello", "World", "!"]
    for item in hello:
        print(item)

Also notice that the python’s build in function print method will print each item in the list in a new line, if you want to print it in one single line then you can use below program instead.

if __name__ == "__main__":
    hello = ["Hello", "World", "!"]
    hello_string = ""
    for item in hello:
        hello_string += item + " "
    print(hello_string)

How to distribute the python software for windows 10?

This article will show you how to distribute your python software for windows 10 after you have finished creating it. In order to distribute the software written in python to the windows 10 platform’s users all you need to do is to use a python module known as PyInstaller which will help you to turn the python script into an executable application which can then be used on the windows 10 platform.

Before you can use the pyinstaller module you will need to download and install the PyInstaller module first, open up the windows command prompt and type in this command : pip install pyinstaller to install the PyInstaller module into the site-packages folder.

After you have installed the pyinstaller module then all you need to do is to browse to the folder where you have saved your python program and then run the below command in the windows command prompt.

pyinstaller firstpythonproject.py

where firstpythonproject.py is the python program which you wish to turn into an application.

Once pyinstaller has finished it’s job you should find a few folders together with your original python script and a spec file under that same folder.

open up the dist folder
open up the dist folder

Under the dist folder you will find another folder with the same name as your python script and in this folder you will find an application file which you can then double click and open it up just like any other ordinary software which runs on windows 10.

After you have started your application you will see a console window at it’s background, in order to get rid of that console you will need to do one simple change within the firstpythonproject.spec file. Open up the firstpythonproject.spec file and then change the console value from True to False within the EXE module.

exe = EXE(pyz,
          a.scripts,
          exclude_binaries=True,
          name='firstpythonproject',
          debug=False,
          strip=False,
          upx=True,
          console=False )

After that run this command in the windows command prompt : pyinstaller firstpythonproject.spec to regenerate all the contents within the dist directory. Now go into the dist directory again and double click on the application file to start the program without the console at it’s background.

This time no more console
This time no more console

If you want to distribute your application now then all you need to do is to upload the entire firstpythonproject folder (or zip it up) to your website so people can download it and open up the application file by double clicking on it! Although there are other tools that you can use to pack up your software but PyInstaller is the best according to my humble opinion because it is so easy to use as compared to the others!

Now lets look at a few python program examples before we get to the networking.

Remove the smallest number from the list and use python to get the sum of the two smallest numbers in the list

Below are two python programs that will remove the smallest number in the list and return the sum of the two smallest numbers in the list.

The first program will remove the first occurrence of the smallest number from the list and return to the new list, and delete the first occurrence of the smallest number, the original list will remain unchanged.

def remove_smallest(numbers):
    minimum = min(numbers) # first we get the smallest number in the list
    listnumber = numbers[0:] # we then create a new list from existing list so we can change the new list value 
    index = numbers.index(minimum) # this will return the index of the first occurrence of the minimum value
    del listnumber[index] # next we delete the first occurrence of the minimum value from the new list
    return  listnumber # return the new list with the first occurrence of the minimum value get removed

The above program will only remove the first occurrence of the smallest number from the list, so if you pass in these values ​​[1,2,4,6,1,8,1] in the list, then only the first number Will be deleted, and the rest of 1 will not, and the return list will change to [2,4,6,1,8,1].

The second program will return the sum of the two minimum values ​​in the list.

def sum_smallest(numbers):

    minimun1 = min(numbers) # first we get the first minimum number
    index = numbers.index(minimun1) # find the index of that minimum number and delete that number from the list
    del numbers[index]
    minimun2 = min(numbers) # get the second smallest number after the first

    return  (minimun1 + minimun2) # return the sum

The strategy here is to remove the smallest number from the list after getting its value and then find the next smallest number from the list.

Calculate the years required for bank investment returns

This simple python program will help you to calculate the number of years you need to get a return for your investment in the bank. This python program can be used in other investment examples and can be modified slightly if needed.

def calculate_years(principal, interest, tax, desired):
    total = principal
    year = 0
    while (total < desired):
        total = total + (total * interest * (1 - tax)) # tax only applies on interest
        year += 1
    return  year

print(calculate_years(1000, 0.05, 0.18, 1100))

Assuming you have initially deposited $1,000 in a bank and you need to pay a tax of 0.18% on the interest paid by the bank each year and the total savings after tax deduction will continue to invest in the same bank. If you are looking for a return on investment of $100 after the tax, then in the above example you will need 3 years to get there.

Find words or phrases without duplicate letters with python

In the python program below, we will create a function that returns true if the word or phrase has no duplicated letter in it, and false if it does.

def is_isogram(string):
    alphabetlist = ["a", 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    count = 0
    liststring = list(string)

    if(string == ''):
        return True

    for char in alphabetlist:
        for word in liststring:
            if(char == word.lower()):
                count += 1
                if(count > 1):
                    return False
        count = 0

    return True

If you enter the following string in the function, you will get True.

print(is_isogram("helo j m")) // True

But if you pass the phrase below, you will get false.

print(is_isogram("Hello World")) // False

Create networking with ZeroMQ sockets

ZeroMQ sockets is another great python networking module which you can use for the communication between client and server program. In this article we will write a client side program and a server side program and make them communicate with each other with the help of ZeroMQ sockets. First of all, ZeroMQ socket module does not come with the Python3 package so you will need to install it through the command line as usual.

pip install pyzmq

Once you have done that let start to create the client server with below code.

import zmq
host = '127.0.0.1'
port = 6999
context = zmq.Context()
server = context.socket(zmq.REP)
server.bind("tcp://%s:%s" % (host, port))

# Let the server runs forever
while True:
	request_bytes = server.recv()
	request_str = request_bytes.decode('utf-8')
	reply_str = "Nice to meet you %s" % request_str
	reply_bytes = bytes(reply_str, 'utf-8')
	server.send(reply_bytes)

Don’t use ‘localhost’ for the host name, you need to provide the ip address instead.

Start the above program.

server program
server program

Next create the client program.

import zmq
host = '127.0.0.1'
port = 6999
context = zmq.Context()
client = context.socket(zmq.REQ)
client.connect("tcp://%s:%s" % (host, port))

print("Hi my name is James")
request_str = "JAMES" 
request_bytes = request_str.encode('utf-8')
client.send(request_bytes)
reply_bytes = client.recv()
reply_str = reply_bytes.decode('utf-8')
print("Server said : %s" % (reply_str))

Start the client program.

client program

Basically the server program will receive a name from the client program and then sends the message back to the client, ZeroMQ can communicate with many clients one after another which is what the word Q means.

Create a server client network with python socket module

In this python networking example We will create the client and server program with the socket module and make them communicate with each other. The client will send two numbers in a UDP datagram to a server and the server returns a packet of data containing the total of that two numbers. In order for the communication to successes the server needs to listen at a particular address and port and the client needs to know these two values in order to deliver its message and receive the answer from the server.

In the following client and server code, address is in a tuple of (address, port). The address will consist of a string which can be a name or an IP address. When your programs are just talking to one another on the same machine, you can use the name ‘localhost’ or the equivalent address ‘127.0.0.1’. You can select the port which normally will range from 6000 to 6999. Since this is just an example any port will do. For more information about the port visit this site to learn more.

Now let’s create two program, the first program is the client which will ask for the sum of two values by sending those values to the server and the second is the server which will return the answer to the client. In each program, we’ll print the time and open a socket. The server will listen for connections to its socket, and the client will write to its socket, which transmits a message to the server.

The first program is the server program.

from datetime import datetime
import socket

server_address = ('localhost', 6888)
max_size = 4096

print('Starting the server at', datetime.now())
print('Waiting for a client to call.')

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(server_address)
data, client = server.recvfrom(max_size)

print('At', datetime.now(), client, ' wants to know the sum of these two numbers ', data)

num1, num2 = data.decode("utf-8").split(',')
total = int(num1) + int(num2)
sum = "The total sum is " + str(total)

server.sendto(sum.encode(), client)
server.close()

We will start the server first, open a command prompt window and start that python file.

server side
server side

Next we will create a client side program.

import socket
from datetime import datetime

server_address = ('localhost', 6888)
max_size = 4096

print('Starting the client at', datetime.now())
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(b'20,60', server_address)

data, server = client.recvfrom(max_size)
print('At', datetime.now(), server, 'said', data)
client.close()

Now start the program in a new command prompt window and you will get the answer to your question. As you can see the computer will automatically assign the ip address and the port number to the client side so we do not need to do anything with it.

client side
client side

UDP sends data in single chunks and it does not guarantee delivery but since this is just an example and we are sending the message only to our local computer then it is alright!

The Python Multiprocessing and JoinableQueue example

This simple example will use the Python Multiprocessing and JoinableQueue modules to withdraw money from your bank account. Queue module is very useful when it combines with the Multiprocessing module to create a communication pipeline between the input and output. You can further read about it through this thread.

Below is the withdrawing example using both the modules mentioned above.

import multiprocessing as mp

def withdraw(amounts_withdraw, output):
	print('Start withdrawing...')
	for amount in amounts_withdraw:
		print('Withdrawing ', amount)
		output.put(amount)

def saving(input):
	saving = 10000
	while True:
		amount = input.get()
		saving = saving - amount
		print('Account balance ', saving)
		input.task_done()

if __name__ == "__main__":

	withdraw_queue = mp.JoinableQueue()
	withdraw_process = mp.Process(target=saving, args=(withdraw_queue,))
	withdraw_process.daemon = True
	withdraw_process.start()

	amounts_withdraw = [1000, 2000, 3000, 4000]
	withdraw(amounts_withdraw, withdraw_queue)
	withdraw_queue.join()

The example above will produce below outcome…

multiprocessing
multiprocessing

Compare the total occurrence of two characters from a string

In this short example we are going to compare the total occurrence of two characters from a string using python program. If the total occurrence of those two characters is the same then the program will return true, otherwise return false. You also need to return true if there is no such two characters in that string.

The original question is asking us to compare the total occurrence of both x and o character but I have modified it so we can compare any two characters as we wish to. We also need to make sure we can compare the total occurrence of those characters regardless of lower or uppercase character.

def xo(s, ch1, ch2):
    x = 0
    o = 0
    for char in s:
        character = char.lower()
        if(character == ch1):
            x += 1
        elif(character == ch2):
            o += 1
    if(x == o or x == 0 or o == 0):
        return True
    else:
        return False

print(xo('hxelloOx', 'x', 'o')) # the parameters are, the string, the first and the second character

Enter the above code into Visual Studio Code IDE or any of your favorite IDE and run it!

Return the position of the string’s characters from the character list with python

Here is one of the python code challenge question from a website: You need to find what is the position of each character in a string from a character list and then return that entire character positions in a single string with space between each character position excepts the last one. You need to ignore all those characters that are not in the character list which is consists of the character from a-z.

The game plan :

First we need to declare the list of a-z characters in a list.

alphabetlist = ["a", 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

Next create a loop which will loop though each character in the string and find the position of each character in the character list above, if the character is not in the list then just skip the iteration and goes to the next one. We need to make sure the character has been converted to lowercase before the search begins as well as add 1 to the return index which will contain zero (we want our index to start at 1 instead of 0).

for ch in text:
        if(ch.lower() not in alphabetlist):
            continue
        else:
            ch = ch.lower()
            letterpos += str(alphabetlist.index(ch) + 1) + " "

Finally return the string of character positions and don’t forget to truncate the space at the end of the string. The full code is as follow:

def alphabet_position(text):
    if(len(text) == 0): # if the text is blank then return it
        return text

    alphabetlist = ["a", 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

    letterpos = ''
   
    for ch in text:
        if(ch.lower() not in alphabetlist):
            continue
        else:
            ch = ch.lower()
            letterpos += str(alphabetlist.index(ch) + 1) + " "
           
    return letterpos.rstrip()

Now we can call the function above with string parameter to see the outcome.

print(alphabet_position("Hello World!")) 

Copy the code above to Visual Studio Code and run the program by yourself to see the output!

Find the sum of all the numbers between two integer including themselves

Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including themselves and return the total. If the two numbers are equal return a or b.

Note: a and b are not ordered!

As you can see the question above is really tricky and here is the answer to the above question:

def sum(a, b):
    agreat = False # is a greater than b?
    numberlist = [a, b]
    diff = 0 # this is for the loop control

    if(a > b):
        diff = a -b
        agreat = True
    elif(b > a):
        diff = b - a
        agreat = False
    else:
        return a

    i = 1
    sum = 0
    nextnumber = 0

    firstloop = False # we need to check whether is it first time looping or not

    while(i < diff):

        if(agreat == True):
            if(firstloop == False):
                numberlist.append(b+1)
                nextnumber = b + 1
                firstloop = True
            else:
                numberlist.append(nextnumber+1)
                nextnumber += 1
        elif(agreat == False):
            if(firstloop == False):
                numberlist.append(a+1)
                nextnumber = a + 1
                firstloop = True
            else:
                numberlist.append(nextnumber+1)
                nextnumber += 1
        i += 1

    for number in numberlist:
        sum += number # finally sum up all those numbers
    
    return sum

This program is done in a quick manner therefore there are still possible to further shorthorn the solution. Go ahead and enter your own code in the comment box below. :0

Phew that is basically it, if you spot some words error within this post do let me know because it is not simple to joint all my posts together to create this single post. Also don’t forget to click on the star rating below to rate my article.

Our Reader Score
[Total: 0 Average: 0]
Our Own Score
0

Leave a Reply

avatar
  Subscribe  
Notify of