Advanced Python
Advanced Python
More on Exception
import urllib
url =
“http://www-personal.buseco.monash.edu.au/~hyndman/TSDL/ecology1/hopedale.dat"
web_page = urllib.urlopen(url)
for line in web_page:
line = line.strip() #why?
print (line )
input_file.close()
File I/O
r - read
a - append
● The tell() method tells you the current position within the file; in other words, the next
read or write will occur at that many bytes from the beginning of the file.
● The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the reference
position from where the bytes are to be moved.
● If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end
of the file would be taken as the reference position.
File I/O
import os.path
path = '/Users/dionysialemonaki/python_project'
check_file = os.path.isfile(path)
print(check_file)
File I/O
import os
os.remove("text2.txt")
os.mkdir("newdir")
os.chdir("newdir")
os.chdir("rmdir")
os.getcwd()
Zipping / Unzipping ….
Python Database Connectivity
pip install mysql-connector-python
import mysql.connector
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "yourusername",
password = "your_password"
print(mydb)
Python Database Connectivity
# Creating an instance of 'cursor' class # which is used to execute the 'SQL'
# statements in 'Python'
cursor = mydb.cursor()
cursor = mydb.cursor()
# Show database
cursor.execute("SHOW DATABASE")
for x in cursor:
print(x)
cursor.execute("SHOW TABLES")
for x in cursor:
print(x)
Python Database Connectivity
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #creating a new database
8. cur.execute("create database PythonDB2")
9. #getting the list of all the databases which will now include the new database PythonDB
10. dbs = cur.execute("show databases")
11. except:
12. myconn.rollback()
13. for x in cur:
14. print(x)
Python Database Connectivity
1. mport mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6. try:
7. #Reading the Employee data
8. cur.execute("select * from Employee")
9. #fetching the rows from the cursor object
10. result = cur.fetchall()
11. #printing the result
12. for x in result:
13. print(x);
14. except:
15. myconn.rollback()
16. myconn.close()
https://www.geeksforgeeks.org/connect-to-mysql-using-pymysql-in-p
ython/
https://www.tutorialspoint.com/python3/python_database_access.htm
Data Binding
● Some widgets (like text entry widgets, radio buttons and so on) can be connected directly to
application variables by using special options: variable, textvariable, onvalue, offvalue, and
value.
● This connection works both ways: if the variable changes for any reason, the widget it's
connected to will be updated to reflect the new value. These Tkinter control variables are used
like regular Python variables to keep certain values.
● It's not possible to hand over a regular Python variable to a widget through a variable or
textvariable option.
● The only kinds of variables for which this works are variables defined in the Tkinter module.
Data Binding
pack()
grid()
place(x,y)
ttk
Note that ttk stands for Tk themed. Therefore, Tk themed widgets are the same as ttk widgets
The tkinter.ttk module contains all the new ttk widgets. It’s a good practice to always use themed widgets whenever they’re available.
The following statements import the classic and the new Tk themed widgets:
import tkinter as tk
● Button
● Checkbutton
● Entry
● Frame
● Label
● LabelFrame
● Menubutton
● PanedWindow
● Radiobutton
● Scale
● Scrollbar
● Spinbox
● Combobox
● Notebook
● Progressbar
● Separator
● Sizegrip
● Treeview
List Box
Select mode
The selectmode option determines how many you can select and how the mouse drags will affect the items:
● tk.BROWSE – allows a single selection. If you select an item and drag it to a different line, the selection
will follow the mouse. This is the default.
● tk.EXTENDED – select any adjacent group of items at once by clicking the first item and dragging to the
last line.
● tk.SINGLE – allow you to select one line and you cannot drag the mouse.
● tk.MULTIPLE – select any number of lines at once. Clicking on any line toggles whether it is selected or
not.
messagebox
To cover all of these scenarios, you can use various functions from the tkinter.messagebox module:
showinfo(title, message)
showerror(title, message)
showwarrning(title, message)
Regular Expressions
x = re.search("The", txt)
print(x)
The search() function searches the string for a match, and returns a
Match object if there is a match. If there is more than one match, only the
first occurrence of the match will be returned
import re
txt = "The rain in Spain"
x = re.split("\s", txt) OR x = re.split("\s", txt,1)
print(x)
The split() function returns a list where the string has been split at each
match. You can control the number of occurrences by specifying the
maxsplit parameter:
import re
txt = "The rain in Spain"
x = re.sub("in", "out", txt)
#additional parameter to control max substitutions
print(x)
The sub() function replaces the matches with the text of your choice
The Match object has properties and methods used to
retrieve information about the search, and the result:
.span() returns a tuple containing the start-, and end
positions of the match.
.string returns the string passed into the function
.group() returns the part of the string where there
was a match
import re
if match:
else:
The 'r' at the start of the pattern string designates a python "raw" string which passes through backslashes
without change which is very handy for regular expressions
Framework
https://www.w3schools.com/django/django_intro.php
● What is Django?
● Django is a Python framework that makes it easier to
create web sites using Python.
● Django emphasizes reusability of components, also referred
to as DRY (Don't Repeat Yourself), and comes with ready-
to-use features like login system, database connection and
CRUD operations (Create Read Update Delete).
● Django is especially helpful for database driven websites.
Django
● Loosely Coupled − Django aims to make each element of its stack independent of the
others.
● Less Coding − Less code so in turn a quick development.
● Don't Repeat Yourself (DRY) − Everything should be developed only in exactly one place
instead of repeating it again and again.
● Fast Development − Django's philosophy is to do all it can to facilitate hyper-fast
development.
● Clean Design − Django strictly maintains a clean design throughout its own code and
makes it easy to follow best web-development practices.
Django
Advantages of Django
Here are few advantages of using Django which can be listed out here −
● Object-Relational Mapping (ORM) Support − Django provides a bridge between the
data model and the database engine, and supports a large set of database systems
including MySQL, Oracle, Postgres, etc. Django also supports NoSQL database through
Django-nonrel fork. For now, the only NoSQL databases supported are MongoDB and
google app engine.
Advantages of Django
Here are few advantages of using Django which can be listed out here −
● Framework Support − Django has built-in support for Ajax, RSS, Caching and various
other frameworks.
● Model
● The model provides data from the database.
● In Django, the data is delivered as an Object
Relational Mapping (ORM),
● The models are usually located in a file called
models.py.
Django
● View
● A view is a function or method that takes http
requests as arguments, imports the relevant
model(s), and finds out what data to send to the
template, and returns the final result.
● The views are usually located in a file called
views.py.
Django
● Template
● A template is a file where you describe how the
result should be represented.
● Templates are often .html files, with HTML code
describing the layout of a web page, but it can also
be in other file formats to present other results, but
we will concentrate on .html files.
● The templates of an application is located in a folder
named templates.
Django
● URLs
● Django also provides a way to navigate around the
different pages in a website.
● When a user requests a URL, Django decides which
view it will send it to.
● This is done in a file called urls.py.
Django
When you have installed Django and created your first Django web
application, and the browser requests the URL, this is basically what
happens:
1. Django receives the URL, checks the urls.py file, and calls the view
that matches the URL.
2. The view, located in views.py, checks for relevant models.
3. The models are imported from the models.py file.
4. The view then sends the data to a specified template in the template
folder.
5. The template contains HTML and Django tags, and with the data it
returns finished HTML content back to the browser.
Django
When you have installed Django and created your first Django web
application, and the browser requests the URL, this is basically what
happens:
1. Django receives the URL, checks the urls.py file, and calls the view
that matches the URL.
2. The view, located in views.py, checks for relevant models.
3. The models are imported from the models.py file.
4. The view then sends the data to a specified template in the template
folder.
5. The template contains HTML and Django tags, and with the data it
returns finished HTML content back to the browser.
Django
1. Installing django
2. Creating virtual environment
3. Creating project
Django
What is an App?
An app is a web application that has a specific meaning in your project, like a home page, a contact form, or a
members database.
In this tutorial we will create an app that allows us to list and register members in a database.
But first, let's just create a simple Django app that displays "Hello World!".
<<Execute the exercise given in w3schools about django framework under django upto creating templates>>
Pandas
● https://www.w3schools.com/python/pandas/pandas_getting_started.asp
● https://pandas.pydata.org/docs/getting_started/intro_tutorials/index.html
● https://www.learndatasci.com/tutorials/python-pandas-tutorial-complete-
introduction-for-beginners/
● https://sparkbyexamples.com/pandas/
Data Visualization
Most of the Matplotlib utilities lies under the pyplot submodule, and are
usually imported under the plt alias:
W3schools matplotlib
https://jovian.com/aryab936/matplotlib-case-study