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”]
Run Python code
A python program should be save as a file with a .py extension.
Try this code:
print("Hello World!") |
Expected output:
Hello World! |
If you are using the interpreter use:
python program.py |
python if string equals

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" |
To get text from keyboard:
|
If you use an old Python version (2.x), you need to use:
|
To test your version:
python –version
String Comparison
To test if two strings are equal use the equality operator (==).
#!/usr/bin/python |
To test if two strings are not equal use the inequality operator (!=)
#!/usr/bin/python |
If you are new to Python programming, I highly recommend this book.
variables in python

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 |
You can output them to the screen using the print() function.
x = 1 |
Python supports arithmetic operations like addition (+), multiplication (*), division (/) and subtractions (-).
#!/usr/bin/env python |
User input
Python 3
Use the input() function to get text input, convert to a number using int() or float().
#!/usr/bin/env python |
Python 2 (old version)
You can also ask the user for input using the raw_input function:
#!/usr/bin/env python |
If you are new to Python programming, I highly recommend this book.
python function
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): |
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 |
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 |
Output:
|
If you are new to Python programming, I highly recommend this book.
dbms in python
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 PythonPyton Database

Data is retrieved from a database system using the SQL language.
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

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 |
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 |
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')") |
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:

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 |
This will output the data in the table Users.
sqlite> SELECT * FROM Users; |
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.

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.

This GUI can be used to modify the records (data) in the table and to add new tables.
Related course: Master SQL Databases with PythonThe 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 |
We can use those queries in a Python program:
#!/usr/bin/python |
This will output all data in the Users table from the database:
$ python get.py |
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:

Jobs:

To create these tables, you can do that by hand in the GUI or use the script below:
# -*- coding: utf-8 -*- |
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 |
It should output:
$ python get2.py |
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() |
Output:

Matplotlib charts can be horizontal, to create a horizontal bar chart:
import matplotlib.pyplot as plt; plt.rcdefaults() |
Output:

Bar chart comparison
You can compare two data series using this Matplotlib code:
import numpy as np |
Output:

Stacked bar chart
The example below creates a stacked bar chart with Matplotlib. Stacked bar plots show diffrent groups together.
# load matplotlib |
Output:
Download All Matplotlib Examples
pie chart python
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 |
The above code has the following output:

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 |
It outputs this plot:

While making the plot, don’t forget to call the method .show().
plt.show() |
Download All Matplotlib Examples
pyqt treeview
PyQt5 (python with qt5 bindings) supports a tree view widget (class QTreeView). In this article we will show how to use the widget.
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.
For layout, we use a qvboxlayout.
|
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:
|
The view is set to have a model,
|
Where model is
|
Then we add data using:
|
tkinter 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 * |

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 * |
Result:

Tk Image button with text label
If you want both an image and text, simply add the parameter compound=LEFT.
from Tkinter import * |
Result:

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 * |
Result:

If you are new to programming Tkinter, I highly recommend this course.
qt message box
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 |
Result:

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:

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:

PyQT4 About box
We have shown the question box above.
QMessageBox.about(w, "About", "An example messagebox @ pythonspot.com ") |
Result:

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 |
If you want to assign multiple variables at once, you can use tuples:
#!/usr/bin/env python |
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 |
If you are new to Python programming, I highly recommend this book.
python dictionary
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 |
Output:
|
We are by no means limited to single word defintions in the value part. A demonstration:
#!/usr/bin/python |
Output:
|
Manipulating the dictionary
We can manipulate the data stored in a dictionairy after declaration. This is shown in the example below:
#!/usr/bin/python |
Output:
|
If you are new to Python programming, I highly recommend this book.
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") |
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") |
Another option is to remove the newline characters with the replace() method.
f = open("test.py","r") |
read file with keyword
The with keyword can be used to read files too. This automatically closes your file.
#!/usr/bin/env python |
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 |
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 |
If you are new to Python programming, I highly recommend this book.
encapsulation in python
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

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 |
This program will output:
updating software |
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

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 |
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 |
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:
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: |
This creates one instance called brian which outputs its given name. We create another class called Programmer.
class Programmer(User): |
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: |
The output:
Name = brian |
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.
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): |
Output:
Groarrr |
Polymorphism with abstract class (most commonly used)

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: |
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: |
Output:
Document1: Show pdf 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

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: |
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: |
Output:
Bananatruck: Truck driving slowly because heavily loaded. |
If you are new to Python programming, I highly recommend this book.
python factory
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") |
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.
|
Output:
Racecar driving. |
If you are new to Python programming, I highly recommend this book.
recursion in python w3schools
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 |
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 |
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 |
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 |
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 |
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
python 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 |
This will output:
WARNING:root:This is a warning! |
We can easily output to a file:
import logging |
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:
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 |
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 |
Output:
2015-06-25 23:24:01,153 Logging app started |
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 |
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) |
In the example below the full command would be “ls -l”
#!/usr/bin/env python |
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) |
Example usage:
#!/usr/bin/env python |
If you are new to Python programming, I highly recommend this book.
python threading
python create set
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 |
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 |
Simple notation
If you use Python version 2.6 or a later version, you can use a simplified notation:
#!/usr/bin/env python |
Set Methods
Clear elements from set
To remove all elements from sets:
#!/usr/bin/env python |
Add elements to a set
To add elements to a set:
#!/usr/bin/env python |
Remove elements to a set
To remove elements to a set:
!/usr/bin/env python |
Difference between two sets
To find the difference between two sets use:
#!/usr/bin/env python |
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 |
Super-set
To test if a set is a super-set:
#!/usr/bin/env python |
Intersection
To test for intersection, use:
#!/usr/bin/env python |
Related course
Python Programming Bootcamp: Go from zero to hero
qpython
python web development
Introduction

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.

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.
Related course: Django Web Developer Course
Flask
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 |
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 state machine
python binary number
flask 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:
- flaskr — a microblog
- minitwit — a twitter clone
- flask website — static pages + mailinglist archives
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
Installing Flask
Install Flask using the command below:
pip install Flask |
Flask hello world app
Create a file called hello.py
|
Finally run the web app using this command:
$ python hello.py |
Open http://localhost:5000/ in your webbrowser, and “Hello World!” should appear.
jinja2 tutorial
chart flask
flask
python mysql
python download file from url
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 courseDownload text
To download a plain text file use this code:
import urllib2 |
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 |
Download file using Python
You can save the data to disk very easily after downloading the file:
import urllib2 |
The first part of the code downloads the file contents into the variable data:
|
The second part stores it into a file (this file does not need to have the same filename)
|
The ‘w’ parameter creates the file (or overwrites if it exists). You can read more about writing files here.
Related coursewx.filedialog
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.

wxPython file dialog
The example below creates a file dialog with a native appearance using wxPython:
#!/usr/bin/python |
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:
|
(no default dir or default file is specified).
The method showModal() displays the window:
|
The command openFileDialog.GetPath() returns the full path to the file if one is selected.
Related course: Creating GUI Applications with wxPython
python dialog box input
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:

Related course: Creating GUI Applications with wxPython
wxPython input dialog
The example code below creates an input dialog with wxPython:
#!/usr/bin/python |
A wxPython textbox can be added to a window using the function:
|
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:
|
You can get the button pressed by picking one of these:
|
(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
python text game
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:

You may like
Simple games with Python
Random number
The user will be asked to guess the random number. We first pick the random number:
from random import randint |
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 |
Python Guessing Game
The code below starts the game:
from random import randint |
An example run:
Guess the number below 10: |
You may like
Simple games with Python
python socket
python json
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 |
Download PyQT Code (Bulk Collection)
pyqt widgets
We have various widgets that we can access with PyQT. Including:
- Textbox
- Combobox
- Calendar
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 |

You can add a qt textbox to display text.
Combobox
A combobox can be used to select an item from a list.
#! /usr/bin/env python |

Calendar widget
The PyQT4 library has a calendar widget, you can create it using the QCalendarWidget() call.
#! /usr/bin/env python |
Result:

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 * |
Result:

QTableWidget labels
You can set the header using the setHorizontalHeaderLabels() function. The same applies for vertical labels. A qt4 demonstration below:
from PyQt4.QtGui import * |
Result:

Note: These days you can use pyqt5 to create a pyqt table.
QTableWidget click events
We can detect cell clicks using this procedure, first add a function:
# on click function |
Then define the function:
def cellClick(row,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 * |
If you want to show the cell/row numbers in a non-programmer way use this instead:
def cellClick(row,col): |
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 * |
Result:

Download PyQT Code (Bulk Collection)
pyqt 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:
The code uses the qtabwidget to display tabs in.
from PyQt4 import QtGui |
Result:
