0% found this document useful (0 votes)
8 views

Advanced Python

python new

Uploaded by

Rohit Kurdiya
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Advanced Python

python new

Uploaded by

Rohit Kurdiya
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

Advanced Python

More on Exception

● The error implies a problem that mostly arises due to the


shortage of system resources. On the other hand, the exceptions
occur during runtime and compile time.
● Errors are unrecoverable, Exceptions are routine
● Three types of exceptions - Checked, Error & Runtime
● Checked Exception - an exception that programmer wants to deal
with - raise
● Runtime exceptions - due to wrong user inputs
● Error - Unforeseen exceptions due to system related issues
File I/O

input_file = open(" …...txt", "r")


for line in input_file:
line = line.strip() #why?
print (line )
input_file.close()
File I/O

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

with open("sample.txt", "r") as f :


print(f.name)
print(f.closed)
print(f.mode)
File I/O

● In the above approaches, every time the file is opened it is


needed to be closed explicitly.
● If one forgets to close the file, it may introduce several bugs in
the code, i.e. many changes in files do not go into effect until
the file is properly closed.
● To prevent this with statement can be used.
● The with the statement itself ensures proper acquisition and
release of resources.
File I/O

r - read

w - write b - binary + - both reading+writing

a - append

r, rb, r+, rb+


w, wb, w+, wb+
a, ab, a+, ab+
File I/O

read( ) = read all contents


read(n) = read n bytes
readlines( ) = read all lines
readlines(n) = read n bytes
File I/O

● 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.rename( "test1.txt", "test2.txt" )

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

# Creating connection object

mydb = mysql.connector.connect(

host = "localhost",

user = "yourusername",

password = "your_password"

)# Printing the connection object

print(mydb)
Python Database Connectivity
# Creating an instance of 'cursor' class # which is used to execute the 'SQL'

# statements in 'Python'

cursor = mydb.cursor()

# Creating a database with a name vesasc execute() method # is used to compile


a SQL statement # below statement is used to create

cursor.execute("CREATE DATABASE ves")


Python Database Connectivity

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

They are declared like this:


x = StringVar() # Holds a string; default value ""
x = IntVar() # Holds an integer; default value 0
x = DoubleVar() # Holds a float; default value 0.0
x = BooleanVar() # Holds a boolean, returns 0 for False and 1 for True
To read the current value of such a variable, call the method get(). The value of such a variable
can be changed with the set() method.
Anchor Property
Adding Elements

pack()
grid()
place(x,y)
ttk

Tkinter has two generations of widgets:

● The old classic tk widgets. Tkinter introduced them in 1991.


● The newer themed ttk widgets added in 2007 with Tk 8.5. The newer Tk themed widgets replace many (but not all) classic widgets.

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

from tkinter import ttk


ttk
The following ttk widgets replace the Tkinkter widgets with the same names:

● Button
● Checkbutton
● Entry
● Frame
● Label
● LabelFrame
● Menubutton
● PanedWindow
● Radiobutton
● Scale
● Scrollbar
● Spinbox

And the following widgets are new and specific to ttk:

● 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() – notify that an operation completed successfully.


● showerror() – notify that an operation hasn’t completed due to an error.
● showwarrning() – notify that an operation completed but something didn’t behave as expected.

showinfo(title, message)

showerror(title, message)

showwarrning(title, message)
Regular Expressions

● A RegEx, or Regular Expression, is a sequence of characters


that forms a search pattern.
● import re
● Findall - Returns a list containing all matches
● Search - Returns a Match object if there is a match anywhere in
the string
● Split - Returns a list where the string has been split at each
match
● Sub - Replaces one or many matches with a string
import re
txt = "The rain in Spain"
x = re.findall("in", txt)
print(x)
The findall() function returns a list containing all matches.
import re

txt = "The rain in Spain"

x = re.search("The", txt)

print(x)

print("your search item:", x.start())

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

str = 'an example word:cat!!'

match = re.search(r'word:\w\w\w', str)

if match:

print('found at', match.start()) ## 'found word:cat'

else:

print('did not find')

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

● Why C has main function?


● Why Library Functions?
● Library VS Framework
○ Reusable Code VS Reusable Design
○ Programmer calls code of designer X Designer call’s
programmer’s code
○ Programmer decide flow X Designers decide flow
○ https://www.interviewbit.com/blog/framework-vs-library/
Django

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

Django comes with the following design philosophies −

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

● Multilingual Support − Django supports multilingual websites through its built-in


internationalization system. So you can develop your website, which would support
multiple languages.
Django

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.

● Administration GUI − Django provides a nice ready-to-use user interface for


administrative activities.

● Development Environment − Django comes with a lightweight web server to facilitate


end-to-end application development and testing.
Django

How does Django Work?


Django follows the MVT design pattern (Model View Template).
● Model - The data you want to present, usually data from a
database.
● View - A request handler that returns the relevant template
and content - based on the request from the user.
● Template - A text file (like an HTML file) containing the
layout of the web page, with logic on how to display the
data.
Django

● 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

● Pandas is a Python library used for working with data


sets.
● Pandas is an open-source library that is made mainly for working
with relational or labeled data both easily and intuitively.
● The name "Pandas" has a reference to both "Panel
Data", and "Python Data Analysis" and was created by
Wes McKinney in 2008.
● This library is built on top of the NumPy library. Pandas is fast
and it has high performance & productivity for users.
Pandas

● Pandas allows us to analyze big data and make


conclusions based on statistical theories.
● It provides various data structures and operations for
manipulating numerical data and time series.
● It has functions for analyzing, cleaning, exploring, and
manipulating data.
● The data produced by Pandas are often used as input for
plotting functions of Matplotlib, statistical analysis in SciPy,
and machine learning algorithms in Scikit-learn.Hence it is
highly popular in Data Science
Pandas - Advantages

● Fast and efficient for manipulating and analyzing data.


● Data from different file objects can be loaded.
● Easy handling of missing data (represented as NaN) in floating
point as well as non-floating point data
● Size mutability: columns can be inserted and deleted from
DataFrame and higher dimensional objects
● Data set merging and joining.
● Flexible reshaping and pivoting of data sets
● Provides time-series functionality.
● Powerful group by functionality for performing split-apply-combine
operations on data sets.
Pandas - How to use

● pip install pandas


● import pandas as pd
● Pandas generally provide two data structures for manipulating data -Series
& DataFrame
● Pandas Series is a one-dimensional labeled array capable of holding
data of any type (integer, string, float, python objects, etc.). The axis
labels are collectively called indexes.
● Pandas DataFrame is a two-dimensional size-mutable, potentially
heterogeneous tabular data structure with labeled axes (rows and
columns).
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

● Data visualization is the graphical representation of information and data.


● By using visual elements like charts, graphs, and maps, data visualization tools
provide an accessible way to see and understand trends, outliers, and patterns in
data.
● Additionally, it provides an excellent way for employees or business owners to
present data to non-technical audiences without confusion.
Data Visualization
Mathplotlib
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in
Python. One of the greatest benefits of visualization is that it allows us visual access to huge
amounts of data in easily digestible visuals.

● Matplotlib is a low level graph plotting library in python that serves as a


visualization utility.
● Matplotlib was created by John D. Hunter.
● Matplotlib is open source and we can use it freely.
● Create publication quality plots.
● Make interactive figures that can zoom, pan, update.
● Customize visual style and layout.
● Export to many file formats.
● Embed in JupyterLab and Graphical User Interfaces.
● Use a rich array of third-party packages built on Matplotlib.
Mathplotlib
● pip install matplotlib
● import matplotlib

Most of the Matplotlib utilities lies under the pyplot submodule, and are
usually imported under the plt alias:

import matplotlib.pyplot as plt

W3schools matplotlib

How it can help?

https://jovian.com/aryab936/matplotlib-case-study

You might also like