python logo


Tag: python

Introduction

Welcome to my Python Course! 

Python is a general-purpose computer programming language.
This course is suitable for both Python 2 and Python 3.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Download Python


To run Python code, you will need one of these programs:


For terminal only: Apple Mac OS X, Microsoft Windows, Linux/UNIX

<caption id=”attachment_3478” align=”alignnone” width=”300”]pycharm PyCharm, a popular Python editor

Run Python code


A python program should be save as a file with a .py extension.
Try this code:

print("Hello World!")
print("This is a Python program.")

Expected output:

Hello World!
This is a Python program

If you are using the interpreter use:

python program.py

Python strings

python-string a string, series of characters

A string is a series of characters, they are mostly used to display text.

To define a string simply type text between quotes. Python accepts single, double and triple quotes.

Related Course:
Python Programming Bootcamp: Go from zero to hero

String input and output


To output text (string) to the screen:

s = "hello world"
print(s)

To get text from keyboard:


name = input("Enter name: ")
print(name)

If you use an old Python version (2.x), you need to use:


name = raw_input("Enter name: ")
print(name)

To test your version:
python –version

String Comparison


To test if two strings are equal use the equality operator (==).

#!/usr/bin/python

sentence = "The cat is brown"
q = "cat"

if q == sentence:
print('strings equal')

To test if two strings are not equal use the inequality operator (!=)

#!/usr/bin/python

sentence = "The cat is brown"
q = "cat"

if q != sentence:
print('strings equal')

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

Python variables

python-variables
Variables in Python (x,y,z). They can be used later in the program

Variables can hold numbers that you can use one or more times.

Numbers can be of one of these datatypes:


  • integer (1,2,3,4)

  • float (numbers behind the dot)

  • boolean (True or False)


Related Course:
Python Programming Bootcamp: Go from zero to hero

Numeric variables example


Example of numeric variables:

x = 1
y = 1.234
z = True

You can output them to the screen using the print() function.

x = 1
y = 1.234
z = True

print(x)
print(y)
print(z)

Python supports arithmetic operations like addition (+), multiplication (*), division (/) and subtractions (-).

#!/usr/bin/env python

x = 3
y = 8

sum = x + y

print(sum)

More mathematical operations

User input


Python 3
Use the input() function to get text input, convert to a number using int() or float().

#!/usr/bin/env python

x = int(input("Enter x:"))
y = int(input("Enter y:"))

sum = x + y
print(sum)

Python 2 (old version)
You can also ask the user for input using the raw_input function:

#!/usr/bin/env python

x = int(raw_input("Enter x:"))
y = int(raw_input("Enter y:"))

sum = x + y
print(sum)

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

Functions in Python

A function is reusable code that can be called anywhere in your program. Functions improve readability of your code: it’s easier for someone to understand code using functions instead of long lists of instructions.

On top of that, functions can be reused or modified which also improve testability and extensibility.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Function definition


We use this syntax to define as function:

def function(parameters):
instructions
return value

The def keyword tells Python we have a piece of reusable code (A function). A program can have many functions.

Practical Example


We can call the function using function(parameters).

#!/usr/bin/python

def f(x):
return(x*x)

print(f(3))

Output:

9

The function has one parameter, x. The return value is the value the function returns. Not all functions have to return something.

Parameters


 We can pass multiple variables:

#!/usr/bin/python

def f(x,y):
print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
print('x * y = ' + str(x*y))

f(3,2)

Output:


You called f(x,y) with the value x = 3 and y = 2
x * y = 6

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

Python Database Programming: SQLite (tutorial)

In this tutorial you will learn how to use the SQLite database management system with Python. You will learn how to use SQLite, SQL queries, RDBMS and more of this cool stuff!

Related course: Master SQL Databases with Python

Pyton Database

Python Database Python Database.
Data is retrieved from a database system using the SQL language. Data is everywhere and software applications use that. Data is either in memory, files or databases.

Python has bindings for many database systems including MySQL, Postregsql, Oracle, Microsoft SQL Server and Maria DB.

One of these database management systems (DBMS) is called SQLite. SQLite was created in the year 2000 and is one of the many management systems in the database zoo.

SQL is a special-purpose programming language designed for managing data held in a databases. The language has been around since 1986 and is worth learning. The is an old funny video about SQL

SQLite


SQLite SQLite, a relational database management system. SQLite is the most widely deployed SQL database engine in the world. The source code for SQLite is in the public domain.

It is a self-contained, serverless, zero-configuration, transactional SQL database engine. The SQLite project is sponsored by Bloomberg and Mozilla.

Install SQLite:

Use this command to install SQLite:

$ sudo apt-get install sqlite


Verify if it is correctly installed. Copy this program and save it as test1.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

con = None

try:
    con = lite.connect('test.db')
    cur = con.cursor()  
    cur.execute('SELECT SQLITE_VERSION()')
    data = cur.fetchone()
    print "SQLite version: %s" % data                
except lite.Error, e:   
    print "Error %s:" % e.args[0]
    sys.exit(1)
finally:    
    if con:
        con.close()


Execute with:
$ python test1.py

It should output:
SQLite version: 3.8.2


What did the script above do?
The script connected to a new database called test.db with this line:

con = lite.connect('test.db')

It then queries the database management system with the command

SELECT SQLITE_VERSION()


which in turn returned its version number. That line is known as an SQL query.

Related course: Master SQL Databases with Python

SQL Create and Insert


The script below will store data into a new database called user.db

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

con = lite.connect('user.db')

with con:

cur = con.cursor()
cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")
cur.execute("INSERT INTO Users VALUES(1,'Michelle')")
cur.execute("INSERT INTO Users VALUES(2,'Sonya')")
cur.execute("INSERT INTO Users VALUES(3,'Greg')")


SQLite is a database management system that uses tables. These tables can have relations with other tables: it’s called relational database management system or RDBMS. The table defines the structure of the data and can hold the data. A database can hold many different tables. The table gets created using the command:

cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")

We add records into the table with these commands:
cur.execute("INSERT INTO Users VALUES(2,'Sonya')")
cur.execute("INSERT INTO Users VALUES(3,'Greg')")


The first value is the ID. The second value is the name. Once we run the script the data gets inserted into the database table Users:

SQL Table SQL Table

SQLite query data


We can explore the database using two methods: the command line and a graphical interface.

From console: To explore using the command line type these commands:

sqlite3 user.db
.tables
SELECT * FROM Users;

This will output the data in the table Users.

sqlite&gt; SELECT * FROM Users;
1|Michelle
2|Sonya
3|Greg

From GUI: If you want to use a GUI instead, there is a lot of choice. Personally I picked sqllite-man but there are many others. We install using:

sudo apt-get install sqliteman

We start the application sqliteman. A gui pops up.

sqliteman sqliteman

Press File > Open > user.db. It appears like not much has changed, do not worry, this is just the user interface. On the left is a small tree view, press Tables > users. The full table including all records will be showing now.

sqliteman sqliteman

This GUI can be used to modify the records (data) in the table and to add new tables.

Related course: Master SQL Databases with Python

The SQL database query language


SQL has many commands to interact with the database. You can try the commands below from the command line or from the GUI:

sqlite3 user.db 
SELECT * FROM Users;
SELECT count(*) FROM Users;
SELECT name FROM Users;
SELECT * FROM Users WHERE id = 2;
DELETE FROM Users WHERE id = 6;

We can use those queries in a Python program:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys


con = lite.connect('user.db')

with con:

cur = con.cursor()
cur.execute("SELECT * FROM Users")

rows = cur.fetchall()

for row in rows:
print row

This will output all data in the Users table from the database:

$ python get.py 
(1, u'Michelle')
(2, u'Sonya')
(3, u'Greg')

Creating a user information database

We can structure our data across multiple tables. This keeps our data structured, fast and organized. If we would have a single table to store everything, we would quickly have a big chaotic mess. What we will do is create multiple tables and use them in a combination. We create two tables:

Users:

SQL Table SQL Table

Jobs:

SQL Table SQL Table

To create these tables, you can do that by hand in the GUI or use the script below:

# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

con = lite.connect('system.db')

with con:

cur = con.cursor()
cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")
cur.execute("INSERT INTO Users VALUES(1,'Michelle')")
cur.execute("INSERT INTO Users VALUES(2,'Howard')")
cur.execute("INSERT INTO Users VALUES(3,'Greg')")

cur.execute("CREATE TABLE Jobs(Id INT, Uid INT, Profession TEXT)")
cur.execute("INSERT INTO Jobs VALUES(1,1,'Scientist')")
cur.execute("INSERT INTO Jobs VALUES(2,2,'Marketeer')")
cur.execute("INSERT INTO Jobs VALUES(3,3,'Developer')")

The jobs table has an extra parameter, Uid. We use that to connect the two tables in an SQL query:

SELECT users.name, jobs.profession FROM jobs INNER JOIN users ON users.ID = jobs.uid

You can incorporate that SQL query in a Python script:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys


con = lite.connect('system.db')

with con:

cur = con.cursor()
cur.execute("SELECT users.name, jobs.profession FROM jobs INNER JOIN users ON users.ID = jobs.uid")

rows = cur.fetchall()

for row in rows:
print row

It should output:

$ python get2.py
(u'Michelle', u'Scientist')
(u'Howard', u'Marketeer')
(u'Greg', u'Developer')

You may like: Databases and data analysis

Matplotlib Bar chart

Matplotlib may be used to create bar charts. You might like the Matplotlib gallery.

Matplotlib is a python library for visualizing data. You can use it to create bar charts in python. Installation of matplot is on pypi, so just use pip: pip install matplotlib

The course below is all about data visualization:

Related course:
Data Visualization with Matplotlib and Python

Bar chart code

A bar chart shows values as vertical bars, where the position of each bar indicates the value it represents. matplot aims to make it as easy as possible to turn data into Bar Charts.

A bar chart in matplotlib made from python code. The code below creates a bar chart:

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = ('Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp')
y_pos = np.arange(len(objects))
performance = [10,8,6,4,2,1]

plt.bar(y_pos, performance, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel('Usage')
plt.title('Programming language usage')

plt.show()

Output:

figure_barchart Python Bar Chart

Matplotlib charts can be horizontal, to create a horizontal bar chart:

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = ('Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp')
y_pos = np.arange(len(objects))
performance = [10,8,6,4,2,1]

plt.barh(y_pos, performance, align='center', alpha=0.5)
plt.yticks(y_pos, objects)
plt.xlabel('Usage')
plt.title('Programming language usage')

plt.show()

Output:

Bar chart horizontal Bar chart horizontal

Bar chart comparison

You can compare two data series using this Matplotlib code:

import numpy as np
import matplotlib.pyplot as plt

# data to plot
n_groups = 4
means_frank = (90, 55, 40, 65)
means_guido = (85, 62, 54, 20)

# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8

rects1 = plt.bar(index, means_frank, bar_width,
alpha=opacity,
color='b',
label='Frank')

rects2 = plt.bar(index + bar_width, means_guido, bar_width,
alpha=opacity,
color='g',
label='Guido')

plt.xlabel('Person')
plt.ylabel('Scores')
plt.title('Scores by person')
plt.xticks(index + bar_width, ('A', 'B', 'C', 'D'))
plt.legend()

plt.tight_layout()
plt.show()

Output:

barchart_python Python Bar Chart comparison

Stacked bar chart

The example below creates a stacked bar chart with Matplotlib. Stacked bar plots show diffrent groups together.

# load matplotlib
import matplotlib.pyplot as plt

# data set
x = ['A', 'B', 'C', 'D']
y1 = [100, 120, 110, 130]
y2 = [120, 125, 115, 125]

# plot stacked bar chart
plt.bar(x, y1, color='g')
plt.bar(x, y2, bottom=y1, color='y')
plt.show()

Output:

stacked bar chart

Download All Matplotlib Examples

 

Matplotlib Pie chart

Matplotlib supports pie charts using the pie() function. You might like the Matplotlib gallery.

The matplotlib module can be used to create all kinds of plots and charts with Python. A pie chart is one of the charts it can create, but it is one of the many.

Related course: Data Visualization with Matplotlib and Python

Matplotlib pie chart

First import plt from the matplotlib module with the line import matplotlib.pyplot as plt
Then you can use the method plt.pie() to create a plot.

The code below creates a pie chart:

import matplotlib.pyplot as plt

# Data to plot
labels = 'Python', 'C++', 'Ruby', 'Java'
sizes = [215, 130, 245, 210]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0) # explode 1st slice

# Plot
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)

plt.axis('equal')
plt.show()

The above code has the following output:

pie chart python pie chart python

You can define it’s sizes, which parts should explode (distance from center), which labels it should have and which colors it should have.

plt.pie(sizes, explode=explode, labels=labels, colors=colors, ...)

Matplotlib pie chart legend

To add a legend use the plt.legend() function. This adds a legend on top of the plot.

import matplotlib.pyplot as plt

labels = ['Cookies', 'Jellybean', 'Milkshake', 'Cheesecake']
sizes = [38.4, 40.6, 20.7, 10.3]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
patches, texts = plt.pie(sizes, colors=colors, shadow=True, startangle=90)
plt.legend(patches, labels, loc="best")
plt.axis('equal')
plt.tight_layout()
plt.show()

It outputs this plot:

python pie chart python pie chart

While making the plot, don’t forget to call the method .show().

plt.show()

Download All Matplotlib Examples

 

PyQt5 Treeview

PyQt5 (python with qt5 bindings) supports a tree view widget (class QTreeView). In this article we will show how to use the widget.

treeview pyqt5

The image shows a QTreeView widget with data inside it.

Related course:
Create GUI Apps with PyQt5

PyQt5 Treeview Example


The code below will create a treeview using the QTreeView class (Run using Python 3). Data is added to the treeview by code. Explanation of the code is below the code block.


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtGui import QIcon

from PyQt5.QtCore import (QDate, QDateTime, QRegExp, QSortFilterProxyModel, Qt,
QTime)
from PyQt5.QtGui import QStandardItemModel
from PyQt5.QtWidgets import (QApplication, QCheckBox, QComboBox, QGridLayout,
QGroupBox, QHBoxLayout, QLabel, QLineEdit, QTreeView, QVBoxLayout,
QWidget)

class App(QWidget):

FROM, SUBJECT, DATE = range(3)

def __init__(self):
super().__init__()
self.title = 'PyQt5 Treeview Example - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 240
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

self.dataGroupBox = QGroupBox("Inbox")
self.dataView = QTreeView()
self.dataView.setRootIsDecorated(False)
self.dataView.setAlternatingRowColors(True)

dataLayout = QHBoxLayout()
dataLayout.addWidget(self.dataView)
self.dataGroupBox.setLayout(dataLayout)

model = self.createMailModel(self)
self.dataView.setModel(model)
self.addMail(model, '[email protected]ub.com', 'Your Github Donation','03/25/2017 02:05 PM')
self.addMail(model, '[email protected]', 'Github Projects','02/02/2017 03:05 PM')
self.addMail(model, '[email protected]', 'Your Phone Bill','01/01/2017 04:05 PM')

mainLayout = QVBoxLayout()
mainLayout.addWidget(self.dataGroupBox)
self.setLayout(mainLayout)

self.show()

def createMailModel(self,parent):
model = QStandardItemModel(0, 3, parent)
model.setHeaderData(self.FROM, Qt.Horizontal, "From")
model.setHeaderData(self.SUBJECT, Qt.Horizontal, "Subject")
model.setHeaderData(self.DATE, Qt.Horizontal, "Date")
return model

def addMail(self,model, mailFrom, subject, date):
model.insertRow(0)
model.setData(model.index(0, self.FROM), mailFrom)
model.setData(model.index(0, self.SUBJECT), subject)
model.setData(model.index(0, self.DATE), date)

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Treeview Explanation


We create a new tree view object using the line:


self.dataView = QTreeView()

The view is set to have a model,


self.dataView.setModel(model)

Where model is


model = QStandardItemModel(0, 3, parent)
model.setHeaderData(self.FROM, Qt.Horizontal, "From")
model.setHeaderData(self.SUBJECT, Qt.Horizontal, "Subject")
model.setHeaderData(self.DATE, Qt.Horizontal, "Date")

Then we add data using:


model.insertRow(0)
model.setData(model.index(0, self.FROM), mailFrom)
model.setData(model.index(0, self.SUBJECT), subject)
model.setData(model.index(0, self.DATE), date)

Download PyQT5 Examples

Tk window and button

Tk button with onClick event
To create a Tkinter window with a button use the example below. The program enters mainloop() which wait for events (user actions). We define the button which has a callback to the function callback(). master is the root window, the window where your button will appear in.

from Tkinter import *

master = Tk()

def callback():
print "click!"

b = Button(master, text="OK", command=callback)
b.pack()

mainloop()
tk button tk button

Related course

Tk image button
If you want an image button, use the PhotoImage class. We set the size of the window and the miminum size with the functions minsize() and geometry(). Example:

from Tkinter import *

master = Tk()
master.minsize(300,100)
master.geometry("320x100")

def callback():
print "click!"


photo=PhotoImage(file="add.png")
b = Button(master,image=photo, command=callback, height=50, width=150)
b.pack()

mainloop()

Result:

tk image button tk image button

Tk Image button with text label
If you want both an image and text, simply add the parameter compound=LEFT.

from Tkinter import *

master = Tk()
master.minsize(300,100)
master.geometry("320x100")

def callback():
print "click!"


photo=PhotoImage(file="add.png")
b = Button(master,image=photo, text="OK", command=callback, height=50, width=150, compound=LEFT)
b.pack()

mainloop()

Result:

tk button with text and image tk button with text and image

Button location
If you want to place the button on your coordinates do not use the pack() function but instead use the function place(x,y), as shown in the example below:

from Tkinter import *

master = Tk()
master.minsize(300,100)
master.geometry("320x100")

def callback():
print "click!"


photo=PhotoImage(file="add.png")
b = Button(master,image=photo, text="OK", command=callback, height=50, width=150, compound=LEFT)
b.place(x = 20, y = 20)

mainloop()

Result:

tk button location tk button location

If you are new to programming Tkinter, I highly recommend this course.

download tkinter examples

QT4 Messagebox

PyQT4 offers message box functionality using several functions.
Messageboxes included in PyQT4 are: question, warning, error, information, criticial and about box.

Related course: Create GUI Apps with Python PyQt5

PyQt4 mesagebox

The code below will display a message box with two buttons:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Show a message box
result = QMessageBox.question(w, 'Message', "Do you like Python?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

if result == QMessageBox.Yes:
print('Yes.')
else:
print('No.')

# Show window
w.show()

sys.exit(a.exec_())

Result:

qtMessagebox question qtMessagebox question

There are different types of messageboxes that PyQT4 provides.

PyQT4 Warning Box


You can display a warning box using this line of code:

QMessageBox.warning(w, "Message", "Are you sure you want to continue?")

PyQT4 Information box


We can display an information box using QMessageBox.information()

QMessageBox.information(w, "Message", "An information messagebox @ pythonspot.com ")

Result:

QMessageBox Info QMessageBox Info

PyQT4 Critical Box


If something goes wrong in your application you may want to display an error message.

QMessageBox.critical(w, "Message", "No disk space left on device.")



Result:

QMessagebox QMessagebox

PyQT4 About box


We have shown the question box above.

QMessageBox.about(w, "About", "An example messagebox @ pythonspot.com ")



Result:

qt Messagebox qt Messagebox

Download PyQT Code (Bulk Collection)

Python tuple

The tuple data structure is used to store a group of data.  The elements in this group are separated by a comma. Once created, the values of a tuple cannot change.  

Related Course:
Python Programming Bootcamp: Go from zero to hero

Python Tuple


An empty tuple in Python would be defined as:

tuple = ()

A comma is required for a tuple with one item:

tuple = (3,)

The comma for one item may be counter intuitive,  but without the comma for a single item, you cannot access the element.  For multiple items, you do not have to put a comma at the end.  This set is an example:

personInfo = ("Diana", 32, "New York")

The data inside a tuple can be of one or more data types such as text and numbers.

Data access


To access the data we can simply use an index. As usual, an index is a number between brackets:

#!/usr/bin/env python

personInfo = ("Diana", 32, "New York")
print(personInfo[0])
print(personInfo[1])

If you want to assign multiple variables at once, you can use tuples:

#!/usr/bin/env python

name,age,country,career = ('Diana',32,'Canada','CompSci')
print(country)

On the right side the tuple is written. Left of the operator  equality operator are the corresponding output variables.

Append to a tuple in Python


If you have an existing tuple, you can append to it with the + operator.  You can only append a tuple to an existing tuple.

#!/usr/bin/env python

x = (3,4,5,6)
x = x + (1,2,3)
print(x)

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

Python dictionaries

A dictionary can be thought of as an unordered set of key: value pairs.

A pair of braces creates an empty dictionary: {}.  Each element can maps to a certain value.  An integer or string can be used for the index. Dictonaries do not have an order.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Dictionary example


Let us make a simple dictionary:

#!/usr/bin/python

words = {}
words["Hello"] = "Bonjour"
words["Yes"] = "Oui"
words["No"] = "Non"
words["Bye"] = "Au Revoir"

print(words["Hello"])
print(words["No"])

Output:


Bonjour
Non

We are by no means limited to single word defintions in the value part. A demonstration:

#!/usr/bin/python

dict = {}
dict['Ford'] = "Car"
dict['Python'] = "The Python Programming Language"
dict[2] = "This sentence is stored here."

print(dict['Ford'])
print(dict['Python'])
print(dict[2])

Output:


Car
The Python Programming Language
This sentence is stored here.

Manipulating the dictionary


We can manipulate the data stored in a dictionairy after declaration.  This is shown in the example below:

#!/usr/bin/python

words = {}
words["Hello"] = "Bonjour"
words["Yes"] = "Oui"
words["No"] = "Non"
words["Bye"] = "Au Revoir"

print(words) # print key-pairs.
del words["Yes"] # delete a key-pair.
print(words) # print key-pairs.
words["Yes"] = "Oui!" # add new key-pair.
print(words) # print key-pairs.

Output:


{'Yes': 'Oui', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
{'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
{'Yes': 'Oui!', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

How to Read a File in Python

You have seen various types of data holders before: integers, strings, lists. But so far, we have not discussed how to read or write files.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Read file

The Python programming language provides the ability to work with files using open().

Python programming treats some files as text files, where lines are separated by newline characters \n. You can open regular files with the paramater r.

Other files are considered binary and can be handled in a way that is similar to the C programming language. They need to be opened with the parameters rb.

read file into string

This is a sample program that shows how to read data from a file.

The file needs to be in the same directory as the program, if not you need to specify a path.

Create python script. Open editor of your choice and create new python script. Then paste the following code.

f = open("file.txt","r")
lines = f.readlines()
print(lines)

The read method readlines() reads all the contents of a file into a string.

Save the file with name example.py and run it.

read file line by line

To output line by line, you can use a for loop. The lines may include a new line character \n, that is why you can output using endl="".

f = open("filename.txt","r")
lines = f.readlines()

for line in lines:
print(line, end="")

Another option is to remove the newline characters with the replace() method.

f = open("test.py","r")
lines = f.readlines()

for line in lines:
line = line.replace("\n","")
print(line)

read file with keyword

The with keyword can be used to read files too. This automatically closes your file.

#!/usr/bin/env python

# Define a filename.
filename = "bestand.py"

# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
content = f.readlines()

# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'.
for line in content:
print(line),

The first part of the code will read the file content. All of the lines read will be stored in the variable content. The second part will iterate over every line in the variable contents.

If you do not want to read the newline characters ‘\n’, you can change the statement f.readlines() to this:

content = f.read().splitlines()

Resulting in this code:

#!/usr/bin/env python

# Define a filename.
filename = "bestand.py"

# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
content = f.read().splitlines()

# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'.
for line in content:
print(line)

While the codes above work, we should always test if the file we want to open exists.  We will test first if the file does not exist, if it does it will read the file else return an error. As in the code below:

#!/usr/bin/env python
import os.path

# Define a filename.
filename = "bestand.py"

if not os.path.isfile(filename):
print('File does not exist.')
else:
# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
content = f.read().splitlines()

# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'.
for line in content:
print(line)

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

Encapsulation

In an object oriented python program, you can restrict access to methods and variables. This can prevent the data from being modified by accident and is known as encapsulation.   Let’s start with an example.

Related Courses:
Python Programming Bootcamp: Go from zero to hero

Private methods

encapsulation encapsulation. Restricted accesss to methods or variables

We create a class Car which has two methods:  drive() and updateSoftware().  When a car object is created, it will call the private methods __updateSoftware().  

This function cannot be called on the object directly, only from within the class.

#!/usr/bin/env python

class Car:

def __init__(self):
self.__updateSoftware()

def drive(self):
print('driving')

def __updateSoftware(self):
print('updating software')

redcar = Car()
redcar.drive()
#redcar.__updateSoftware() not accesible from object.

This program will output:

updating software
driving

Encapsulation prevents from accessing accidentally, but not intentionally.

The private attributes and methods are not really hidden, they’re renamed adding _Car” in the beginning of their name.

The method can actually be called using redcar._Car__updateSoftware()

Private variables

encapsulation-example Class with private variables

Variables can be private which can be useful on many occasions. A private variable can only be changed within a class method and not outside of the class.

Objects can hold crucial data for your application and you do not want that data to be changeable from anywhere in the code.
An example:

#!/usr/bin/env python

class Car:

__maxspeed = 0
__name = ""

def __init__(self):
self.__maxspeed = 200
self.__name = "Supercar"

def drive(self):
print('driving. maxspeed ' + str(self.__maxspeed))

redcar = Car()
redcar.drive()
redcar.__maxspeed = 10 # will not change variable because its private
redcar.drive()

If you want to change the value of a private variable, a setter method is used.  This is simply a method that sets the value of a private variable.

#!/usr/bin/env python

class Car:

__maxspeed = 0
__name = ""

def __init__(self):
self.__maxspeed = 200
self.__name = "Supercar"

def drive(self):
print('driving. maxspeed ' + str(self.__maxspeed))

def setMaxSpeed(self,speed):
self.__maxspeed = speed

redcar = Car()
redcar.drive()
redcar.setMaxSpeed(320)
redcar.drive()

Why would you create them? Because some of the private values you may want to change after creation of the object while others may not need to be changed at all.

Python Encapsulation


To summarize, in Python there are:

Other programming languages have protected class methods too, but Python does not.

Encapsulation gives you more control over the degree of coupling in your code, it allows a class to change its implementation without affecting other parts of the code.

If you are new to Python programming, I highly recommend this book.

Download Exercises

Understanding Class Inheritance in Python 3

Classes can inherit functionality of other classes. If an object is created using a class that inherits from a superclass, the object will contain the methods of both the class and the superclass. The same holds true for variables of both the superclass and the class that inherits from the super class.

Python supports inheritance from multiple classes, unlike other popular programming languages.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Intoduction


We define a basic class named User:

Type Description
public methods Accessible from anywhere
private methods Accessible only in their own class. starts with two underscores
public variables Accessible from anywhere
private variables Accesible only in their own class or by a method if defined. starts with two underscores
class User:
name = ""

def __init__(self, name):
self.name = name

def printName(self):
print("Name = " + self.name)

brian = User("brian")
brian.printName()

This creates one instance called brian which outputs its given name. We create another class called Programmer.

class Programmer(User):

def __init__(self, name):
self.name = name

def doPython(self):
print("Programming Python")

This looks very much like a standard class except than User is given in the parameters. This means all functionality of the class User is accessible in the Programmer class.

Inheritance example


Full example of Python inheritance:

class User:
name = ""

def __init__(self, name):
self.name = name

def printName(self):
print("Name = " + self.name)

class Programmer(User):
def __init__(self, name):
self.name = name

def doPython(self):
print("Programming Python")

brian = User("brian")
brian.printName()

diana = Programmer("Diana")
diana.printName()
diana.doPython()

The output:

Name  = brian
Name = Diana
Programming Python

Brian is an instance of User and can only access the method printName. Diana is an instance of Programmer, a class with inheritance from User, and can access both the methods in Programmer and User.

If you are new to Python programming, I highly recommend this book.

Download Exercises

Polymorphism

Sometimes an object comes in many types or forms. If we have a button, there are many different draw outputs (round button, check button, square button, button with image) but they do share the same logic: onClick().  We access them using the same method . This idea is called Polymorphism.

Polymorphism is based on the greek words Poly (many) and morphism (forms).  We will create a structure that can take or use many forms of objects.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Polymorphism with a function:


We create two classes:  Bear and Dog, both  can make a distinct sound.  We then make two instances and call their action using the same method.

class Bear(object):
def sound(self):
print("Groarrr")

class Dog(object):
def sound(self):
print("Woof woof!")

def makeSound(animalType):
animalType.sound()


bearObj = Bear()
dogObj = Dog()

makeSound(bearObj)
makeSound(dogObj)

Output:

Groarrr
Woof woof!

Polymorphism with abstract class (most commonly used)

polymorphism example Polymorphism visual.
Abstract structure is defined in Document class.

If you create an editor you may not know in advance what type of documents a user will open (pdf format or word format?).  

Wouldn’t it be great to acess them like this,  instead of having 20 types for every document?

for document in documents:
print document.name + ': ' + document.show()

To do so, we create an abstract class called document.  This class does not have any implementation but defines the structure (in form of functions) that all forms must have.   If we define the function show()  then both the PdfDocument and WordDocument must have the show() function. Full code:

class Document:
def __init__(self, name):
self.name = name

def show(self):
raise NotImplementedError("Subclass must implement abstract method")

class Pdf(Document):
def show(self):
return 'Show pdf contents!'

class Word(Document):
def show(self):
return 'Show word contents!'

documents = [Pdf('Document1'),
Pdf('Document2'),
Word('Document3')]

for document in documents:
print document.name + ': ' + document.show()

Output:

Document1: Show pdf contents!
Document2: Show pdf contents!
Document3: Show word contents!

We have an abstract access point (document) to many types of objects (pdf,word) that follow the same structure.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Polymorphism example

polymorphism-example Structure in abstract class, implementation in other classes

Another example would be to have an abstract class Car which holds the structure  drive() and stop().  

We define two objects Sportscar and Truck, both are a form of Car. In pseudo code what we will do is:

class Car:
def drive abstract, no implementation.
def stop abstract, no implementation.

class Sportscar(Car):
def drive: implementation of sportscar
def stop: implementation of sportscar

class Truck(Car):
def drive: implementation of truck
def stop: implementation of truck


Then we can access any type of car and  call the functionality without taking further into account if the form is Sportscar or Truck.  Full code:

class Car:
def __init__(self, name):
self.name = name

def drive(self):
raise NotImplementedError("Subclass must implement abstract method")

def stop(self):
raise NotImplementedError("Subclass must implement abstract method")

class Sportscar(Car):
def drive(self):
return 'Sportscar driving!'

def stop(self):
return 'Sportscar braking!'

class Truck(Car):
def drive(self):
return 'Truck driving slowly because heavily loaded.'

def stop(self):
return 'Truck braking!'

cars = [Truck('Bananatruck'),
Truck('Orangetruck'),
Sportscar('Z3')]

for car in cars:
print car.name + ': ' + car.drive()

Output:

Bananatruck: Truck driving slowly because heavily loaded.
Orangetruck: Truck driving slowly because heavily loaded.
Z3: Sportscar driving!

If you are new to Python programming, I highly recommend this book.

Download Exercises

Factory method

We may not always know what kind of objects we want to create in advance.
Some objects can be created only at execution time after a user requests so.

Examples when you may use a factory method:


  • A user may click on a certain button that creates an object.

  • A user may create several new documents of different types.

  • If a user starts a webbrowser, the browser does not know in advance how many tabs (where every tab is an object) will be opened.


Related Course:
Python Programming Bootcamp: Go from zero to hero

Factory method pattern


To deal with this we can use the factory method pattern.
The idea is to have one function, the factory, that takes an input string and outputs an object.

obj = Car.factory("Racecar")
obj.drive()

Key fact: a factory method returns (new) objects.

The type of object depends on the type of input string you specify. This technique could make your program more easily extensible also. A new programmer could easily add functionality by adding a new string and class, without having to read all of the source code.

Factory method example


The example below demonstrates a factory method. The factory method (named factory) returns a new object of either type depending on the input.


class Car(object):

def factory(type):
if type == "Racecar":
return Racecar()
if type == "Van":
return Van()

factory = staticmethod(factory)

class Racecar(Car):
def drive(self):
print("Racecar driving.")

class Van(Car):
def drive(self):
print("Van driving.")

# Create object using factory.
obj = Car.factory("Racecar")
obj.drive()

Output:

Racecar driving.

If you are new to Python programming, I highly recommend this book.

Download Exercises

Recursion and Recursive Functions in Python

In English there are many examples of recursion:

  • "To understand recursion, you must first understand recursion",
  • "A human is someone whose mother is human".

You might wonder, what does this have to do with programming?

You may want to split a complex problem into several smaller ones. You are already familiar with loops or iterations. In some situations recursion may be a better solution.

In Python, a function is recursive if it calls itself and has a termination condition. Why a termination condition? To stop the function from calling itself ad infinity.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Recursion examples


Recursion in with a list
Let’s start with a very basic example: adding all numbers in a list.  Without recursion, this could be:

#!/usr/bin/env python

def sum(list):
sum = 0

# Add every number in the list.
for i in range(0, len(list)):
sum = sum + list[i]

# Return the sum.
return sum

print(sum([5,7,3,8,10]))

Where we simply call the sum function, the function adds every element to the variable sum and returns.  To do this recursively:

#!/usr/bin/env python

def sum(list):
if len(list) == 1:
return list[0]
else:
return list[0] + sum(list[1:])

print(sum([5,7,3,8,10]))

If the length of the list is one it returns the list (the termination condition). Else, it returns the element and a call to the function sum() minus one element of the list. If all calls are executed, it returns reaches the termination condition and returns the answer.

Factorial with recursion
The mathematical definition of factorial is:  n! = n * (n-1)!, if n > 1 and f(1) = 1. Example:   3! = 3 x 2 x 1 = 6.  We can implement this in Python using a recursive function:

#!/usr/bin/env python

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

print(factorial(3))

When calling the factorial function n = 3.  Thus it returns n * factorial(n-1).  This process will continue until n = 1. If n==1 is reached, it will return the result.

Limitations of recursions


Everytime a function calls itself and stores some memory. Thus, a recursive function could hold much more memory than a traditional function. Python stops the function calls after a depth of 1000 calls. If you run this example:

#!/usr/bin/env python

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

print(factorial(3000))

You will get the error:

RuntimeError: maximum recursion depth exceeded

In other programming languages, your program could simply crash. You can resolve this by modifying the number of recursion calls such as:

#!/usr/bin/env python
import sys

sys.setrecursionlimit(5000)

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

print(factorial(3000))

but keep in mind there is still a limit to the input for the factorial function. For this reason, you should use recursion wisely. As you learned now for the factorial problem, a recursive function is not the best solution.  For other problems such as traversing a directory, recursion may be a good solution.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Introduction to Logging

Python logging


We can track events in a software application, this is known as logging. Let’s start with a simple example, we will log a warning message.

As opposed to just printing the errors, logging can be configured to disable output or save to a file. This is a big advantage to simple printing the errors.

Related course
Python Programming Bootcamp: Go from zero to hero

Logging example

import logging

# print a log message to the console.
logging.warning('This is a warning!')

This will output:

WARNING:root:This is a warning!

We can easily output to a file:

import logging

logging.basicConfig(filename='program.log',level=logging.DEBUG)
logging.warning('An example message.')
logging.warning('Another message')

The importance of a log message depends on the severity.

Level of severity


The logger module has several levels of severity. We set the level of severity using this line of code:

logging.basicConfig(level=logging.DEBUG)

These are the levels of severity:

The default logging level is warning, which implies that other messages are ignored. If you want to print debug or info log messages you have to change the logging level like so:

Type Description
DEBUG Information only for problem diagnostics
INFO The program is running as expected
WARNING Indicate something went wrong
ERROR The software will no longer be able to function
CRITICAL Very serious error
import logging

logging.basicConfig(level=logging.DEBUG)
logging.debug('Debug message')

Time in log


You can enable time for logging using this line of code:

logging.basicConfig(format='%(asctime)s %(message)s')

An example below:

import logging

logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
logging.info('Logging app started')
logging.warning('An example logging message.')
logging.warning('Another log message')

Output:

2015-06-25 23:24:01,153 Logging app started
2015-06-25 23:24:01,153 An example message.
2015-06-25 23:24:01,153 Another message

Related course
Python Programming Bootcamp: Go from zero to hero

Python Subprocess

The subprocess module enables you to start new applications from your Python program. How cool is that?

Related Course:
Python Programming Bootcamp: Go from zero to hero

Start a process in Python:


You can start a process in Python using the Popen function call. The program below starts the unix program ‘cat’ and the second parameter is the argument. This is equivalent to ‘cat test.py’.  You can start any program with any parameter.

#!/usr/bin/env python

from subprocess import Popen, PIPE

process = Popen(['cat', 'test.py'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
print stdout

The process.communicate() call reads input and output from the process.  stdout is the process output. stderr will be written only if an error occurs.  If you want to wait for the program to finish you can call Popen.wait().

Subprocess call():


Subprocess has a method call() which can be used to start a program. The parameter is a list of which the first argument must be the program name. The full definition is:

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
# Run the command described by args.
# Wait for command to complete, then return the returncode attribute.

In the example below the full command would be “ls -l”

#!/usr/bin/env python

import subprocess
subprocess.call(["ls", "-l"])

Save process output (stdout)


We can get the output of a program and store it in a string directly using check_output. The method is defined as:

 subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
# Run command with arguments and return its output as a byte string.

Example usage:

#!/usr/bin/env python
import subprocess

s = subprocess.check_output(["echo", "Hello World!"])
print("s = " + s)

If you are new to Python programming, I highly recommend this book.

Threading and threads

Sets in Python - collection of unique elements

Sets in Python


A set in Python is a collection of objects. Sets are available in Python 2.4 and newer versions. They are different from lists or tuples in that they are modeled after sets in mathematics.

Related course
Python Programming Bootcamp: Go from zero to hero

Set example
To create a set, we use the set() function.

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
print(x)

If we add the same item element multiple times, they are removed. A set may not contain the same element multiple times.

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram", "Postcard"])
print(x)

Simple notation


If you use Python version 2.6 or a later version, you can use a simplified notation:

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
print(x)

y = {"Postcard","Radio","Telegram"}
print(y)

Set Methods


Clear elements from set
To remove all elements from sets:

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.clear()
print(x)

Add elements to a set
To add elements to a set:

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.add("Telephone")
print(x)

Remove elements to a set
To remove elements to a set:

!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.remove("Radio")
print(x)

Difference between two sets
To find the difference between two sets use:

#!/usr/bin/env python
x = set(["Postcard", "Radio", "Telegram"])
y = set(["Radio","Television"])
print( x.difference(y) )
print( y.difference(x) )

Be aware that x.difference(y) is different from y.difference(x).

Subset
To test if a set is a subset use:

#!/usr/bin/env python

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.issubset(y) )<b>
</b>

Super-set
To test if a set is a super-set:

#!/usr/bin/env python

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.issuperset(y) )

Intersection
To test for intersection, use:

#!/usr/bin/env python

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.intersection(y) )

Related course
Python Programming Bootcamp: Go from zero to hero

Android Development in Python with QPython

Python Web Development Frameworks

Introduction


pythonQuote

Web apps are often created using a framework. Frameworks make it easier to develop web apps that are scalable, reliable and maintainable. It avoids recreating the same code over and over again.
Common features are:

  • URL Routing
  • Output templates
  • Database management
  • Session management
  • Security against common attacks

A framework may offer some or all of these features.

For example, the Flask web application framework does not have database support and you would need a separate module to use a database. The Django web application framework supports databases by default.

Related course: Create Web Apps with Python Flask

Python Hosting

To run your app on the web, you will need hosting. Unless you want to do hosting yourself, you need a party to host.
Hosting servers:

Why use a web framework?

As you are doing web development, you want to avoid spending time on programming things that have already been solved. On the other hand, if you are an experienced web developer a web framework may not offer everything you need.

What Python web frameworks exist?


Django and Flask are the most popular web frameworks. However, you may want to evaluate the frameworks. An overview:


The most popular python web application framework is Django, followed by Flask.

python web development # of projects on Github mentioning a framework.

Django

Django is the most used Python web framework. It takes care of many things so you can focus on the web app development. Sites built withDjango have dealt with high traffic spikes such as 50 thousands hits per second.

Database access is achieved through an Object-relational mapper: You define your data models in Python and Django deals with the actual database management systems (SQL). However, if you need to you can write your own SQL Queries with Django. URL routing is supported by Django. It encourages beautiful URL design such as ending without .php or .asp.

Features:

  • Object-relational mapper
  • URLs routing and views
  • Template engine
  • Forms
  • Authentication
  • Admin
  • Internationalization
  • Security

If you want to know more about Django, read here.

Did you know the websites of NASA, Bitbucket and Pinterest were made with Django?

Related course: Django Web Developer Course

Flask

flask-logo
Flask is a Python micro framework which is modular by design. The framework is intended to build web apps. Flask does not have a specific database system or ORM system. If you want to use a database, you’ll have to use extensions. Flask is often combined with SQLAlchemy for database use.

Flask is very easy to get running, a minimal app would be:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
return 'Hello World!'

if __name__ == '__main__':
app.run()

The framework supports URL routing, template (using Jinja2), session management and has some out of the box security.
Features:

  • URL Routing and views
  • Template engine
  • Session management
  • Logging

If you want to know more about Flask, read here.

Related course: Create Web Apps with Python Flask

Django Getting started

Python finite state machine

Binary numbers and logical operators

Flask getting started: Hello World

In this tutorial you’ll learn how to build a web app with Python.

We’ll use a micro-framework called Flask. It has a small core but is extensible with many plugins such as SQLAlchemy, Babel, CouchDB, MongoDB etc.

Some Flask example apps are:

Related course
Python Flask: Make Web Apps with Python

  • easy to use.
  • built in development server and debugger
  • integrated unit testing support
  • RESTful request dispatching
  • uses Jinja2 templating
  • support for secure cookies (client side sessions)
  • 100% WSGI 1.0 compliant
  • Unicode based
  • extensively documented

Download Flask Examples

Installing Flask

Install Flask using the command below:

pip install Flask

Flask hello world app


Create a file called hello.py


from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
return "Hello World!"

if __name__ == "__main__":
app.run()

Finally run the web app using this command:

$ python hello.py
* Running on http://localhost:5000/

Open http://localhost:5000/ in your webbrowser, and “Hello World!” should appear.

Download Flask Examples

Jinja2 Template engine

Flask and great looking charts using Chart.js

Flask Web App with Python (beginners tutorial)

MySQL with Python

HTTP download file with Python

The urllib2 module can be used to download data from the web (network resource access). This data can be a file, a website or whatever you want Python to download. The module supports HTTP, HTTPS, FTP and several other protocols.

In this article you will learn how to download data from the web using Python.

Related course

Download text


To download a plain text file use this code:

import urllib2
response = urllib2.urlopen('https://wordpress.org/plugins/about/readme.txt')
data = response.read()
print(data)

We get a response object using the urllib2.urlopen() method, where the parameter is the link. All of the file contents is received using the response.read() method call. After calling this, we have the file data in a Python variable of type string.

Download HTML


This will request the html code from a website. It will output everything to the screen.

import urllib2
response = urllib2.urlopen('https://en.wikipedia.org/')
html = response.read()
print html

Download file using Python


You can save the data to disk very easily after downloading the file:

import urllib2
response = urllib2.urlopen('https://wordpress.org/plugins/about/readme.txt')
data = response.read()

# Write data to file
filename = "test.txt"
file_ = open(filename, 'w')
file_.write(data)
file_.close()

The first part of the code downloads the file contents into the variable data:


import urllib2
response = urllib2.urlopen('https://wordpress.org/plugins/about/readme.txt')
data = response.read()

The second part stores it into a file (this file does not need to have the same filename)


# Write data to file
filename = "test.txt"
file_ = open(filename, 'w')
file_.write(data)
file_.close()

The ‘w’ parameter creates the file (or overwrites if it exists). You can read more about writing files here.

Related course

wxPython file dialog

Nearly every desktop application that can open one or more files has a file dialog.

An open file dialog may seem like a very complicated window to create: it contains buttons, locations, labels and many more widgets. Moreover, the appearance of this open file dialog looks different on every platform: Mac OS, Windows and so on.

Related course: Creating GUI Applications with wxPython

The wxPython module comes with open file dialogs, which can be created with a few functions calls.

wxPythonOpenFile wxPython Open File Dialog

wxPython file dialog


The example below creates a file dialog with a native appearance using wxPython:

#!/usr/bin/python

import wx

def onButton(event):
print "Button pressed."

app = wx.App()

frame = wx.Frame(None, -1, 'win.py')
frame.SetDimensions(0,0,200,50)

# Create open file dialog
openFileDialog = wx.FileDialog(frame, "Open", "", "",
"Python files (*.py)|*.py",
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)

openFileDialog.ShowModal()
print(openFileDialog.GetPath())
openFileDialog.Destroy()

To create a file dialog with wxPython we can simply call wx.FileDialog().
The definition of this method is: (parent, message, defaultDir, defaultFile, wildcard, style, pos)
We call this method with the arguments:


wx.FileDialog(frame, "Open", "", "","Python files (*.py)|*.py",wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)

(no default dir or default file is specified).

The method showModal() displays the window:


openFileDialog.ShowModal()

The command openFileDialog.GetPath() returns the full path to the file if one is selected.

Related course: Creating GUI Applications with wxPython

wxPython input dialog

Input dialogs let your user give you feedback or input. They appear in desktop applications once in a while.

wxPython supports input dialogs, they are included with the framework.
A typical wxPython dialog may look like:

wx input input dialog made with wxPython

Related course: Creating GUI Applications with wxPython

wxPython input dialog


The example code below creates an input dialog with wxPython:

#!/usr/bin/python

import wx

def onButton(event):
print "Button pressed."

app = wx.App()

frame = wx.Frame(None, -1, 'win.py')
frame.SetDimensions(0,0,200,50)

# Create text input
dlg = wx.TextEntryDialog(frame, 'Enter some text','Text Entry')
dlg.SetValue("Default")
if dlg.ShowModal() == wx.ID_OK:
print('You entered: %s\n' % dlg.GetValue())
dlg.Destroy()

A wxPython textbox can be added to a window using the function:


wx.TextEntryDialog(frame, 'Enter some text','Text Entry')

Where the first argument is the frame, the second argument is the label and the last argument is the window title.

The function below displays the dialog and waits for a user to press one of the buttons:


dlg.ShowModal()

You can get the button pressed by picking one of these:


wx.OK
wx.CANCEL

(the result is either one of these)

After input is been given, you can get the input text using dlg.GetValue() function.

Related course: Creating GUI Applications with wxPython

Simple text game with Python

In this article we will demonstrate how to create a simple guessing game.
The goal of the game is to guess the right number.

Example
An example run below:

python-text-game Simple text game with Python

You may like
Python Game Development for Beginners

Random number


The user will be asked to guess the random number. We first pick the random number:

from random import randint

x = randint(1,9)

The randint() function will pick a pseudo random number between 1 and 10. Then we have to continue until the correct number is found:

guess = -1

print("Guess the number below 10:")
while guess != x:
guess = int(raw_input("Guess: "))

if guess != x:
print("Wrong guess")
else:
print("Guessed correctly")

Python Guessing Game


The code below starts the game:

from random import randint

x = randint(1,9)
guess = -1

print "Guess the number below 10:"
while guess != x:
guess = int(raw_input("Guess: "))

if guess != x:
print("Wrong guess")
else:
print("Guessed correctly")

An example run:

Guess the number below 10:
Guess: 3
Wrong guess
Guess: 6
Wrong guess
..


You may like
Python Game Development for Beginners

Python network sockets programming tutorial

JSON encoding and decoding with Python

Menu with PyQt4

PyQT Menu pythonspot PyQT Menu

PyQt4 menus appear in the top of the window bar. A menu gives the user control over the application and is often location in the top of the window.

The QMainWindow class creates the main application window. This class has a method named menuBar() which adds the title bar.

Menus can be added to the title bar using addMenu(). Inside each menu you can add a command using the addAction method.

Related course:

PyQt4 menubar


This code will add a menu to your qt4 app:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QMainWindow()

# Set window size.
w.resize(320, 240)

# Set window title
w.setWindowTitle("Hello World!")

# Create main menu
mainMenu = w.menuBar()
mainMenu.setNativeMenuBar(False)
fileMenu = mainMenu.addMenu('&amp;File')

# Add exit button
exitButton = QAction(QIcon('exit24.png'), 'Exit', w)
exitButton.setShortcut('Ctrl+Q')
exitButton.setStatusTip('Exit application')
exitButton.triggered.connect(w.close)
fileMenu.addAction(exitButton)

# Show window
w.show()

sys.exit(a.exec_())

Download PyQT Code (Bulk Collection)

QT4 Widgets

We have various widgets that we can access with PyQT. Including:

  • Textbox
  • Combobox
  • Calendar
For more widgets we suggest using the GUI creation tool covered in the next tutorial.

Related course: Create GUI Apps with PyQt5

Textbox widget
Input fields are present in nearly every application. In PyQT4 an input field can be created using the QLineEdit() function.

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QMainWindow()

# Set window size.
w.resize(320, 100)

# Set window title
w.setWindowTitle("PyQT Python Widget!")

# Create textbox
textbox = QLineEdit(w)
textbox.move(20, 20)
textbox.resize(280,40)

# Show window
w.show()

sys.exit(a.exec_())
qt textbox qt textbox

Combobox
A combobox can be used to select an item from a list.

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QMainWindow()

# Set window size.
w.resize(320, 100)

# Set window title
w.setWindowTitle("PyQT Python Widget!")

# Create combobox
combo = QComboBox(w)
combo.addItem("Python")
combo.addItem("Perl")
combo.addItem("Java")
combo.addItem("C++")
combo.move(20,20)

# Show window
w.show()

sys.exit(a.exec_())
qt combobox qt combobox

Calendar widget
The PyQT4 library has a calendar widget, you can create it using the QCalendarWidget() call.

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QMainWindow()

# Set window size.
w.resize(320, 240)

# Set window title
w.setWindowTitle("PyQT Python Widget!")

# Create calendar
cal = QCalendarWidget(w)
cal.setGridVisible(True)
cal.move(0, 0)
cal.resize(320,240)

# Show window
w.show()

sys.exit(a.exec_())

Result:

calendar qt calendar qt

Download PyQT Code (Bulk Collection)

QT4 Table

We can show a table using the QTableWidget, part of the PyQt module.  We set the title, row count, column count and add the data.

Related course:

Qt4 Table example


An example below:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

Result:

PyQT Table PyQt Table

QTableWidget labels


You can set the header using the setHorizontalHeaderLabels() function. The same applies for vertical labels. A demonstration below:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set label
table.setHorizontalHeaderLabels(QString("H1;H2;").split(";"))
table.setVerticalHeaderLabels(QString("V1;V2;V3;V4").split(";"))

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

Result:

PyQT Table PyQT Table

QTableWidget click events


We can detect cell clicks using this procedure, first add a function:

# on click function
table.cellClicked.connect(cellClick)



Then define the function:

def cellClick(row,col):
print "Click on " + str(row) + " " + str(col)

The Python programming language starts counting with 0, so when you press on (1,1) you will see (0,0). Full code to detect table clicks:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def cellClick(row,col):
print "Click on " + str(row) + " " + str(col)

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set label
table.setHorizontalHeaderLabels(QString("H1;H2;").split(";"))
table.setVerticalHeaderLabels(QString("V1;V2;V3;V4").split(";"))

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# on click function
table.cellClicked.connect(cellClick)

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

If you want to show the cell/row numbers in a non-programmer way use this instead:

def cellClick(row,col):
print "Click on " + str(row+1) + " " + str(col+1)



Tooltip text


We can set tooltip (mouse over) text using the method. If you set tooltips on non-existing columns you will get an error.

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

def main():
app = QApplication(sys.argv)
table = QTableWidget()
tableItem = QTableWidgetItem()

# initiate table
table.setWindowTitle("QTableWidget Example @pythonspot.com")
table.resize(400, 250)
table.setRowCount(4)
table.setColumnCount(2)

# set label
table.setHorizontalHeaderLabels(QString("H1;H2;").split(";"))
table.setVerticalHeaderLabels(QString("V1;V2;V3;V4").split(";"))

# set data
table.setItem(0,0, QTableWidgetItem("Item (1,1)"))
table.setItem(0,1, QTableWidgetItem("Item (1,2)"))
table.setItem(1,0, QTableWidgetItem("Item (2,1)"))
table.setItem(1,1, QTableWidgetItem("Item (2,2)"))
table.setItem(2,0, QTableWidgetItem("Item (3,1)"))
table.setItem(2,1, QTableWidgetItem("Item (3,2)"))
table.setItem(3,0, QTableWidgetItem("Item (4,1)"))
table.setItem(3,1, QTableWidgetItem("Item (4,2)"))

# tooltip text
table.horizontalHeaderItem(0).setToolTip("Column 1 ")
table.horizontalHeaderItem(1).setToolTip("Column 2 ")

# show table
table.show()
return app.exec_()

if __name__ == '__main__':
main()

Result:

PyQT Table tooltips PyQT Table tooltips

Download PyQT Code (Bulk Collection)

QT4 Tabs

Tabs are very useful in graphical applications. They appear in webbrowsers, text editors and any other apps.  To create a tabbed window, you need to call the  QTabWidget()  function.  Every tab is a QWidget() which you have seen before.  You can connect the QWidgets with the QTabWidget with the function:

tabs.addTab(tab1,"Tab 1")

where the first parameter is the tab object and the second the name that appears on the screen. We added some buttons to the first tab (QWidget).

Related course:

Example code:

from PyQt4 import QtGui
from PyQt4 import QtCore
import sys

def main():

app = QtGui.QApplication(sys.argv)
tabs = QtGui.QTabWidget()

# Create tabs
tab1 = QtGui.QWidget()
tab2 = QtGui.QWidget()
tab3 = QtGui.QWidget()
tab4 = QtGui.QWidget()

# Resize width and height
tabs.resize(250, 150)

# Set layout of first tab
vBoxlayout = QtGui.QVBoxLayout()
pushButton1 = QtGui.QPushButton("Start")
pushButton2 = QtGui.QPushButton("Settings")
pushButton3 = QtGui.QPushButton("Stop")
vBoxlayout.addWidget(pushButton1)
vBoxlayout.addWidget(pushButton2)
vBoxlayout.addWidget(pushButton3)
tab1.setLayout(vBoxlayout)

# Add tabs
tabs.addTab(tab1,"Tab 1")
tabs.addTab(tab2,"Tab 2")
tabs.addTab(tab3,"Tab 3")
tabs.addTab(tab4,"Tab 4")

# Set title and show
tabs.setWindowTitle('PyQt QTabWidget @ pythonspot.com')
tabs.show()

sys.exit(app.exec_())

if __name__ == '__main__':
main()

Result:

PyQT Tabs PyQT Tabs

Download PyQT Code (Bulk Collection)


12