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 Courses:

Download Python

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

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

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 Courses:

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

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 courses

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)

Functions

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:
Complete Python Bootcamp: Go from zero to hero in Python

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

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 courses

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.

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> 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.

 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.

Related course
The course below is all about data visualization:

Bar chart 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

More on bar charts
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

Download All Matplotlib Examples

 

Posts navigation

1 2 3 4 8 9 10